file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.4.18;
// BlackBox2.0 - Secure Ether & Token Storage
// Rinkeby test contract: 0x21ED89693fF7e91c757DbDD9Aa30448415aa8156
// token interface
contract Token {
function balanceOf(address _owner) constant public returns (uint balance);
function allowance(address _user, address _spender) constant public returns (uint amount);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
}
// owned by contract creator
contract Owned {
address public owner = msg.sender;
bool public restricted = true;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// restrict external contract calls
modifier onlyCompliant {
if (restricted) require(tx.origin == msg.sender);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
function changeRestrictions() public onlyOwner {
restricted = !restricted;
}
function kill() public onlyOwner {
selfdestruct(owner);
}
}
// helper functions for hashing
contract Encoder {
enum Algorithm { sha, keccak }
/// @dev generateProofSet - function for off-chain proof derivation
/// @param seed Secret used to secure the proof-set
/// @param caller Address of the caller, or account that verifies the proof-set
/// @param receiver Address of the encoded recepient
/// @param tokenAddress Address of the token to transfer from the caller
/// @param algorithm Hash algorithm to use for generating proof-set
function generateProofSet(
string seed,
address caller,
address receiver,
address tokenAddress,
Algorithm algorithm
) pure public returns(bytes32 hash, bytes32 operator, bytes32 check, address check_receiver, address check_token) {
(hash, operator, check) = _escrow(seed, caller, receiver, tokenAddress, algorithm);
bytes32 key = hash_seed(seed, algorithm);
check_receiver = address(hash_data(key, algorithm)^operator);
if (check_receiver == 0) check_receiver = caller;
if (tokenAddress != 0) check_token = address(check^key^blind(receiver, algorithm));
}
// internal function for generating the proof-set
function _escrow(
string seed,
address caller,
address receiver,
address tokenAddress,
Algorithm algorithm
) pure internal returns(bytes32 index, bytes32 operator, bytes32 check) {
require(caller != receiver && caller != 0);
bytes32 x = hash_seed(seed, algorithm);
if (algorithm == Algorithm.sha) {
index = sha256(x, caller);
operator = sha256(x)^bytes32(receiver);
check = x^sha256(receiver);
} else {
index = keccak256(x, caller);
operator = keccak256(x)^bytes32(receiver);
check = x^keccak256(receiver);
}
if (tokenAddress != 0) {
check ^= bytes32(tokenAddress);
}
}
// internal function for hashing the seed
function hash_seed(
string seed,
Algorithm algorithm
) pure internal returns(bytes32) {
if (algorithm == Algorithm.sha) return sha256(seed);
else return keccak256(seed);
}
// internal function for hashing bytes
function hash_data(
bytes32 key,
Algorithm algorithm
) pure internal returns(bytes32) {
if (algorithm == Algorithm.sha) return sha256(key);
else return keccak256(key);
}
// internal function for hashing an address
function blind(
address addr,
Algorithm algorithm
) pure internal returns(bytes32) {
if (algorithm == Algorithm.sha) return sha256(addr);
else return keccak256(addr);
}
}
contract BlackBox is Owned, Encoder {
// struct of proof set
struct Proof {
uint256 balance;
bytes32 operator;
bytes32 check;
}
// mappings
mapping(bytes32 => Proof) public proofs;
mapping(bytes32 => bool) public used;
mapping(address => uint) private deposits;
// events
event ProofVerified(string _key, address _prover, uint _value);
event Locked(bytes32 _hash, bytes32 _operator, bytes32 _check);
event WithdrawTokens(address _token, address _to, uint _value);
event ClearedDeposit(address _to, uint value);
event TokenTransfer(address _token, address _from, address _to, uint _value);
/// @dev lock - store a proof-set
/// @param _hash Hash Key used to index the proof
/// @param _operator A derived operator to encode the intended recipient
/// @param _check A derived operator to check recipient, or a decode the token address
function lock(
bytes32 _hash,
bytes32 _operator,
bytes32 _check
) public payable {
// protect invalid entries on value transfer
if (msg.value > 0) {
require(_hash != 0 && _operator != 0 && _check != 0);
}
// check existence
require(!used[_hash]);
// lock the ether
proofs[_hash].balance = msg.value;
proofs[_hash].operator = _operator;
proofs[_hash].check = _check;
// track unique keys
used[_hash] = true;
Locked(_hash, _operator, _check);
}
/// @dev unlock - verify a proof to transfer the locked funds
/// @param _seed Secret used to derive the proof set
/// @param _value Optional token value to transfer if the proof-set maps to a token transfer
/// @param _algo Hash algorithm type
function unlock(
string _seed,
uint _value,
Algorithm _algo
) public onlyCompliant {
bytes32 hash = 0;
bytes32 operator = 0;
bytes32 check = 0;
// calculate the proof
(hash, operator, check) = _escrow(_seed, msg.sender, 0, 0, _algo);
require(used[hash]);
// get balance to send to decoded receiver
uint balance = proofs[hash].balance;
address receiver = address(proofs[hash].operator^operator);
address _token = address(proofs[hash].check^hash_seed(_seed, _algo)^blind(receiver, _algo));
delete proofs[hash];
if (receiver == 0) receiver = msg.sender;
// send balance and deposits
clearDeposits(receiver, balance);
ProofVerified(_seed, msg.sender, balance);
// check for token transfer
if (_token != 0) {
Token token = Token(_token);
uint tokenBalance = token.balanceOf(msg.sender);
uint allowance = token.allowance(msg.sender, this);
// check the balance to send to the receiver
if (_value == 0 || _value > tokenBalance) _value = tokenBalance;
if (allowance > 0 && _value > 0) {
if (_value > allowance) _value = allowance;
TokenTransfer(_token, msg.sender, receiver, _value);
require(token.transferFrom(msg.sender, receiver, _value));
}
}
}
/// @dev withdrawTokens - withdraw tokens from contract
/// @param _token Address of token that this contract holds
function withdrawTokens(address _token) public onlyOwner {
Token token = Token(_token);
uint256 value = token.balanceOf(this);
require(token.transfer(msg.sender, value));
WithdrawTokens(_token, msg.sender, value);
}
/// @dev clearDeposits - internal function to send ether
/// @param _for Address of recipient
/// @param _value Value of proof balance
function clearDeposits(address _for, uint _value) internal {
uint deposit = deposits[msg.sender];
if (deposit > 0) delete deposits[msg.sender];
if (deposit + _value > 0) {
if (!_for.send(deposit+_value)) {
require(msg.sender.send(deposit+_value));
}
ClearedDeposit(_for, deposit+_value);
}
}
function allowance(address _token, address _from) public view returns(uint _allowance) {
Token token = Token(_token);
_allowance = token.allowance(_from, this);
}
// store deposits for msg.sender
function() public payable {
require(msg.value > 0);
deposits[msg.sender] += msg.value;
}
} | lock - store a proof-set _hash Hash Key used to index the proof _operator A derived operator to encode the intended recipient _check A derived operator to check recipient, or a decode the token address protect invalid entries on value transfer | function lock(
bytes32 _hash,
bytes32 _operator,
bytes32 _check
) public payable {
if (msg.value > 0) {
require(_hash != 0 && _operator != 0 && _check != 0);
}
proofs[_hash].operator = _operator;
proofs[_hash].check = _check;
Locked(_hash, _operator, _check);
}
| 1,498,954 |
./partial_match/97/0xc2af23aA2A87D916cd989C6f6c48307142abE403/sources/LucaxUtilityToken.sol | Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./ | function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 11,384,467 |
/**
*Submitted for verification at Etherscan.io on 2022-03-30
*/
// SPDX-License-Identifier: MIT
// ................................................................................
// ..........................................................................
// ............8888........................................................
// ..........8::8............888888888888................................
// .......888.........88D~~~~~~~~~~~~88..............................
// ......88........8~~~~~~~~~~~~~~~~~DD............................
// ......................888...~8:~8~~~~~~~~~~~~~~~~~~~~8..........................
// ........................8...888D~~~~~~~~~~~~~~~~~~~~~8..........................
// ........................8.8D~~~~~~~~~~~~~~~~~~~~~~~~~~88........................
// ........................88~~~~~~~~~~~~~~~~~~~~~~~~~~~~88........................
// ........................:8~~~~~~~~~~~~~888888N~~~~~~~~88........................
// ........................8~~~~~~~~..:8888D..:8888D8~:~~8D........................
// ........................8~~~~~~~88................888~~~8.......................
// ........................8~~~~~888..................:8~~~8.......................
// ........................8~~~~~88....:88........88..:88~~8.......................
// ................ ...:8~~~~88D....8 8......8 8..:8~~8.......................
// ............:. .8~~~~8......8 8......8 8..:8~~8.......................
// ............ .8~~~~888....8 8......8 8..:8~~8.......................
// ............ .8~~~~~88....:88~......:88..:88~~8.......................
// ............ .8~~~~~888................:888~~~8.......................
// ........ .8~~~~~~~88..............:88:~~~~8.......................
// ........ .8~~~~~~~~8888888......8888~~~~~~8.......................
// ........:...............8~~~~~~~~~~~8~DDDDDDDDD~~~~~~~~~8.......................
// ........................8~~~~~~~~~~~8~~~~~~~~~~~~~~~~~~~8.......................
// .........................8~~~~~~~~~~8~~~:D8DDDDDD~~~~~88........................
// .........................8888~~~~~~~~8~~~~D8..8D~~~~~888........................
// .........................8===D8D~~~~~8~~~~~~88~~~~~~88..........................
// .........................8==D===888D~8~~~~~~~~~~8888=8..........................
// .........................8==D=======++88++++++++=====8..........................
// ........................88==D=========88=============8..........................
// ......................88==88D=========88============8=88........................
// .....................8=====+8888=====8==========8888====8.......................
// ....................D====888====8888888888888888========88......................
// ..................88===+D8=========+88======++++++88O++==8......................
// .................8?===88==========88=888888888++++++=8====88D...................
// .................8===888=========8===8================88===+8...................
// .................8===8===========8===888========8..8==88===+8...................
// ................8==+88==========8=====88========8..88=88=====8..................
// ................8==+D===========D=====88========88..8=888====8..................
// ................8==+D=========88======88=========+8.8==+8====8..................
// ................8=88=========888======88===============+8====D88................
// ................8=88=========8===88888D8===============+8=====88................
// ................8=88=========8888D8D=D=8===============+8=====88................
// ................8=88=========8=+DDD====================+8=====88................
// ................8=88========8888=======================+8=====88................
// ................8=88========88=========================+8=====88................
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);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/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
* ====
*
* [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);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev 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;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721A] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
uint256 private currentIndex = 0;
uint256 public maxBatchSize = 35;
// 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), "ERC721A: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
address owner = _owners[curr];
if (owner != address(0)) {
return owner;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
// function ownerOf(uint256 tokenId) public view virtual override returns (address) {
// return ownershipOf(tokenId);
// }
/**
* @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 = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721A: 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), "ERC721A: 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 ERC721A 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), "ERC721A: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < currentIndex;
}
/**
* @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), "ERC721A: operator query for nonexistent token");
address owner = ERC721A.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 quantity) internal virtual {
_safeMint(to, quantity, "");
}
/**
* @dev Same as {xref-ERC721A-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
require(!_exists(startTokenId), "ERC721A: token already minted");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
_balances[to] += quantity;
_owners[startTokenId] =to;
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev 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 = ERC721A.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);
_afterTokenTransfer(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(ERC721A.ownerOf(tokenId) == from, "ERC721A: transfer from incorrect owner");
require(to != address(0), "ERC721A: 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;
if(_owners[tokenId+1] == address(0))
_owners[tokenId+1] = from;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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(ERC721A.ownerOf(tokenId), to, tokenId);
}
/**
* @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, "ERC721A: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function getTotalSupply() public view returns(uint256) {
return currentIndex;
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
/**
* @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);
}
}
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since 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. 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;
}
}
}
contract Companions is ERC721A, Ownable
{
using SafeMath for uint256;
IERC721 starContract;
string public baseURI;
string public provenanceHash;
uint256 public maxSupply = 10000;
uint256 public maxBatchAmount = 400;
uint256 public holderMintedAmount;
uint256 public adminMintedAmount;
uint256 public whitelistMintedAmount;
uint256 public publicMintedAmount;
uint256 public whitelistMintPrice = 0.042 ether;
uint256 public publicMintPrice;
uint256 public publicMaxPerTransaction = 10;
uint256 public startingIndexBlock;
uint256 public startingIndex;
bool public holderMintActive = false;
bool public whitelistMintActive = false;
bool public publicMintActive = false;
mapping(uint256 => bool) public usedStarIds;
mapping(uint256 => uint256) public matchStarComp;
mapping(address => bool) public mintedWhitelist;
bytes32 private whitelistRoot;
bytes32 private tieredWhitelistRoot;
/**
* @dev TheSolaVerse: Companions
*/
constructor() ERC721A("The SolaVerse: Companions", "Companion") {}
/**
* @dev Calculate the total amount minted so far.
*/
function totalSupply() public view returns (uint256)
{
return holderMintedAmount.add(adminMintedAmount).add(whitelistMintedAmount).add(publicMintedAmount);
}
/**
* @dev SOLA-STAR holder wallets.
*/
function holderMint(uint256[] memory _ids) public
{
require(holderMintActive, "Holder mint is paused.");
require(_ids.length <= maxBatchAmount, "Can't mint that many.");
for (uint256 i=0; i<_ids.length; i++)
{
require(starContract.ownerOf(_ids[i]) == msg.sender, "You don't own this one.");
require(!usedStarIds[_ids[i]], "This one was already used for minting.");
}
_safeMint(msg.sender, _ids.length);
for (uint256 i=0; i<_ids.length; i++)
{
usedStarIds[_ids[i]] = true;
matchStarComp[_ids[i]] = holderMintedAmount + i;
}
holderMintedAmount += _ids.length;
}
/**
* @dev Whitelisted wallets.
*/
function whitelistMint(bytes32[] memory _proof, uint256 _num_tokens) public payable
{
require(whitelistMintActive, "Whitelist mint is paused.");
require(mintedWhitelist[msg.sender] == false, "Already minted.");
require(msg.value == _num_tokens.mul(whitelistMintPrice), "Insufficient funds.");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_proof, whitelistRoot, leaf), "Invalid proof.");
_safeMint(msg.sender, _num_tokens);
whitelistMintedAmount += _num_tokens;
mintedWhitelist[msg.sender] = true;
}
/**
* @dev Whitelisted wallets with Tiers.
*/
function tieredWhitelistMint(bytes32[] memory _proof, uint256 _num_tokens) public payable
{
require(whitelistMintActive, "Whitelist mint is paused.");
require(mintedWhitelist[msg.sender] == false, "Already minted.");
require(msg.value == _num_tokens.mul(whitelistMintPrice), "Insufficient funds.");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _num_tokens));
require(MerkleProof.verify(_proof, tieredWhitelistRoot, leaf), "Invalid proof.");
_safeMint(msg.sender, _num_tokens);
whitelistMintedAmount += _num_tokens;
mintedWhitelist[msg.sender] = true;
}
/**
* @dev Public mint.
*/
function publicMint(uint256 _num_tokens) public payable
{
require(publicMintActive, "Public mint is paused.");
require(publicMintPrice > 0, "Public mint price not set.");
require(msg.value == publicMintPrice.mul(_num_tokens), "Insufficient funds.");
require(_num_tokens <= publicMaxPerTransaction, "Can't mint that many at once.");
require(totalSupply().add(_num_tokens) <= maxSupply, "Can't mint that many.");
_safeMint(msg.sender, _num_tokens);
publicMintedAmount += _num_tokens;
if (startingIndexBlock == 0 && (totalSupply() == maxSupply))
{
startingIndexBlock = block.number;
}
}
/**
* @dev Admin mint.
*/
function adminMint(address _to, uint256 _num_tokens) public onlyOwner
{
require(_num_tokens <= maxBatchAmount, "Can't mint that many.");
_safeMint(_to, _num_tokens);
adminMintedAmount += _num_tokens;
}
/**
* @dev Link to the SOLA-STAR NFT contract to check ownership during holderMint.
*/
function setStarContract(address _addr) public onlyOwner
{
starContract = IERC721(_addr);
}
/**
* @dev Set the Merkle Root for the Whitelist.
*/
function setWhitelistMerkleRoot(bytes32 _root) public onlyOwner
{
whitelistRoot = _root;
}
/**
* @dev Set the Merkle Root for the Tiered Whitelist.
*/
function setTieredWhitelistMerkleRoot(bytes32 _root) public onlyOwner
{
tieredWhitelistRoot = _root;
}
/**
* @dev Toggle the Holder Mint status.
*/
function toggleHolderMint() public onlyOwner
{
holderMintActive = !holderMintActive;
}
/**
* @dev Toggle the Whitelist Mint status.
*/
function toggleWhitelistMint() public onlyOwner
{
whitelistMintActive = !whitelistMintActive;
}
/**
* @dev Toggle the Public Mint status.
*/
function togglepublicMint() public onlyOwner
{
publicMintActive = !publicMintActive;
}
/**
* @dev Set the cost of the tokens for the public mint.
*/
function setPublicMintPrice(uint256 _price) public onlyOwner
{
publicMintPrice = _price;
}
/**
* @dev Update the BaseURI for the reveals.
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner
{
baseURI = _newBaseURI;
}
/**
* @dev Get the Base URI.
*/
function _baseURI() internal view virtual override returns (string memory)
{
return baseURI;
}
/**
* @dev Finalize starting index.
*/
function finalizeStartingIndex() public onlyOwner
{
require(startingIndex == 0, "Starting index already set.");
require(startingIndexBlock != 0, "Starting index block not set.");
startingIndex = uint256(blockhash(startingIndexBlock)) % maxSupply;
if (block.number.sub(startingIndexBlock) > 255)
{
startingIndex = uint256(blockhash(block.number.sub(1))) % maxSupply;
}
if (startingIndex == 0)
{
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking setting starting index.
*/
function emergencySetStartingIndexBlock() public onlyOwner
{
require(startingIndex == 0, "Starting index already set.");
startingIndexBlock = block.number;
}
/**
* @dev Set provenance once it's calculated.
*
* @param _provenance_hash string memory
*/
function setProvenanceHash(string memory _provenance_hash) public onlyOwner
{
provenanceHash = _provenance_hash;
}
/**
* @dev Withdraw the balance from the contract.
*/
function withdraw() public onlyOwner
{
uint256 balance = address(this).balance;
require(balance > 0, "Balance is 0");
payable(msg.sender).transfer(balance);
}
} | Set the Merkle Root for the Tiered Whitelist./ | function setTieredWhitelistMerkleRoot(bytes32 _root) public onlyOwner
{
tieredWhitelistRoot = _root;
}
| 6,711,482 |
pragma solidity ^0.4.2;
contract XG4KCrowdFunding {
// data structure to hold information about campaign contributors
struct Funder {
address addr;
uint amount;
}
// Campaign data structure
struct Campaign {
address beneficiary;
uint fundingGoal;
uint numFunders;
uint amount;
uint deadline;
mapping (uint => Funder) funders;
}
//Declares a state variable 'numCampaigns'
uint numCampaigns;
//Creates a mapping of Campaign datatypes
mapping (uint => Campaign) campaigns;
//first function sets up a new campaign
function newCampaign(address beneficiary, uint goal, uint deadline) returns (uint campaignID) {
campaignID = numCampaigns++; // campaignID is return variable
Campaign c = campaigns[campaignID]; // assigns reference
c.beneficiary = beneficiary;
c.fundingGoal = goal;
c.deadline = block.number + deadline;
}
//function to contributes to the campaign
function contribute(uint campaignID) {
Campaign c = campaigns[campaignID];
Funder f = c.funders[c.numFunders++];
f.addr = msg.sender;
f.amount = msg.value;
c.amount += f.amount;
}
// checks if the goal or time limit has been reached and ends the campaign
function checkGoalReached(uint campaignID) returns (bool reached) {
Campaign c = campaigns[campaignID];
if (c.amount >= c.fundingGoal){
c.beneficiary.send(c.amount);
clean(campaignID);
return true;
}
if (c.deadline <= block.number){
uint j = 0;
uint n = c.numFunders;
while (j <= n){
c.funders[j].addr.send(c.funders[j].amount);
j++;
}
clean(campaignID);
return true;
}
return false;
}
function clean(uint id) private{
Campaign c = campaigns[id];
uint i = 0;
uint n = c.numFunders;
c.amount = 0;
c.beneficiary = 0;
c.fundingGoal = 0;
c.deadline = 0;
c.numFunders = 0;
while (i <= n){
c.funders[i].addr = 0;
c.funders[i].amount = 0;
i++;
}
}
} | checks if the goal or time limit has been reached and ends the campaign | function checkGoalReached(uint campaignID) returns (bool reached) {
Campaign c = campaigns[campaignID];
if (c.amount >= c.fundingGoal){
c.beneficiary.send(c.amount);
clean(campaignID);
return true;
}
if (c.deadline <= block.number){
uint j = 0;
uint n = c.numFunders;
while (j <= n){
c.funders[j].addr.send(c.funders[j].amount);
j++;
}
clean(campaignID);
return true;
}
return false;
}
| 1,012,844 |
./full_match/11155111/0xef13FaAe57356Caa68e046c69E8Eb533f880C192/sources/contracts/NewContracts/721A(R,PS).sol | Changes the price to mint a token. Only the contract owner can call this function. | function changePrice(uint256 newMintPrice) public onlyOwner {
mintPrice = newMintPrice;
}
| 3,805,622 |
./partial_match/1/0xBA51AAAA95aeEFc1292515b36D86C51dC7877773/sources/src/interfaces/IWellFunction.sol | IWellFunction Defines a relationship between token reserves and LP token supply. Well Functions can contain arbitrary logic, but should be deterministic if expected to be used alongside a Pump. When interacing with a Well or Well Function, always verify that the Well Function is valid./ | interface IWellFunction {
error InvalidJArgument();
function calcReserve(
uint256[] memory reserves,
uint256 j,
uint256 lpTokenSupply,
bytes calldata data
) external view returns (uint256 reserve);
function calcLpTokenSupply(
uint256[] memory reserves,
bytes calldata data
) external view returns (uint256 lpTokenSupply);
function calcLPTokenUnderlying(
uint256 lpTokenAmount,
uint256[] memory reserves,
uint256 lpTokenSupply,
bytes calldata data
) external view returns (uint256[] memory underlyingAmounts);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
| 4,363,059 |
./full_match/5/0x94571FA1995B3052302fd027CC7a3ABAca1Ab358/sources/browser/WXMR.sol | 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 {
require(owner != address(0), "ERC20: approve from 0x0 address");
require(spender != address(0), "ERC20: approve to 0x0 address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 1,904,846 |
./full_match/97/0x5a05f17Da7e3897DC2d03ED616333Fad85607CE6/sources/project_/contracts/HeartBall.sol | Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5.05` (`505 / 10 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the default value returned by this function, unless it's overridden. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}./ | function decimals() public view virtual returns (uint8) {
return 18;
}
| 3,270,134 |
./full_match/5/0x1a147b572DF9ca1d1d78Cfdbaa0375037C8559Ff/sources/src/SmoothlyPool.sol | Register n amount of validators to the pool indexes Validator indexes Backend verifies ownership of the validators This is intended to be called from the front-end, double checking for ownership. Anyone registering unowned validators will lose their staking funds and those will be distributed amongst the pool registrants. | function registerBulk(uint64[] calldata indexes) external payable {
if (msg.value != (STAKE_FEE * indexes.length)) revert NotEnoughEth();
emit Registered(msg.sender, indexes);
}
| 7,066,373 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import './libraries/SafeMath.sol';
import './libraries/Address.sol';
import './libraries/ERC20.sol';
import './libraries/ERC20Capped.sol';
import './libraries/AccessControl.sol';
// XPZ with Governance.
contract XPZToken is ERC20, ERC20Capped, AccessControl {
using SafeMath for uint256;
using Address for address;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
uint256 MAX_SUPPLY = 10000000000 * 10 ** 18;
constructor(address _admin, string memory _name, string memory _symbol)
ERC20(_name, _symbol)
ERC20Capped(MAX_SUPPLY)
public {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
}
function setSupplyCap(uint256 amount) public {
require(amount > 0, "XPZ: Don't be Zero");
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XPZ: DEFAULT_ADMIN_ROLE required');
require(totalSupply() <= amount, "XPZ: cap would be exceeded");
super.setCap(amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_beforeTokenTransfer(address(sender), address(recipient), amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
return super.transferFrom(sender, recipient, amount);
}
function transfer(address to, uint256 amount) public override returns (bool) {
_beforeTokenTransfer(msg.sender, address(to), amount);
_moveDelegates(_delegates[msg.sender], _delegates[to], amount);
return super.transfer(to, amount);
}
function mint(address account, uint256 amount) public {
require(hasRole(MINTER_ROLE, msg.sender), 'XPZ: MINTER_ROLE required');
_beforeTokenTransfer(address(0), account, amount);
_moveDelegates(address(0), _delegates[account], amount);
super._mint(account, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
}
/// @dev Add an account to the minter role. Restricted to admins.
function grantMinterRole(address account) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XPZ: DEFAULT_ADMIN_ROLE required');
grantRole(MINTER_ROLE, account);
}
/// @dev Add an account to the burner role. Restricted to admins.
function grantBurnerRole(address account) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XPZ: DEFAULT_ADMIN_ROLE required');
grantRole(BURNER_ROLE, account);
}
/// @dev Remove an account from the minter role. Restricted to admins.
function revokeMinterRole(address account) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XPZ: DEFAULT_ADMIN_ROLE required');
revokeRole(MINTER_ROLE, account);
}
/// @dev Remove an account from the burner role. Restricted to admins.
function revokeBurnerRole(address account) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XPZ: DEFAULT_ADMIN_ROLE required');
revokeRole(BURNER_ROLE, account);
}
// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "XPZ::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "XPZ::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "XPZ::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "XPZ::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying XPZ (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "XPZ::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// 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.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;
import '../interfaces/IERC20.sol';
import './Context.sol';
import './Address.sol';
import './SafeMath.sol';
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;
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public override view returns (string memory) {
return _name;
}
function decimals() public override view returns (uint8) {
return _decimals;
}
function symbol() public override view returns (string memory) {
return _symbol;
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero')
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'ERC20: mint to the zero address');
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), 'ERC20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance')
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
abstract contract ERC20Capped is ERC20 {
using SafeMath for uint256;
uint256 public _cap;
constructor (uint256 cap_) internal {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
function cap() public view returns (uint256) {
return _cap;
}
function setCap(uint256 cap_) internal {
_cap = cap_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./EnumerableSet.sol";
import "./Address.sol";
import "./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.6.12;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the 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;
/**
* @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(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
| Remove an account from the minter role. Restricted to admins. | function revokeMinterRole(address account) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XPZ: DEFAULT_ADMIN_ROLE required');
revokeRole(MINTER_ROLE, account);
}
| 10,013,548 |
pragma solidity ^0.4.24;
import "zeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "./IronHandsInterface.sol";
import "./HourglassInterface.sol";
contract LeadHands is Ownable, ERC721Token {
/**
* Modifiers
*/
/**
* The tokens from the source cannot be transfered.
*/
modifier notSource(address aContract) {
require(aContract != address(source));
_;
}
/**
* Only if this person owns the token or is approved
*/
modifier ownerOrApproved(address _operator, uint256 _tokenId) {
require(isApprovedOrOwner(_operator, _tokenId));
_;
}
/**
* Only if the contract has a positive balance
*/
modifier hasBalance() {
require(address(this).balance > 10);
_;
}
/*
* Only if we can mint that many bonds, and they sent enough to buy a single bond
*/
modifier canMint(uint256 amount){
require(amount > 3000000 && (revenue == 0 || amount <= totalPurchasableBonds()));
if(bondValue > 0){
require(amount >= bondValue);
}
_;
}
/**
* Events
*/
event BondCreated(uint256 amount, address depositer, uint256 bondId);
event Payout(uint256 amount, address creditor, uint256 bondId);
event BondPaidOut(uint256 bondId);
event BondDestroyed(uint256 paid, uint256 owed, address deserter, uint256 bondId);
event Revenue(uint256 amount, address revenueSource);
event Donation(uint256 amount, address donator);
/**
* Structs
*/
struct Participant {
address etherAddress;
uint256 payout;
uint256 tokens;
}
/**
* Storage variables
*/
//Total ETH revenue over the lifetime of the contract
uint256 revenue;
//Total ETH received from dividends
uint256 dividends;
//Total ETH donated to the contract
uint256 donations;
//The percent to return to depositers. 100 for 0%, 200 to double, etc.
uint256 public multiplier;
//Where in the line we are with creditors
uint256 public payoutOrder = 0;
//How much is owed to people
uint256 public backlog = 0;
//Number of Participants
uint256 public participantsOwed = 0;
//The creditor line
Participant[] public participants;
//How much each person is owed
mapping(address => uint256) public creditRemaining;
//What we will be buying
HourglassInterface source;
//IronHands, the other revenue source
IronHandsInterface ironHands;
//tokenURI prefix which will have the tokenId appended to it
string myTokenURIPrefix;
//Bond value per bond, or 0 for user sized bonds.
uint256 bondValue;
//Amount of inflation to allow, or 0 for unlimited inflation
uint256 inflationMultiplier;
/**
* Constructor
*/
constructor(uint256 myBondValue, uint256 myInflationMultipler, uint256 multiplierPercent, address sourceAddress, address ironHandsAddress, string name, string symbol, string tokenURIPrefix) public ERC721Token(name, symbol) {
multiplier = multiplierPercent;
source = HourglassInterface(sourceAddress);
ironHands = IronHandsInterface(ironHandsAddress);
myTokenURIPrefix = tokenURIPrefix;
bondValue = myBondValue;
inflationMultiplier = myInflationMultipler;
}
/**
* Deposit ETH to get in line to be credited back the multiplier as a percent,
* Add that ETH to the pool, then pay out who we owe and buy more tokens.
*/
function purchaseBond() payable canMint(msg.value) public returns (uint256[]){
//A single bond is fixed at bond value, or 0 for user defined value on buy
uint256 amountPerBond = bondValue == 0 ? msg.value : bondValue;
//The amount they have deposited
uint256 remainder = msg.value;
//The issued bonds
uint256[] memory issuedBonds = new uint256[](0);
//counter for storing the bonds in the issuedBonds array
uint256 issuedBondsIndex = 0;
//while we still have money to spend
while(remainder >= amountPerBond){
remainder -= bondValue;
//Compute how much to pay them
uint256 amountCredited = bondValue.mul(multiplier).div(100);
//Compute how much we're going to invest in each opportunity
uint256 tokens = invest(bondValue);
//Get in line to be paid back.
participants.push(Participant(msg.sender, amountCredited, tokens));
//Increase the backlog by the amount owed
backlog += amountCredited;
//Increase the number of participants owed
participantsOwed++;
//Increase the amount owed to this address
creditRemaining[msg.sender] += amountCredited;
//Give them the token
_mint(msg.sender, participants.length-1);
//Add it to the list of bonds they bought
issuedBonds[issuedBondsIndex] = participants.length-1;
//increment the issuedBondsIndex counter
issuedBondsIndex++;
//Emit a deposit event.
emit BondCreated(bondValue, msg.sender, participants.length-1);
}
//If they sent in more than the bond value
if(remainder > 0){
//Send them back the portion they are owed.
msg.sender.transfer(remainder);
}
//Do the internal payout loop
internalPayout();
//Tell them what bonds were issued to them
return issuedBonds;
}
/**
* Take 50% of the money and spend it on tokens, which will pay dividends later.
* Take the other 50%, and use it to pay off depositors.
*/
function payout() public {
//Take everything in the pool
uint256 existingBalance = address(this).balance;
//It needs to be something worth splitting up
require(existingBalance > 10);
invest(existingBalance);
//Pay people out
internalPayout();
}
/**
* Withdraw and payout in one transactions
*/
function withdrawAndPayout() public {
//if we have dividends
if(myDividends() > 0){
//withdraw them
withdraw();
}
//payout everyone we can
payout();
}
/**
* Sells the tokens your investment bought, giving you whatever it received in doing so, and canceling your future payout.
* Calling this with a position you own in line with forefit that future payout as well as 50% of your initial deposit.
* This is here in response to people not being able to "get their money out early". Now you can, but at a very high cost.
*/
function exit(uint256 _tokenId) ownerOrApproved(msg.sender, _tokenId) public {
require(participants[_tokenId].tokens > 0 && participants[_tokenId].payout > 0);
//Withdraw dividends first
if(myDividends() > 0){
withdraw();
}
//Lock divs so not used to pay seller
uint256 lockedFunds = address(this).balance;
//Get tokens for this postion
uint256 tokensToSell = participants[_tokenId].tokens;
//Get the amount the are owed on this postion
uint256 owedAmount = participants[_tokenId].payout;
//Set tokens for this position to 0
participants[_tokenId].tokens = 0;
//Set amount owed on this position to 0
participants[_tokenId].payout = 0;
//Sell particpant's tokens
source.sell(tokensToSell);
//get the money out
withdraw();
//remove divs from funds to be paid
uint256 availableFunds = address(this).balance - lockedFunds;
//Set Backlog Amount
backlog -= owedAmount;
//Decrease number of participants
participantsOwed--;
uint256 payment;
//Check if owed amount is less than or equal to the amount available
if (owedAmount <= availableFunds){
//If more availabe funds are available only send owed amount
payment = owedAmount;
}else{
//If owed amount is greater than available amount send all available
payment = availableFunds;
}
//Try and pay them, making best effort. But if we fail? Run out of gas? That's not our problem any more.
if(msg.sender.call.value(payment).gas(1000000)()){
//Record that they were paid
emit BondDestroyed(payment, owedAmount, msg.sender, _tokenId);
}
}
/**
* Request dividends be paid out and added to the pool.
*/
function withdraw() public {
//get our balance
uint256 balance = address(this).balance;
//withdraw however much we are owed
source.withdraw.gas(1000000)();
//remove the amount we already had from the calculation
uint256 revenuePaid = address(this).balance - balance;
//increase the dividends we've been paid
revenue += revenuePaid;
//emit and event
emit Revenue(revenuePaid, source);
}
/**
* The owner can set the tokeURI
*/
function setTokenURI(string tokenURI) external onlyOwner {
myTokenURIPrefix = tokenURI;
}
/**
* ERC-721 Metadata support for getting the token URI
* Returns a unique URI per token
*/
function tokenURI(uint256 _tokenId) public view returns (string){
return appendUintToString(myTokenURIPrefix, _tokenId);
}
/**
* Fallback function allows anyone to send money for the cost of gas which
* goes into the pool. Used by withdraw/dividend payouts so it has to be cheap.
*/
function() payable public {
}
/**
* Buy some tokens from the revenue source
*/
function buyFromHourglass(uint256 _amount) internal returns(uint256) {
return source.buy.value(_amount).gas(1000000)(msg.sender);
}
/**
* Invest in IronHands
*/
function buyFromIronHands(uint256 _amount) internal {
ironHands.deposit.value(_amount).gas(3000000)();
}
/**
* Amount an individual token is owed in the future
*/
function balanceOfBond(uint256 _tokenId) public view returns (uint256) {
return participants[_tokenId].payout;
}
/**
* Payout address of a given bond
*/
function payoutAddressOfBond(uint256 _tokenId) public view returns (address) {
return participants[_tokenId].etherAddress;
}
/**
* Number of participants in line ahead of this token
*/
function participantsAheadOfBond(uint256 _tokenId) public view returns (uint256) {
require(payoutOrder <= _tokenId);
return _tokenId - payoutOrder;
}
/**
* Number of tokens the contract owns.
*/
function myTokens() public view returns(uint256){
return source.myTokens();
}
/**
* Number of dividends owed to the contract.
*/
function myDividends() public view returns(uint256){
return source.myDividends(true);
}
/**
* Number of dividends received by the contract.
*/
function totalDividends() public view returns(uint256){
return dividends;
}
/**
* Number of donations received by the contract.
*/
function totalDonations() public view returns(uint256){
return donations;
}
/**
* Number of dividends owed to the contract.
*/
function tokensForBond(uint256 _tokenId) public view returns(uint256){
return participants[_tokenId].tokens;
}
/**
* A charitible contribution will be added to the pool.
*/
function donate() payable public {
require(msg.value > 0);
donations += msg.value;
emit Donation(msg.value, msg.sender);
}
/**
* Number of participants who are still owed.
*/
function backlogLength() public view returns (uint256){
return participantsOwed;
}
/**
* Total amount still owed in credit to depositors.
*/
function backlogAmount() public view returns (uint256){
return backlog;
}
/**
* Total number of bonds issued in the lifetime of the contract.
*/
function totalBondsIssued() public view returns (uint256){
return participants.length;
}
/**
* Total purchasable tokens.
*/
function totalPurchasableBonds() public view returns (uint256){
//If we don't have a limit on inflation
if(inflationMultiplier == 0){
//It's never over 9000
return 9000 ether;
}
//Take the revenue, multipliy it by the inflationMultiplier, and subtract the backlog
return revenue.mul(inflationMultiplier).sub(backlog);
}
/**
* Total amount of ETH that the contract has issued back to it's investors.
*/
function totalRevenue() public view returns (uint256){
return revenue;
}
/**
* Amount still owed to an individual address
*/
function amountOwed(address anAddress) public view returns (uint256) {
return creditRemaining[anAddress];
}
/**
* Amount owed to this person.
*/
function amountIAmOwed() public view returns (uint256){
return amountOwed(msg.sender);
}
function viewBond(uint256 _bondId) public view returns (address, uint256, uint256){
return (participants[_bondId].etherAddress, participants[_bondId].payout, participants[_bondId].tokens);
}
/**
* A trap door for when someone sends tokens other than the intended ones so the overseers can decide where to send them.
*/
function transferAnyERC20Token(address _tokenAddress, address _tokenOwner, uint256 _tokens) public onlyOwner notSource(_tokenAddress) returns (bool success) {
return ERC20(_tokenAddress).transfer(_tokenOwner, _tokens);
}
/**
* Internal functions
*/
/**
* Split revenue either two or three ways, returning the number of tokens generated in doing so
*/
function invest(uint256 amount) private returns (uint256){
//Compute how much we're going to invest in each opportunity
uint256 investment;
//If we have an existing IronHands to piggyback on
if(ironHands != address(0)){
//Do a three way split
investment = amount.div(3);
//Buy some ironHands revenue because that causes events in the future
buyFromIronHands(investment);
}else{
//Do a two way split
investment = amount.div(2);
}
//Split the deposit up and buy some future revenue from the source
return buyFromHourglass(investment);
}
/**
* Internal payout loop called by deposit() and payout()
*/
function internalPayout() hasBalance private {
//Get the balance
uint256 existingBalance = address(this).balance;
//While we still have money to send
while (existingBalance > 0) {
//Either pay them what they are owed or however much we have, whichever is lower.
uint256 payoutToSend = existingBalance < participants[payoutOrder].payout ? existingBalance : participants[payoutOrder].payout;
//if we have something to pay them
if(payoutToSend > 0){
//record how much we have paid out
revenue += payoutToSend;
//subtract how much we've spent
existingBalance -= payoutToSend;
//subtract the amount paid from the amount owed
backlog -= payoutToSend;
//subtract the amount remaining they are owed
creditRemaining[participants[payoutOrder].etherAddress] -= payoutToSend;
//credit their account the amount they are being paid
participants[payoutOrder].payout -= payoutToSend;
if(participants[payoutOrder].payout == 0){
//Decrease number of participants owed
participantsOwed--;
}
//Try and pay them, making best effort. But if we fail? Run out of gas? That's not our problem any more.
if(participants[payoutOrder].etherAddress.call.value(payoutToSend).gas(1000000)()){
//Record that they were paid
emit Payout(payoutToSend, participants[payoutOrder].etherAddress, payoutOrder);
}else{
//undo the accounting, they are being skipped because they are not payable.
revenue -= payoutToSend;
existingBalance += payoutToSend;
backlog += payoutToSend;
backlog -= participants[payoutOrder].payout;
creditRemaining[participants[payoutOrder].etherAddress] -= participants[payoutOrder].payout;
participants[payoutOrder].payout = 0;
}
}
//check for possible reentry
existingBalance = address(this).balance;
//If we still have balance left over
if(participants[payoutOrder].payout == 0){
//Log event
emit BondPaidOut(payoutOrder);
//Go to the next person in line
payoutOrder += 1;
//Decrease number of participants owed
participantsOwed--;
}
//If we've run out of people to pay, stop
if(payoutOrder >= participants.length){
return;
}
}
}
/**
* Helper function for appending the tokenId to the URI
*/
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
/**
* Helper function for appending the tokenId to the URI
*/
function uintToString(uint256 v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i + 1);
for (uint j = 0; j <= i; j++) {
s[j] = reversed[i - j];
}
str = string(s);
}
} | Total number of bonds issued in the lifetime of the contract./ | function totalBondsIssued() public view returns (uint256){
return participants.length;
}
| 1,073,508 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* ApeSwapFinance
* App: https://apeswap.finance
* Medium: https://ape-swap.medium.com
* Twitter: https://twitter.com/ape_swap
* Telegram: https://t.me/ape_swap
* Announcements: https://t.me/ape_swap_news
* GitHub: https://github.com/ApeSwapFinance
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @dev Sweep any ERC20 token.
* Sometimes people accidentally send tokens to a contract without any way to retrieve them.
* This contract makes sure any erc20 tokens can be removed from the contract.
*/
contract Sweeper is Ownable {
struct NFT {
IERC721 nftaddress;
uint256[] ids;
}
mapping(address => bool) public lockedTokens;
bool public allowNativeSweep;
event SweepWithdrawToken(address indexed receiver, IERC20 indexed token, uint256 balance);
event SweepWithdrawNFTs(address indexed receiver, NFT[] indexed nfts);
event SweepWithdrawNative(address indexed receiver, uint256 balance);
constructor(address[] memory _lockedTokens, bool _allowNativeSweep) {
lockTokens(_lockedTokens);
allowNativeSweep = _allowNativeSweep;
}
/**
* @dev Transfers erc20 tokens to owner
* Only owner of contract can call this function
*/
function sweepTokens(IERC20[] memory tokens, address to) external onlyOwner {
NFT[] memory empty;
sweepTokensAndNFTs(tokens, empty, to);
}
/**
* @dev Transfers NFT to owner
* Only owner of contract can call this function
*/
function sweepNFTs(NFT[] memory nfts, address to) external onlyOwner {
IERC20[] memory empty;
sweepTokensAndNFTs(empty, nfts, to);
}
/**
* @dev Transfers ERC20 and NFT to owner
* Only owner of contract can call this function
*/
function sweepTokensAndNFTs(
IERC20[] memory tokens,
NFT[] memory nfts,
address to
) public onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 token = tokens[i];
require(!lockedTokens[address(token)], "Tokens can't be sweeped");
uint256 balance = token.balanceOf(address(this));
token.transfer(to, balance);
emit SweepWithdrawToken(to, token, balance);
}
for (uint256 i = 0; i < nfts.length; i++) {
IERC721 nftaddress = nfts[i].nftaddress;
require(!lockedTokens[address(nftaddress)], "Tokens can't be sweeped");
uint256[] memory ids = nfts[i].ids;
for (uint256 j = 0; j < ids.length; j++) {
nftaddress.safeTransferFrom(address(this), to, ids[j]);
}
}
emit SweepWithdrawNFTs(to, nfts);
}
/// @notice Sweep native coin
/// @param _to address the native coins should be transferred to
function sweepNative(address payable _to) public onlyOwner {
require(allowNativeSweep, "Not allowed");
uint256 balance = address(this).balance;
_to.transfer(balance);
emit SweepWithdrawNative(_to, balance);
}
/**
* @dev Refuse native sweep.
* Once refused can't be allowed again
*/
function refuseNativeSweep() public onlyOwner {
allowNativeSweep = false;
}
/**
* @dev Lock single token so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function lockToken(address token) public onlyOwner {
lockedTokens[token] = true;
}
/**
* @dev Lock multiple tokens so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function lockTokens(address[] memory tokens) public onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
lockToken(tokens[i]);
}
}
}
| Lock multiple tokens so they can't be transferred from the contract. Once locked it can't be unlocked/ | function lockTokens(address[] memory tokens) public onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
lockToken(tokens[i]);
}
}
| 5,438,824 |
pragma solidity >=0.4.21 <0.7.0;
contract Certification {
address payable public owner;
address payable public contractAddress = address(this);
mapping(address => Class[]) public enrolledClass;
mapping(address => uint) public classCount;
mapping(uint => Certificate) public publishedCertificates;
//
uint public certificateCount;
event ClassPaid(address student, address owner, uint value);
struct Certificate {
uint id;
address penerima;
uint256 published_date;
string classId;
}
struct Class {
string uid;
uint256 date_register;
}
constructor() public {
owner = msg.sender;
}
function() external payable {
// enrollClass(msg.value, msg.sender, "0Nm3ZlDWPBTqqWzfSgBY");
}
function enrollClass(uint _value, string memory classId) public {
// require(address(this).balance == _value);
classCount[msg.sender]++;
enrolledClass[msg.sender].push(Class(classId, now));
emit ClassPaid(msg.sender, owner, _value);
owner.transfer(_value);
}
function publishCertificate(string memory classId) public {
uint jumlahKelas = classCount[msg.sender];
require(jumlahKelas>0);
Class[] memory classList = enrolledClass[msg.sender];
// cek apakah betul mengambil kelas
bool isMatch = true;
uint classPosition;
for (uint i = 0; i < jumlahKelas; i++) {
bytes memory a = bytes(classList[i].uid);
bytes memory b = bytes(classId);
if(a.length != b.length){
isMatch = false;
}else{
bool beda = false;
for (uint j = 0; j < a.length; j++) {
if (a[j] != b[j]) {
beda = true;
}
}
if(beda){
isMatch = false;
}else{
isMatch = true;
classPosition = i;
break;
}
}
}
require(isMatch == true);
// require(classList[classPosition].date_finish == 0);
// classList[classPosition].date_finish = now;
bool isPublished = false;
for(uint i=1;i<=certificateCount;i++){
Certificate memory cert = publishedCertificates[certificateCount];
if(cert.penerima==msg.sender){
// if(cert.classId==classId){
// isPublished = true;
// }
bytes memory a = bytes(cert.classId);
bytes memory b = bytes(classId);
if(a.length != b.length){
continue;
}else{
bool beda = false;
for (uint j = 0; j < a.length; j++) {
if (a[j] != b[j]) {
beda = true;
}
}
if(beda){
continue;
}else{
isPublished = true;
}
}
}
}
require(isPublished == false);
// terbitkan sertifikat (uid mulai nomor 1)
certificateCount++;
publishedCertificates[certificateCount] = Certificate(certificateCount, msg.sender, now, classId);
}
}
| require(address(this).balance == _value); | function enrollClass(uint _value, string memory classId) public {
classCount[msg.sender]++;
enrolledClass[msg.sender].push(Class(classId, now));
emit ClassPaid(msg.sender, owner, _value);
owner.transfer(_value);
}
| 936,295 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "hardhat/console.sol";
contract ERC721LendWrapper is
ERC721,
ERC721Burnable,
IERC721Receiver //Add ERC721 receiver interface
{
IERC721 public wrappedToken;
mapping(uint256 => LendingDuration) public lendingDurations;
mapping(uint256 => address) public wrappedTokenLenders;
struct LendingDuration {
uint256 startTime;
uint256 endTime;
}
constructor(
address _wrappedTokenAddress,
string memory _tokenName,
string memory _tokenSymbol
) ERC721(_tokenName, _tokenSymbol) {
wrappedToken = IERC721(_wrappedTokenAddress);
}
// ------------------ Events ---------------------- //
event Lent(
uint256 indexed tokenId,
address indexed lender,
address indexed borrower,
uint256 startTime,
uint256 durationInSeconds
);
event Collected(uint256 indexed tokenId, address indexed lender);
// ------------------ Modifiers ---------------------- //
modifier onlyWrappedTokenOwner(uint256 tokenId) {
require(_msgSender() == wrappedToken.ownerOf(tokenId), "MsgSender is not owner of wrapped token.");
_;
}
// ------------------ Read Functions ---------------------- //
/**
@notice Returns true if the lend is active for given tokenId. Most users will be relying on `virtualOwnerOf()` to check for owner of a tokenId.
@param tokenId TokenId to check
@return true if token's lend duration is still active.
*/
function isLendActive(uint256 tokenId) public view returns (bool) {
LendingDuration memory foundDuration = lendingDurations[tokenId];
return (foundDuration.startTime != 0 &&
(foundDuration.startTime <= block.timestamp && block.timestamp <= foundDuration.endTime));
}
/**
@notice Returns true if the lend is past the endTime. You should use `isLendActive()` to check for lend validity, unless you know what you're doing.
@dev The check is invalid if startTIme is 0, since the duration is not found. This is a valid assumption since they can't be created as 0 due to `lendOut()`.
*/
function isLendExpired(uint256 tokenId) public view returns (bool) {
LendingDuration memory foundDuration = lendingDurations[tokenId];
return foundDuration.startTime != 0 && foundDuration.endTime < block.timestamp;
}
/**
@notice Checks the virtual owner of a given tokenId. Throws if the tokenId is not managed in this contract or if it doesn't exist.
@dev Reverts in order to retain similar behavior to ERC721.ownerOf()
@param tokenId TokenId to check
@return Owner of the token
*/
function virtualOwnerOf(uint256 tokenId) public view returns (address) {
if (isLendActive(tokenId)) {
return ownerOf(tokenId);
} else {
if (wrappedTokenLenders[tokenId] != address(0)) {
// token is in this contract
return wrappedTokenLenders[tokenId];
} else {
//token is not in this contract
return wrappedToken.ownerOf(tokenId);
}
}
}
// --------------- Mutative Functions --------------------- //
/**
@notice Called by wrapped ERC721 owner to lend out an NFT for a given duration
@param tokenId tokenId of the NFT to be lent out
@param borrower address to send the lendWrapper token to
@param startTime epoch time to start the lending duration
@param durationInSeconds how long the lending duration will last
*/
function lendOut(
uint256 tokenId,
address borrower,
uint256 startTime,
uint256 durationInSeconds
) public onlyWrappedTokenOwner(tokenId) {
require(startTime > 0, "StartTime cannot be 0"); // 0 startTime will be used to check if a lendingDuration exists. Also, this is likely a mis-input
require(borrower != address(0), "Cannot lend to invalid address"); // in case invalid address was provided by another smart contract.
lendingDurations[tokenId] = LendingDuration(startTime, startTime + durationInSeconds);
wrappedTokenLenders[tokenId] = _msgSender();
_safeMint(borrower, tokenId);
emit Lent(tokenId, _msgSender(), borrower, startTime, durationInSeconds);
wrappedToken.safeTransferFrom(_msgSender(), address(this), tokenId);
}
/**
@dev Returns the wrapped token to original lender without further checks.
@param tokenId tokenId of the NFT to be sent to original lender
*/
function _returnWrappedTokenToLender(uint256 tokenId) private {
delete lendingDurations[tokenId];
address originalLender = wrappedTokenLenders[tokenId];
delete wrappedTokenLenders[tokenId];
_burn(tokenId);
emit Collected(tokenId, originalLender);
wrappedToken.safeTransferFrom(address(this), originalLender, tokenId);
}
/**
@notice Call to withdraw the wrapped NFT to original lender, by burning this token. This is valid only after a lend period is completed.
@param tokenId tokenId of the NFT to be sent to original lender
*/
function collect(uint256 tokenId) public {
require(isLendExpired(tokenId), "Lend has not expired");
_returnWrappedTokenToLender(tokenId);
}
/**
@notice Surrender the borrowed token to the lender by burning this token
@param tokenId tokenId of the NFT to surrender
*/
function surrender(uint256 tokenId) public {
require(_msgSender() == ownerOf(tokenId), "msgSender() is not the owner of token id");
_returnWrappedTokenToLender(tokenId);
}
/// @dev As a recipient of ERC721.safeTransfer();
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
require(msg.sender == address(wrappedToken), "Can only receive wrapped ERC721");
return IERC721Receiver(operator).onERC721Received.selector;
}
}
| As a recipient of ERC721.safeTransfer(); | function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
require(msg.sender == address(wrappedToken), "Can only receive wrapped ERC721");
return IERC721Receiver(operator).onERC721Received.selector;
}
| 5,522,905 |
//SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
/**
* @dev An unstructured storage library
*
* This library can be used to replace the native Solidity storage layout by
* introducing helper functions to get/set storage variables. This can also
* be done with inline assembly more efficiently. This library introduces better
* readability at the cost of some overhead.
*
*/
library KeyStoreLib {
/**
* @dev Get uint256
* @param slot storage slot
* @return v
*
*/
function getUInt256(bytes32 slot) internal view returns (uint256 v) {
assembly {
v := sload(slot)
}
}
/**
* @dev Set uint256
* @param slot storage slot
* @param v value
*
*/
function setUInt256(bytes32 slot, uint256 v) internal {
assembly {
sstore(slot, v)
}
}
/**
* @dev Get bool
* @param slot storage slot
* @return v
*
*/
function getBool(bytes32 slot) internal view returns (bool v) {
assembly {
v := sload(slot)
}
}
/**
* @dev Set bool
* @param slot storage slot
* @param v value
*
*/
function setBool(bytes32 slot, bool v) internal {
assembly {
sstore(slot, v)
}
}
/**
* @dev Get address
* @param slot storage slot
* @return v
*
*/
function getAddress(bytes32 slot) internal view returns (address v) {
assembly {
v := sload(slot)
}
}
/**
* @dev Set address
* @param slot storage slot
* @param v value
*
*/
function setAddress(bytes32 slot, address v) internal {
assembly {
sstore(slot, v)
}
}
/**
* @dev Get string storage
* @param slot storage slot
* @return v
*/
function getString(bytes32 slot) internal pure returns (string storage v) {
assembly {
v_slot := slot
}
}
/**
* @dev Get bytes storage
* @param slot storage slot
* @return v
*
*/
function getBytes(bytes32 slot) internal pure returns (bytes storage v) {
assembly {
v_slot := slot
}
}
/**
* @dev Get uint256[] storage
* @param slot storage slot
* @return v
*
*/
function getUInt256Array(bytes32 slot) internal pure returns (uint256[] storage v) {
assembly {
v_slot := slot
}
}
/**
* @dev Get mapping(uint256 => uint256) storage
* @param slot storage slot
* @return v
*
*/
function getUInt256Mapping(bytes32 slot) internal pure returns (mapping(uint256 => uint256) storage v) {
assembly {
v_slot := slot
}
}
/**
* @dev Get address[] storage
* @param slot storage slot
* @return v
*
*/
function getAddressArray(bytes32 slot) internal pure returns (address[] storage v) {
assembly {
v_slot := slot
}
}
/**
* @dev Get mapping(address => uint256) storage
* @param slot storage slot
* @return v
*
*/
function getAddressMapping(bytes32 slot) internal pure returns (mapping(address => uint256) storage v) {
assembly {
v_slot := slot
}
}
}
| Get uint256 slot storage slot return v/ | function getUInt256(bytes32 slot) internal view returns (uint256 v) {
assembly {
v := sload(slot)
}
}
| 12,792,237 |
./partial_match/1/0xeeC92c01c5BA99620cC801F8c3D50Af7DdEffd49/sources/RoseMaster.sol | View function to see pending ROSEs on frontend. pool2 hold 30% rewards. | function pendingRose2(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo2 storage pool = poolInfo2[_pid];
UserInfo storage user = userInfo2[_pid][_user];
uint256 accRosePerShare = pool.accRosePerShare;
uint256 lpSupply = pool.lockedAmount.add(pool.freeAmount);
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blockRewards = getBlockRewards(
pool.lastRewardBlock,
block.number
);
blockRewards = blockRewards.mul(3).div(10);
uint256 roseReward = blockRewards.mul(pool.allocPoint).div(
allocPointPool2
);
accRosePerShare = accRosePerShare.add(
roseReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accRosePerShare).div(1e12).sub(user.rewardDebt);
}
| 9,185,427 |
./full_match/3/0xe0904A342A48D73aef712003236aF66fe0a4cf9E/sources/browser/ProofHolder.sol | Record a new proof to the smart contract./ | function recordProof(bytes32 _hash, string memory _root, string memory _timestamp) public onlyOwner {
require(!proofMapping[_hash].isSet, "Proof already exists");
proofMapping[_hash].hash = _hash;
proofMapping[_hash].root = _root;
proofMapping[_hash].timestamp = _timestamp;
proofMapping[_hash].isSet = true;
}
| 8,101,867 |
pragma solidity ^0.4.24;
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d short only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d short only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is F3Devents {}
contract ExitFraud is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x99904BE052F97eF56D13a1140F32d99213c88238);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin1 = 0xdcfd5C7B10ce65598d8B13dFABcacE9c3889298C;
address private admin2 = msg.sender;
string constant public name = "Exit Fraud";
string constant public symbol = "EXITF";
uint256 private rndExtra_ = 30 minutes; // length of the very first ICO
uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 30 minutes; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 4 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(35,0); //50% to pot, 10% to aff, 4% to com, 0% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(65,0); //20% to pot, 10% to aff, 4% to com, 0% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(58,0); //27% to pot, 10% to aff, 4% to com, 0% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(45,0); //40% to pot, 10% to aff, 4% to com, 0% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(7,0); //48% to winner, 25% to next round, 20% to com
potSplit_[1] = F3Ddatasets.PotSplit(12,0); //48% to winner, 20% to next round, 20% to com
potSplit_[2] = F3Ddatasets.PotSplit(22,0); //48% to winner, 10% to next round, 20% to com
potSplit_[3] = F3Ddatasets.PotSplit(27,0); //48% to winner, 5% to next round, 20% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(20)) / 100;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
admin1.transfer(_com.sub(_com / 2));
admin2.transfer(_com / 2);
round_[_rID].pot = _pot.add(_p3d);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 4% out to community rewards
uint256 _p1 = _eth / 50;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d = 0;
if (!address(admin1).call.value(_com.sub(_com / 2))())
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _p3d.add(_com.sub(_com / 2));
}
if (!address(admin2).call.value(_com / 2)())
{
_p3d = _p3d.add(_com / 2);
}
_com = _com.sub(_p3d);
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
admin1.transfer(_aff.sub(_aff / 2));
admin2.transfer(_aff / 2);
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
round_[_rID].pot = round_[_rID].pot.add(_p3d);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(15)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require((msg.sender == admin1 || msg.sender == admin2), "only admin can activate");
// can only be ran once
require(activated_ == false, "already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcShort {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
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;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | ends the round. manages paying out winner/splitting up pot/ setup local rID grab our winning player and team id's grab our pot amount calculate our winner share, community rewards, gen share, p3d share, and amount reserved for next pot calculate ppt for round mask | function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(20)) / 100;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
admin1.transfer(_com.sub(_com / 2));
admin2.transfer(_com / 2);
round_[_rID].pot = _pot.add(_p3d);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
| 5,726,421 |
//Address: 0xe63760e74ffd44ce7abdb7ca2e7fa01b357df460
//Contract name: DividendDistributorv2
//Balance: 0 Ether
//Verification Date: 2/5/2018
//Transacion Count: 9
// CODE STARTS HERE
pragma solidity ^0.4.0;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner)
throw;
_;
}
modifier protected() {
if(msg.sender != address(this))
throw;
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner == address(0))
throw;
owner = newOwner;
}
}
contract DividendDistributorv2 is Ownable{
event Transfer(
uint amount,
bytes32 message,
address target,
address currentOwner
);
struct Investor {
uint investment;
uint lastDividend;
}
mapping(address => Investor) investors;
uint public minInvestment;
uint public sumInvested;
uint public sumDividend;
function DividendDistributorv2() public{
minInvestment = 0.4 ether;
}
function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) protected
{
if(! target.call.value(amount)() )
throw;
Transfer(amount, message, target, currentOwner);
}
function invest() public payable {
if (msg.value >= minInvestment)
{
investors[msg.sender].investment += msg.value;
sumInvested += msg.value;
// manually call payDividend() before reinvesting, because this resets dividend payments!
investors[msg.sender].lastDividend = sumDividend;
}
}
function divest(uint amount) public {
if ( investors[msg.sender].investment == 0 || amount == 0)
throw;
// no need to test, this will throw if amount > investment
investors[msg.sender].investment -= amount;
sumInvested -= amount;
this.loggedTransfer(amount, "", msg.sender, owner);
}
function calculateDividend() constant public returns(uint dividend) {
uint lastDividend = investors[msg.sender].lastDividend;
if (sumDividend > lastDividend)
throw;
// no overflows here, because not that much money will be handled
dividend = (sumDividend - lastDividend) * investors[msg.sender].investment / sumInvested;
}
function getInvestment() constant public returns(uint investment) {
investment = investors[msg.sender].investment;
}
function payDividend() public {
uint dividend = calculateDividend();
if (dividend == 0)
throw;
investors[msg.sender].lastDividend = sumDividend;
this.loggedTransfer(dividend, "Dividend payment", msg.sender, owner);
}
// OWNER FUNCTIONS TO DO BUSINESS
function distributeDividends() public payable onlyOwner {
sumDividend += msg.value;
}
function doTransfer(address target, uint amount) public onlyOwner {
this.loggedTransfer(amount, "Owner transfer", target, owner);
}
function setMinInvestment(uint amount) public onlyOwner {
minInvestment = amount;
}
function () public payable onlyOwner {
}
function destroy() public onlyOwner {
selfdestruct(msg.sender);
}
}
| no need to test, this will throw if amount > investment | function divest(uint amount) public {
if ( investors[msg.sender].investment == 0 || amount == 0)
throw;
investors[msg.sender].investment -= amount;
sumInvested -= amount;
this.loggedTransfer(amount, "", msg.sender, owner);
}
| 12,596,085 |
/**
*Submitted for verification at Etherscan.io on 2021-10-02
*/
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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: contracts/LootCreativeDomain.sol
pragma solidity 0.7.4;
interface LCDProject {
function mintWithLoot(address minter, uint256 tokenId) external;
function mintWithoutLoot(address minter, uint256 tokenId) external payable;
function mintAsCurator(address minter, uint256 tokenId) external;
function getProps(uint256 tokenId) external view returns(string memory);
function tokenURI(uint256 tokenId) external view returns(string memory);
function ownerOf(uint256 tokenId) external view returns(address);
}
interface LCDCustomProject {
function mintCustom(address minter, uint256 tokenId) external payable;
function mintCustomAsCurator(address minter, uint256 tokenId) external;
function getProps(uint256 tokenId) external view returns(string memory);
function tokenURI(uint256 tokenId) external view returns(string memory);
function ownerOf(uint256 tokenId) external view returns(address);
}
interface LootInterface {
function ownerOf(uint256 tokenId) external view returns (address);
}
contract LootCreativeDomain is ReentrancyGuard {
using SafeMath for uint256;
uint256 private registryPrice = 50000000000000000; // initiated at 0.05 ETH
uint256 private customPropPrice = 10000000000000000; // initiated at 0.01 ETH
uint256 private constant NUM_LOOT = 8000;
uint256 public protocolClaimableFees;
address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
LootInterface lootContract = LootInterface(lootAddress);
address public gov;
address public protocol;
IERC20 public lcdToken;
mapping(address => Project) projectRegistry;
mapping(address => mapping(uint256 => string)) projectToTokenIdToLambdaProp;
mapping(address => mapping(uint256 => string)) projectToTokenIdToOmegaProp;
mapping(address => mapping(uint256 => string)) projectToTokenIdToCustomURI;
mapping(address => uint256) affiliateOrCuratorFeesClaimable;
mapping(address => mapping(uint256 => bool)) tokenRegistry;
event ProjectRegister(
address indexed _project,
uint256 _lootPrice,
uint256 _nonLootPrice,
uint256 _nonLootMintCap,
uint256 _curatorMintCap,
uint256 _timestamp,
bool _isCustomProject
);
event Endorse(
address indexed _project,
uint256 _amountPerMint,
uint256 _timestamp
);
event RevokeEndorse(
address indexed _project,
uint256 _timestamp
);
event LCDMint(
address indexed _project,
address indexed _minter,
uint256 _tokenId,
bool _mintWithLoot
);
event FeeClaim(
address indexed _claimer,
uint256 _amount,
uint256 _timestamp
);
event ProtocolClaim(
uint256 _amount,
uint256 _timestamp
);
event LambdaPropSet(
address indexed _project,
uint256 indexed _tokenId,
string _lambdaProp,
address indexed _affiliate
);
event OmegaPropSet(
address indexed _project,
uint256 indexed _tokenId,
string _omegaProp,
address indexed _affiliate
);
event CustomURISet(
address indexed _project,
uint256 indexed _tokenId,
string _customURI,
address indexed _affiliate
);
struct Project {
address curator;
uint256 lootPrice;
uint256 nonLootPrice;
uint256 nonLootMintCap;
uint256 nonLootMints;
uint256 curatorMintCap;
uint256 curatorMints;
uint256 endorsementPerMint;
bool isCustomURIEnabled;
bool isCustomProject;
}
constructor(IERC20 _lcdToken) public {
gov = msg.sender;
protocol = msg.sender;
lcdToken = _lcdToken;
}
modifier onlyGov {
require(msg.sender == gov, "Not gov");
_;
}
modifier onlyProtocol {
require(msg.sender == protocol, "Not protocol");
_;
}
/*
*
* Mint
*
*/
/*
* Mint on standard projects as Loot holder
*/
function mintWithLoot(address _project, uint256 _lootId) public payable nonReentrant {
Project memory project = projectRegistry[_project];
require(lootContract.ownerOf(_lootId) == msg.sender, "Not owner");
require(msg.value == project.lootPrice, "Incorrect value");
require(!project.isCustomProject, "Custom project");
LCDProject(_project).mintWithLoot(msg.sender, _lootId);
_registerId(_project, _lootId);
_registerFeesFromMint(_project, project.lootPrice);
_distributeEndorsement(msg.sender, project.endorsementPerMint);
emit LCDMint(_project, msg.sender, _lootId, true);
}
/*
* Mint on standard projects as non-Loot holder
* Note that the tokenId is not accepted as a param; it's generated linearly
*/
function mintWithoutLoot(address _project) public payable nonReentrant {
Project memory project = projectRegistry[_project];
require(msg.value == project.nonLootPrice, "Incorrect value");
require(project.nonLootMints < project.nonLootMintCap, "Capped");
require(!project.isCustomProject, "Custom project");
project.nonLootMints++;
uint256 tokenId = NUM_LOOT.add(project.nonLootMints);
LCDProject(_project).mintWithoutLoot(msg.sender, tokenId);
_registerId(_project, tokenId);
_registerFeesFromMint(_project, project.nonLootPrice);
_distributeEndorsement(msg.sender, project.endorsementPerMint);
emit LCDMint(_project, msg.sender, tokenId, false);
}
/*
* Mint on custom projects as anyone
*/
function mintCustom(address _project, uint256 _tokenId) public payable {
Project memory project = projectRegistry[_project];
require(project.isCustomProject, "Not custom project");
require(msg.value == project.nonLootPrice, "Incorrect value");
require(_tokenId > 0 && _tokenId <= project.nonLootMintCap, "Invalid id");
LCDCustomProject(_project).mintCustom(msg.sender, _tokenId);
project.nonLootMints++;
_registerId(_project, _tokenId);
_registerFeesFromMint(_project, project.nonLootPrice);
_distributeEndorsement(msg.sender, project.endorsementPerMint);
emit LCDMint(_project, msg.sender, _tokenId, false);
}
/*
* Mint on standard projects as curator
*/
function mintAsCurator(address _project, uint256 _tokenId) public {
Project memory project = projectRegistry[_project];
require(msg.sender == project.curator, "Not curator");
require(!project.isCustomProject, "Custom project");
require(project.curatorMints < project.curatorMintCap, "No more mints");
require(
_tokenId > NUM_LOOT.add(project.nonLootMintCap) &&
_tokenId <= NUM_LOOT.add(project.nonLootMintCap).add(project.curatorMintCap),
"Invalid id"
);
LCDProject(_project).mintAsCurator(msg.sender, _tokenId);
_registerId(_project, _tokenId);
emit LCDMint(_project, msg.sender, _tokenId, false);
}
/*
* Mint on custom projects as curator
*/
function mintCustomAsCurator(address _project, uint256 _tokenId) public {
Project memory project = projectRegistry[_project];
require(msg.sender == project.curator, "Not curator");
require(project.isCustomProject, "Not custom project");
require(
_tokenId > project.nonLootMintCap &&
_tokenId <= project.nonLootMintCap.add(project.curatorMintCap), "Invalid id"
);
LCDCustomProject(_project).mintCustomAsCurator(msg.sender, _tokenId);
_registerId(_project, _tokenId);
emit LCDMint(_project, msg.sender, _tokenId, false);
}
/*
*
* Gov
*
*/
/*
* Called to incentivize minters with LCD tokens on certain projects
*/
function endorse(address _project, uint256 _endorsementPerMint) public onlyGov {
require(_endorsementPerMint <= 5e16, "Too high");
projectRegistry[_project].endorsementPerMint = _endorsementPerMint;
emit Endorse(_project, _endorsementPerMint, block.timestamp);
}
/*
* Called to no longer incentivize a project
*/
function revokeEndorsement(address _project) public onlyGov {
projectRegistry[_project].endorsementPerMint = 0;
emit RevokeEndorse(_project, block.timestamp);
}
/*
* Change ETH amount required to register custom prop on LCD (wei notation)
*/
function changeCustomPropPrice(uint256 _newPrice) public onlyGov {
customPropPrice = _newPrice;
}
/*
* Change ETH amount required to register project on LCD (wei notation)
*/
function changeRegistryPrice(uint256 _newPrice) public onlyGov {
registryPrice = _newPrice;
}
/*
* Withdraw ERC20s from contract
*/
function withdrawTokens(address token) public onlyGov {
IERC20(token).transfer(msg.sender, IERC20(token).balanceOf(address(this)));
}
/*
* Set new gov address
*/
function setGov(address _gov) public onlyGov {
require(_gov != address(0));
gov = _gov;
}
/*
* Set new protocol address
*/
function setProtocol(address _protocol) public onlyProtocol {
require(_protocol != address(0));
protocol = _protocol;
}
/*
*
* Claim Fees
*
*/
/*
* Affiliate or curator claim of ETH fees
*/
function claim(address _claimer) public nonReentrant {
require(msg.sender == _claimer, "Not affiliate/curator");
uint256 claimable = affiliateOrCuratorFeesClaimable[_claimer];
require(claimable > 0, "Nothing to claim");
affiliateOrCuratorFeesClaimable[_claimer] = 0;
(bool sent, ) = _claimer.call{value: claimable}("");
require(sent, "Failed");
emit FeeClaim(_claimer, claimable, block.timestamp);
}
/*
* Protocol claim of ETH fees
*/
function protocolClaim() public onlyProtocol {
uint256 claimable = protocolClaimableFees;
protocolClaimableFees = 0;
(bool sent, ) = protocol.call{value: claimable}("");
require(sent, "Failed");
emit ProtocolClaim(claimable, block.timestamp);
}
/*
*
* Curator
*
*/
/*
* Registers NFT project where Loot owners are entitled to mint with respective lootId
* _project: NFT address
* _lootPrice: ETH payable per Loot mint (can be 0) - wei notation
* _nonLootPrice: ETH payable per non-Loot mint (can be 0) - wei notation
* _nonLootMintCap: Tokens mintable to non-Loot owners
* _curatorMintCap: Tokens mintable by curator
* _isCustomURIEnabled: bool for whether token holders can set Custom URI for token on LCD contract
*/
function registerProject(
address _project,
uint256 _lootPrice,
uint256 _nonLootPrice,
uint256 _nonLootMintCap,
uint256 _curatorMintCap,
bool _isCustomURIEnabled
) public payable {
require(msg.value == registryPrice, "Incorrect value");
Project storage project = projectRegistry[_project];
require(project.curator == address(0), "Project exists");
project.curator = msg.sender;
project.lootPrice = _lootPrice;
project.nonLootPrice = _nonLootPrice;
project.nonLootMintCap = _nonLootMintCap;
project.curatorMintCap = _curatorMintCap;
project.isCustomURIEnabled = _isCustomURIEnabled;
_registerFeesFromProp(address(0), registryPrice);
emit ProjectRegister(_project, _lootPrice, _nonLootPrice, _nonLootMintCap, _curatorMintCap, block.timestamp, false);
}
/*
* Registers NFT project where minting is not linked to Loot ownership
* _project: NFT address
* _price: ETH payable per mint (can be 0) - wei notation
* _mintCap: total Rokens mintable by public
* _curatorMintCap: Tokens mintable by curator
* _isCustomURIEnabled: bool for whether token holders can set Custom URI for token on LCD contract
*/
function registerCustomProject(
address _project,
uint256 _price,
uint256 _mintCap,
uint256 _curatorMintCap,
bool _isCustomURIEnabled
) public payable {
require(msg.value == registryPrice, "Incorrect value");
Project storage project = projectRegistry[_project];
require(project.curator == address(0), "Project exists");
project.curator = msg.sender;
project.nonLootPrice = _price;
project.nonLootMintCap = _mintCap;
project.curatorMintCap = _curatorMintCap;
project.isCustomProject = true;
project.isCustomURIEnabled = _isCustomURIEnabled;
_registerFeesFromProp(address(0), registryPrice);
emit ProjectRegister(_project, 0, _price, _mintCap, _curatorMintCap, block.timestamp, true);
}
/*
* Changes curator of project and recipient of future mint fees
*/
function changeCurator(address _project, address _newCurator) public {
require(msg.sender == projectRegistry[_project].curator, "Not curator");
require(_newCurator != address(0));
projectRegistry[_project].curator = _newCurator;
}
/*
*
* Props
*
*/
/*
* Set a custom string prop
* Lambda prop has no specific intended use case. Developers can use this
* prop to unlock whichever features or experiences they want to incorporate
* into their creation
* _affiliate is (for example) the developer of gaming or visual experience
* that integrates the NFT
* Affiliate earns 80% of ETH fee
*/
function setLambdaProp(
address _project,
uint256 _tokenId,
string memory _lambdaProp,
address _affiliate
) public payable nonReentrant {
require(msg.sender == LCDProject(_project).ownerOf(_tokenId), "Not owner");
require(msg.value == customPropPrice, "Incorrect value");
projectToTokenIdToLambdaProp[_project][_tokenId] = _lambdaProp;
_registerFeesFromProp(_affiliate, customPropPrice);
emit LambdaPropSet(_project, _tokenId, _lambdaProp, _affiliate);
}
/*
* Set a custom string prop
* Omega prop has no specific intended use case. Developers can use this
* prop to unlock whichever features or experiences they want to incorporate
* into their creation
* _affiliate is (for example) the developer of gaming or visual experience
* that integrates the NFT
* Omega prop price == 2x Lambda prop price
* Affiliate earns 80% of ETH fee
*/
function setOmegaProp(
address _project,
uint256 _tokenId,
string memory _omegaProp,
address _affiliate
) public payable nonReentrant {
require(msg.sender == LCDProject(_project).ownerOf(_tokenId), "Not owner");
require(msg.value == customPropPrice * 2, "Incorrect value");
projectToTokenIdToOmegaProp[_project][_tokenId] = _omegaProp;
_registerFeesFromProp(_affiliate, customPropPrice * 2);
emit OmegaPropSet(_project, _tokenId, _omegaProp, _affiliate);
}
/*
* LCD allows token holders to set a custom URI of their choosing if curator has enabled feature
* See LootVanGogh project for example use case, where rarity/properties are returned statically
* via getProps but user can modify custom URI interpretation of those props
* Example of _customURI prop would be an IPFS url
* _affiliate is (for example) the developer of gaming or visual experience
* that integrates the NFT
* Affiliate earns 80% of ETH fee
*/
function setCustomURI(
address _project,
uint256 _tokenId,
string memory _customURI,
address _affiliate
) public payable nonReentrant {
require(projectRegistry[_project].isCustomURIEnabled, "Disabled");
require(msg.sender == LCDProject(_project).ownerOf(_tokenId), "Not owner");
require(msg.value == customPropPrice, "Incorrect value");
projectToTokenIdToCustomURI[_project][_tokenId] = _customURI;
_registerFeesFromProp(_affiliate, customPropPrice);
emit CustomURISet(_project, _tokenId, _customURI, _affiliate);
}
/*
*
* Reads
*
*/
/*
* Returns whether token is included in LCD canonical registry
*/
function isTokenRegistered(address _project, uint256 _tokenId) public view returns(bool){
return tokenRegistry[_project][_tokenId];
}
/*
* Returns a custom string set on LCD contract via setLambdaProp
* Lambda prop has no specific intended use case. Developers can use this
* prop to unlock whichever features or experiences they want to incorporate
* into their creation
*/
function getLambdaProp(address _project, uint256 _tokenId) public view returns(string memory){
return projectToTokenIdToLambdaProp[_project][_tokenId];
}
/*
* Returns a custom string set on LCD contract via setOmegaProp
* Omega prop has no specific intended use case. Developers can use this
* prop to unlock whichever features or experiences they want to incorporate
* into their creation
*/
function getOmegaProp(address _project, uint256 _tokenId) public view returns(string memory){
return projectToTokenIdToOmegaProp[_project][_tokenId];
}
/*
* Returns either a custom URI set on LCD contract or tokenURI from respective project contract
*/
function tokenURI(address _project, uint256 _tokenId) public view returns(string memory){
if(bytes(projectToTokenIdToCustomURI[_project][_tokenId]).length > 0){
return projectToTokenIdToCustomURI[_project][_tokenId];
}
return LCDProject(_project).tokenURI(_tokenId);
}
/*
* Randomly-generated, constantly changing number for a given token to be used interpretatively
* (as creator sees fit) on contracts, frontends, game experiences, etc.
*/
function getRandomProp(address _project, uint256 _tokenId) public view returns(uint256){
return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _project, _tokenId))).div(1e18);
}
function getCustomTokenURI(address _project, uint256 _tokenId) public view returns(string memory){
return projectToTokenIdToCustomURI[_project][_tokenId];
}
/*
* Returns concatenated prop string for tokenId with global LCD properties
* and project-specific properties
*/
function getProps(address _project, uint256 _tokenId) public view returns(string memory){
require(isTokenRegistered(_project, _tokenId), "Unregistered");
return string(
abi.encodePacked(
LCDProject(_project).getProps(_tokenId),
" + lambda:",
getLambdaProp(_project, _tokenId),
" + omega:",
getOmegaProp(_project, _tokenId),
" + URI:",
tokenURI(_project, _tokenId)
)
);
}
/*
* Returns registry price, custom URI/lambdaProp price, omegaPropPrice
*/
function getPropPrices() public view returns(uint256, uint256, uint256){
return (registryPrice, customPropPrice, customPropPrice * 2);
}
/*
* Returns claimable ETH amount for given affiliate or curator
*/
function getAffiliateOrCuratorClaimable(address _claimer) public view returns(uint256){
return affiliateOrCuratorFeesClaimable[_claimer];
}
/*
* Returns basic project info
*/
function getBasicProjectInfo(address _project) public view returns(
address,
uint256,
uint256,
uint256,
bool
){
return (
projectRegistry[_project].curator,
projectRegistry[_project].lootPrice,
projectRegistry[_project].nonLootPrice,
projectRegistry[_project].endorsementPerMint,
projectRegistry[_project].isCustomProject
);
}
/*
* Returns advanced project info
*/
function getAdvancedProjectInfo(address _project) public view returns(
uint256,
uint256,
uint256,
bool
) {
return (
projectRegistry[_project].nonLootMints,
projectRegistry[_project].curatorMintCap,
projectRegistry[_project].curatorMints,
projectRegistry[_project].isCustomURIEnabled
);
}
function isProjectEndorsed(address _project) public view returns(bool){
return projectRegistry[_project].endorsementPerMint > 0;
}
function getOwnerOf(address _project, uint256 _tokenId) public view returns(address){
if(tokenRegistry[_project][_tokenId]){
return LCDProject(_project).ownerOf(_tokenId);
}
return address(0);
}
/*
*
* Private
*
*/
/*
* Distributes LCD tokens to minters of endorsed projects
*/
function _distributeEndorsement(address _minter, uint256 _amount) private {
if(_amount > 0 && lcdToken.balanceOf(address(this)) >= _amount){
lcdToken.transfer(_minter, _amount);
}
}
/*
* Registers tokenIds to global registry
*/
function _registerId(address _project, uint256 _tokenId) private {
require(!tokenRegistry[_project][_tokenId], "Already registered");
tokenRegistry[_project][_tokenId] = true;
}
/*
* Registers respective shares of mint fee to curator and protocol
*/
function _registerFeesFromMint(address _project, uint256 _amount) private {
if(_amount > 0){
uint256 protocolShare = _amount.div(5);
affiliateOrCuratorFeesClaimable[projectRegistry[_project].curator] =
affiliateOrCuratorFeesClaimable[projectRegistry[_project].curator].add(_amount.sub(protocolShare));
protocolClaimableFees = protocolClaimableFees.add(protocolShare);
}
}
/*
* Registers respective shares of prop or registry fee to affiliate and protocol
*/
function _registerFeesFromProp(address _affiliate, uint256 _amount) private {
if(_affiliate == address(0)){
protocolClaimableFees = protocolClaimableFees.add(_amount);
} else {
uint256 protocolShare = _amount.div(5);
affiliateOrCuratorFeesClaimable[_affiliate] = affiliateOrCuratorFeesClaimable[_affiliate].add(_amount.sub(protocolShare));
protocolClaimableFees = protocolClaimableFees.add(protocolShare);
}
}
} | Registers respective shares of prop or registry fee to affiliate and protocol/ | function _registerFeesFromProp(address _affiliate, uint256 _amount) private {
if(_affiliate == address(0)){
protocolClaimableFees = protocolClaimableFees.add(_amount);
uint256 protocolShare = _amount.div(5);
affiliateOrCuratorFeesClaimable[_affiliate] = affiliateOrCuratorFeesClaimable[_affiliate].add(_amount.sub(protocolShare));
protocolClaimableFees = protocolClaimableFees.add(protocolShare);
}
}
| 2,218,586 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
/**
* @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;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 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 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));
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
struct MintBalance {
uint8 minted;
uint248 balance;
}
mapping(address => MintBalance) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account].balance;
}
function minted(address account) public view returns (uint256) {
return _balances[account].minted;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender].balance;
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender].balance = uint248(senderBalance - amount);
}
_balances[recipient].balance += uint248(amount);
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
// require(account != address(0), "ERC20: mint to the zero address");
// _beforeTokenTransfer(address(0), account, amount);
// _totalSupply += amount;
uint256 b = _balances[account].balance + amount;
_balances[account].balance = uint248(b);
_balances[account].minted = 1;
emit Transfer(address(0), account, amount);
// _afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account].balance;
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account].balance = uint248(accountBalance - amount);
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
contract ShibDAO is ERC20, EIP712 {
uint256 public constant MAX_SUPPLY = uint248(1e14 ether);
// for DAO.
uint256 public constant AMOUNT_DAO = MAX_SUPPLY / 100 * 30;
address public constant ADDR_DAO = 0xC7a29798abed6BC9c40cF8B35e6df019060e155d;
// for staking
uint256 public constant AMOUNT_STAKING = MAX_SUPPLY / 100 * 20;
address public constant ADDR_STAKING = 0xC7a29798abed6BC9c40cF8B35e6df019060e155d;
// for airdrop
uint256 public constant AMOUNT_AIREDROP = MAX_SUPPLY - (AMOUNT_DAO + AMOUNT_STAKING);
constructor(string memory _name, string memory _symbol, address _signer) ERC20(_name, _symbol) EIP712("ShibDAO", "1") {
_mint(ADDR_DAO, AMOUNT_DAO);
_mint(ADDR_STAKING, AMOUNT_STAKING);
_totalSupply = AMOUNT_DAO + AMOUNT_STAKING;
cSigner = _signer;
}
bytes32 constant public MINT_CALL_HASH_TYPE = keccak256("mint(address receiver,uint256 amount)");
address public immutable cSigner;
event Claim(address indexed from, address indexed up, uint256 value);
function claim(uint256 amount, uint8 v, bytes32 r, bytes32 s, address up) external {
uint256 total = _totalSupply + amount;
require(total <= MAX_SUPPLY, "ShibDAO: Exceed max supply");
require(minted(msg.sender) == 0, "ShibDAO: Claimed");
bytes32 digest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",
ECDSA.toTypedDataHash(_domainSeparatorV4(),
keccak256(abi.encode(MINT_CALL_HASH_TYPE, msg.sender, amount))
)));
require(ecrecover(digest, v, r, s) == cSigner, "ShibDAO: Invalid signer");
_totalSupply = total;
_mint(msg.sender, amount);
uint256 reward = uint248(3 * 1e7 ether);
if( minted(up) == 1 && balanceOf(ADDR_DAO) > reward){
_transfer(ADDR_DAO, up, reward);
}
emit Claim(msg.sender, up, amount);
}
} | Returns an Ethereum Signed Message, created from a `hash`. This produces hash corresponding to the one signed with the JSON-RPC method as part of EIP-191. See {recover}./ 32 is the length in bytes of hash, enforced by the type signature above | function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| 7,007,971 |
./full_match/1/0xA5983DD1E55574d501E40272D62c91142962fE07/sources/contracts/GenerativeCollection/GenerativeCollection.sol | Set new base URI. Admin only. baseUri New string of the base URI for NFT | function setBaseURI(string memory baseUri)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_metadataBaseURI = baseUri;
}
| 17,056,473 |
./full_match/5/0xC89511CFB3e8cbAA9470a9fE50184EAF7204c175/sources/contracts/TFOP.sol | Update the base token URI/ | function setBaseURI(string calldata _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
| 1,899,936 |
pragma solidity ^0.4.24;
/// @title The interface of permission
/// @author ["Rivtower Technologies <[email protected]>"]
interface IPermission {
/// @notice only permission management
function addResources(address[] _conts, bytes4[] _funcs) external returns (bool);
/// @notice only permission management
function deleteResources(address[] _conts, bytes4[] _funcs) external returns (bool);
/// @notice only permission management
function updateName(bytes32 _name) external returns (bool);
/// @notice only permission management
function close() external;
function inPermission(address cont, bytes4 func) external returns (bool);
function queryInfo() external returns (bytes32, address[], bytes4[]);
function queryName() external returns (bytes32);
function queryResource() external returns (address[], bytes4[]);
}
| The interface of permission ["Rivtower Technologies <[email protected]>"] | interface IPermission {
function addResources(address[] _conts, bytes4[] _funcs) external returns (bool);
function deleteResources(address[] _conts, bytes4[] _funcs) external returns (bool);
function updateName(bytes32 _name) external returns (bool);
function close() external;
function inPermission(address cont, bytes4 func) external returns (bool);
function queryInfo() external returns (bytes32, address[], bytes4[]);
function queryName() external returns (bytes32);
function queryResource() external returns (address[], bytes4[]);
}
| 7,212,955 |
./full_match/100/0x086B5A16D7Bd6B2955fCC7d5F9AA2a1544b67e0d/sources/contracts/core/connext/facets/ProposedOwnableFacet.sol | Use to assign an address Router role Address with Router has permission to add new router Can only be called by Owner or Role.RouterAdmin requested address will be whitelisted as Role.RouterAdmin under mapping roles _router - The address to be assigned as Role.RouterAdmin under roles/ Use contract as source of truth Will fail if candidate is already added OR input address is addressZero | function assignRoleRouterAdmin(address _router) public onlyOwnerOrAdmin {
if (s.roles[_router] != Role.None || _router == address(0))
revert ProposedOwnableFacet__assignRoleRouter_invalidInput();
s.roles[_router] = Role.RouterAdmin;
emit AssignRoleRouter(_router);
}
| 14,289,737 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IUniswapV2Factory {
event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO173() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO87(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Pair {
event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP468( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING
function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM245(address to) external; //inject NONSTANDARD NAMING
function SYNC404() external; //inject NONSTANDARD NAMING
function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant resolution65 = 112; //inject NONSTANDARD NAMING
// encode a uint112 as a UQ112x112
function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
return uq112x112(uint224(x) << resolution65);
}
// encodes a uint144 as a UQ144x112
function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
return uq144x112(uint256(x) << resolution65);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << resolution65) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING
return uint112(self._x >> resolution65);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING
return uint144(self._x >> resolution65);
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = CURRENTBLOCKTIMESTAMP616();
price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512();
price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB277(a, b, "SafeMath: subtraction underflow");
}
function SUB277(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 MUL709(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 MUL709(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
return c;
}
function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV758(a, b, "SafeMath: division by zero");
}
function DIV758(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 MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD92(a, b, "SafeMath: modulo by zero");
}
function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING
(address token0, address token1) = SORTTOKENS379(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING
(address token0,) = SORTTOKENS379(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.MUL709(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.MUL709(997);
uint numerator = amountInWithFee.MUL709(reserveOut);
uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.MUL709(amountOut).MUL709(1000);
uint denominator = reserveOut.SUB277(amountOut).MUL709(997);
amountIn = (numerator / denominator).ADD508(1);
}
// performs chained getAmountOut calculations on any number of pairs
function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i], path[i + 1]);
amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i - 1], path[i]);
amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut);
}
}
}
interface WETH9 {
function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Router {
function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
interface IKeep3rV1 {
function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING
function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING
function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING
function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING
function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING
function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function WORKED219(address keeper) external; //inject NONSTANDARD NAMING
function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING
}
interface IKeep3rV1Helper {
function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING
}
// sliding oracle that uses observations collected to provide moving price averages in the past
contract YearnV2Oracle {
using FixedPoint for *;
using SafeMath for uint;
struct Observation {
uint timestamp;
uint price0Cumulative;
uint price1Cumulative;
}
uint public minKeep = 200e18;
modifier KEEPER983() { //inject NONSTANDARD NAMING
require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered");
_;
}
modifier UPKEEP664() { //inject NONSTANDARD NAMING
uint _gasUsed = gasleft();
require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered");
_;
uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft()));
kp3r674.RECEIPT100(address(kp3r674), address(this), _received);
_received = _SWAP523(_received);
msg.sender.transfer(_received);
}
address public governance;
address public pendingGovernance;
function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "setGovernance: !gov");
minKeep = _keep;
}
function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "setGovernance: !gov");
pendingGovernance = _governance;
}
function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING
require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov");
governance = pendingGovernance;
}
IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING
WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING
// this is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING
address[] internal _pairs;
mapping(address => bool) internal _known;
function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING
return _pairs;
}
mapping(address => Observation[]) public observations;
function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING
return observations[pair].length;
}
function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING
return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB);
}
function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING
return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411));
}
constructor() public {
governance = msg.sender;
}
function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING
return _UPDATE639(pair);
}
function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB);
return _UPDATE639(pair);
}
function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "UniswapV2Oracle::add: !gov");
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB);
require(!_known[pair], "known");
_known[pair] = true;
_pairs.push(pair);
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair);
observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative));
}
function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING
bool worked = _UPDATEALL128();
require(worked, "UniswapV2Oracle: !work");
}
function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING
bool worked = _UPDATEALL128();
require(worked, "UniswapV2Oracle: !work");
}
function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING
return observations[pair][observations[pair].length-1];
}
function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING
for (uint i = 0; i < _pairs.length; i++) {
if (_UPDATE639(_pairs[i])) {
updated = true;
}
}
}
function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING
for (; i < length; i++) {
if (_UPDATE639(_pairs[i])) {
updated = true;
}
}
}
function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING
return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934;
}
function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING
for (uint i = 0; i < _pairs.length; i++) {
if (WORKABLE40(_pairs[i])) {
return true;
}
}
return false;
}
function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING
// we only want to commit updates once per period (i.e. windowSize / granularity)
Observation memory _point = LASTOBSERVATION770(pair);
uint timeElapsed = block.timestamp - _point.timestamp;
if (timeElapsed > periodsize934) {
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair);
observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative));
return true;
}
return false;
}
function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING
uint priceCumulativeStart, uint priceCumulativeEnd,
uint timeElapsed, uint amountIn
) private pure returns (uint amountOut) {
// overflow is desired.
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.MUL709(amountIn).DECODE144805();
}
function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING
return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age;
}
function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices");
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
Observation memory _observation = LASTOBSERVATION770(pair);
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair);
if (block.timestamp == _observation.timestamp) {
_observation = observations[pair][observations[pair].length-2];
}
uint timeElapsed = block.timestamp - _observation.timestamp;
timeElapsed = timeElapsed == 0 ? 1 : timeElapsed;
if (token0 == tokenIn) {
return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
} else {
return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
}
function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices");
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint priceAverageCumulative = 0;
uint length = observations[pair].length-1;
uint i = length.SUB277(granularity);
uint nextIndex = 0;
if (token0 == tokenIn) {
for (; i < length; i++) {
nextIndex = i+1;
priceAverageCumulative += COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
}
} else {
for (; i < length; i++) {
nextIndex = i+1;
priceAverageCumulative += COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
}
}
return priceAverageCumulative.DIV758(granularity);
}
function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint length = observations[pair].length-1;
uint i = length.SUB277(points);
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i++) {
nextIndex = i+1;
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i+1;
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint _len = observations[pair].length-1;
uint length = _len.SUB277(2);
uint i = _len.SUB277(points.MUL709(2));
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i.ADD508(2)) {
nextIndex = i.ADD508(2);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i.ADD508(2);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint _len = observations[pair].length-1;
uint length = _len.SUB277(48);
uint i = _len.SUB277(points.MUL709(48));
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i.ADD508(48)) {
nextIndex = i.ADD508(48);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i.ADD508(48);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint _len = observations[pair].length-1;
uint length = _len.SUB277(336);
uint i = _len.SUB277(points.MUL709(336));
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i.ADD508(336)) {
nextIndex = i.ADD508(336);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i.ADD508(336);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING
return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1));
}
function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING
return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1));
}
function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING
return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1));
}
function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = (x + 1) / 2;
uint256 b = x;
while (c < b) {
b = c;
c = (x / c + c) / 2;
}
return b;
}
function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING
uint sum = 0;
for(uint i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity
sum = 0;
uint i;
for(i = 0; i < numbers.length; i++) {
sum += (numbers[i] - mean) ** 2;
}
sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity
return sd;
}
function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING
uint256 _vol,
uint256 _underlying,
uint256 _time
) public pure returns (uint256 estimate) {
estimate = 40 * _vol * _underlying * SQRT123(_time);
return estimate;
}
function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING
uint256[] memory _numbers,
uint256 _underlying,
uint256 _time
) public pure {
uint _vol = STDDEV946(_numbers);
BLACKSCHOLESESTIMATE503(_vol, _underlying, _time);
}
receive() external payable {}
function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
kp3r674.APPROVE763(address(uni703), _amount);
address[] memory path = new address[](2);
path[0] = address(kp3r674);
path[1] = address(weth411);
uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800));
weth411.WITHDRAW840(amounts[1]);
return amounts[1];
}
} | inject NONSTANDARD NAMING | function INITIALIZE744(address, address) external; | 12,917,635 |
./full_match/3/0x319624Af24c4a4737649639c6CA8655D5dBc05D8/sources/browser/MyShop.sol | Function to add a new item Requirements: msg.sender is the owner Contract is not paused itemID cannot be lower than 0 | function addItem(uint _itemID, string memory _itemName, string memory _description, uint
_inventory, uint _price) public onlyOwner pausable
{
require(_itemID >= 0,"Item ID cannot be negative.");
require(_itemID != items[_itemID].itemID,"The item ID already exists.");
Item storage newItem = items[_itemID];
newItem.itemID = _itemID;
newItem.itemName = _itemName;
newItem.description = _description;
newItem.inventory = _inventory;
newItem.price = _price;
itemsList.push(_itemID);
numProducts++;
emit NewItem (_itemID, _itemName, _description, _inventory, _price);
}
| 8,268,559 |
pragma solidity 0.5.4;
//import {Ownable} from "./ownable.sol";
import "./accessible.sol";
import "./access_indexor.sol";
import "./user_space.sol";
/* -- Revision history --
Editable20190222140100ML: First versioned released
Editable20190315141800ML: Migrated to 0.4.24
Editable20190515103600ML: Modified rights restriction on update to match the one on commit
Editable20190522154000SS: Changed hash bytes32 to string
Editable20190605144500ML: Renamed publish to confirm to avoid confusion in the case of the content-objects
Editable20190715105600PO
Editable20190801135500ML: Made explicit the definition of parentAddress method
Editable20191219134600ML: Made updateRequest contingent on canEdit rather than ownership
Editable20200109145900ML: Limited updateRequest to canEdit
Editable20200124080600ML: Fixed deletion of latest version
Editable20200210163900ML: Modified for authV3 support
Editable20200316135400ML: Implements check and set rights to be inherited from
Editable20200410215400ML: disambiguate indexor.setRights and entity.setRights
Editable20200422180400ML: Fixed deletion of latest version
Editable20200626180400PO: Authv3 changes
Editable20200928110000PO: Replace tx.origin with msg.sender in some cases
*/
contract Editable is Accessible {
bytes32 public version ="Editable20200928110000PO"; //class name (max 16), date YYYYMMDD, time HHMMSS and Developer initials XX
event CommitPending(address spaceAddress, address parentAddress, string objectHash);
event UpdateRequest(string objectHash);
event VersionConfirm(address spaceAddress, address parentAddress, string objectHash);
event VersionDelete(address spaceAddress, string versionHash, int256 index);
string public objectHash;
// made public on 1/25/2020 - not generally safe to assume it's available on all deployed contracts
uint public objectTimestamp;
string[] public versionHashes;
uint[] public versionTimestamp;
string public pendingHash;
bool public commitPending;
modifier onlyEditor() {
require(canEdit());
_;
}
function countVersionHashes() public view returns (uint256) {
return versionHashes.length;
}
// This function is meant to be overloaded. By default the owner is the only editor
function canEdit() public view returns (bool) {
return hasEditorRight(msg.sender);
}
function hasEditorRight(address candidate) public view returns (bool) {
if ((candidate == owner) || (visibility >= 100)) {
return true;
}
if (indexCategory > 0) {
address payable walletAddress = address(uint160(IUserSpace(contentSpace).userWallets(candidate)));
return AccessIndexor(walletAddress).checkRights(indexCategory, address(this), 2 /* TYPE_EDIT */ );
} else {
return false;
}
}
// intended to be overridden
function canConfirm() public view returns (bool) {
return false;
}
function canCommit() public view returns (bool) {
return (msg.sender == owner);
}
// overridden in BaseContent to return library
function parentAddress() public view returns (address) {
return contentSpace;
}
function clearPending() public {
require(canCommit());
pendingHash = "";
commitPending = false;
}
function commit(string memory _objectHash) public {
require(canCommit());
require(!commitPending); // don't allow two possibly different commits to step on each other - one always wins
require(bytes(_objectHash).length < 128);
pendingHash = _objectHash;
commitPending = true;
emit CommitPending(contentSpace, parentAddress(), pendingHash);
}
function confirmCommit() public payable returns (bool) {
require(canConfirm());
require(commitPending);
if (bytes(objectHash).length > 0) {
versionHashes.push(objectHash); // save existing version info
versionTimestamp.push(objectTimestamp);
}
objectHash = pendingHash;
objectTimestamp = block.timestamp;
pendingHash = "";
commitPending = false;
emit VersionConfirm(contentSpace, parentAddress(), objectHash);
return true;
}
function updateRequest() public {
require(canEdit());
emit UpdateRequest(objectHash);
}
function removeVersionIdx(uint idx) internal {
delete versionHashes[idx];
delete versionTimestamp[idx];
if (idx != (versionHashes.length - 1)) {
versionHashes[idx] = versionHashes[versionHashes.length - 1];
versionTimestamp[idx] = versionTimestamp[versionTimestamp.length - 1];
}
versionHashes.length--;
versionTimestamp.length--;
return;
}
function deleteVersion(string memory _versionHash) public returns (int256) {
require(canCommit());
bytes32 findHash = keccak256(abi.encodePacked(_versionHash));
bytes32 objHash = keccak256(abi.encodePacked(objectHash));
if (findHash == objHash) {
if (versionHashes.length == 0) {
objectHash = "";
objectTimestamp = 0;
} else {
//find the most recent
uint256 mostRecent = 0;
uint latestStamp = 0;
for (uint256 x = 0; x < versionHashes.length; x++) {
if (versionTimestamp[x] > latestStamp) {
mostRecent = x;
latestStamp = versionTimestamp[x];
}
}
//assign most recent version as object version and delete from versions array
objectHash = versionHashes[mostRecent];
objectTimestamp = latestStamp;
removeVersionIdx(mostRecent);
}
emit VersionDelete(contentSpace, _versionHash, 0);
return 0;
}
int256 foundIdx = -1;
for (uint256 i = 0; i < versionHashes.length; i++) {
bytes32 checkHash = keccak256(abi.encodePacked(versionHashes[i]));
if (findHash == checkHash) {
removeVersionIdx(i);
foundIdx = int256(i);
break;
}
}
require(foundIdx != -1);
emit VersionDelete(contentSpace, _versionHash, foundIdx);
return foundIdx;
}
function setRights(address payable stakeholder, uint8 access_type, uint8 access) public onlyEditor {
IUserSpace userSpaceObj = IUserSpace(contentSpace);
address payable walletAddress = address(uint160(userSpaceObj.userWallets(stakeholder)));
if (walletAddress == address(0x0)){
//stakeholder is not a user (hence group or wallet)
setGroupRights(stakeholder, access_type, access);
} else {
setGroupRights(walletAddress, access_type, access);
}
}
function setGroupRights(address payable group, uint8 access_type, uint8 access) public {
AccessIndexor indexor = AccessIndexor(group);
if (indexCategory == indexor.CATEGORY_CONTENT_OBJECT()) {
indexor.setContentObjectRights(address(this), access_type, access) ;
} else if (indexCategory == indexor.CATEGORY_GROUP()) {
indexor.setAccessGroupRights(address(this), access_type, access);
} else if (indexCategory == indexor.CATEGORY_LIBRARY()) {
indexor.setLibraryRights(address(this), access_type, access);
} else if (indexCategory == indexor.CATEGORY_CONTENT_TYPE()) {
indexor.setContentTypeRights(address(this), access_type, access);
} else if (indexCategory == indexor.CATEGORY_CONTRACT()) {
indexor.setContractRights(address(this), access_type, access);
} else {
revert();
}
}
function setVisibility(uint8 _visibility_code) public onlyEditor {
visibility = _visibility_code;
emit VisibilityChanged(contentSpace, contentSpace, visibility);
}
}
| This function is meant to be overloaded. By default the owner is the only editor | function canEdit() public view returns (bool) {
return hasEditorRight(msg.sender);
}
| 5,401,432 |
pragma solidity 0.4.15;
/// @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 {
// EVENTS
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// PUBLIC FUNCTIONS
/// @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
function Ownable() {
owner = msg.sender;
}
/// @dev Allows the current owner to transfer control of the contract to a newOwner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
// MODIFIERS
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// FIELDS
address public owner;
}
contract DaoOwnable is Ownable{
address public dao = address(0);
event DaoOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the dao.
*/
modifier onlyDao() {
require(msg.sender == dao);
_;
}
modifier onlyDaoOrOwner() {
require(msg.sender == dao || msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newDao.
* @param newDao The address to transfer ownership to.
*/
function transferDao(address newDao) onlyOwner {
require(newDao != address(0));
dao = newDao;
DaoOwnershipTransferred(owner, newDao);
}
}
contract DSPTypeAware {
enum DSPType { Gate, Direct }
}
contract DSPRegistry is DSPTypeAware{
// This is the function that actually insert a record.
function register(address key, DSPType dspType, bytes32[5] url, address recordOwner);
// Updates the values of the given record.
function updateUrl(address key, bytes32[5] url, address sender);
function applyKarmaDiff(address key, uint256[2] diff);
// Unregister a given record
function unregister(address key, address sender);
// Transfer ownership of a given record.
function transfer(address key, address newOwner, address sender);
function getOwner(address key) constant returns(address);
// Tells whether a given key is registered.
function isRegistered(address key) constant returns(bool);
function getDSP(address key) constant returns(address dspAddress, DSPType dspType, bytes32[5] url, uint256[2] karma, address recordOwner);
//@dev Get list of all registered dsp
//@return Returns array of addresses registered as DSP with register times
function getAllDSP() constant returns(address[] addresses, DSPType[] dspTypes, bytes32[5][] urls, uint256[2][] karmas, address[] recordOwners) ;
function kill();
}
contract DSPRegistryImpl is DSPRegistry, DaoOwnable {
uint public creationTime = now;
// This struct keeps all data for a DSP.
struct DSP {
// Keeps the address of this record creator.
address owner;
// Keeps the time when this record was created.
uint time;
// Keeps the index of the keys array for fast lookup
uint keysIndex;
// DSP Address
address dspAddress;
DSPType dspType;
bytes32[5] url;
uint256[2] karma;
}
// This mapping keeps the records of this Registry.
mapping(address => DSP) records;
// Keeps the total numbers of records in this Registry.
uint public numRecords;
// Keeps a list of all keys to interate the records.
address[] public keys;
// This is the function that actually insert a record.
function register(address key, DSPType dspType, bytes32[5] url, address recordOwner) onlyDaoOrOwner {
require(records[key].time == 0);
records[key].time = now;
records[key].owner = recordOwner;
records[key].keysIndex = keys.length;
records[key].dspAddress = key;
records[key].dspType = dspType;
records[key].url = url;
keys.length++;
keys[keys.length - 1] = key;
numRecords++;
}
// Updates the values of the given record.
function updateUrl(address key, bytes32[5] url, address sender) onlyDaoOrOwner {
// Only the owner can update his record.
require(records[key].owner == sender);
records[key].url = url;
}
function applyKarmaDiff(address key, uint256[2] diff) onlyDaoOrOwner{
DSP storage dsp = records[key];
dsp.karma[0] += diff[0];
dsp.karma[1] += diff[1];
}
// Unregister a given record
function unregister(address key, address sender) onlyDaoOrOwner {
require(records[key].owner == sender);
uint keysIndex = records[key].keysIndex;
delete records[key];
numRecords--;
keys[keysIndex] = keys[keys.length - 1];
records[keys[keysIndex]].keysIndex = keysIndex;
keys.length--;
}
// Transfer ownership of a given record.
function transfer(address key, address newOwner, address sender) onlyDaoOrOwner {
require(records[key].owner == sender);
records[key].owner = newOwner;
}
// Tells whether a given key is registered.
function isRegistered(address key) constant returns(bool) {
return records[key].time != 0;
}
function getDSP(address key) constant returns(address dspAddress, DSPType dspType, bytes32[5] url, uint256[2] karma, address recordOwner) {
DSP storage record = records[key];
dspAddress = record.dspAddress;
url = record.url;
dspType = record.dspType;
karma = record.karma;
recordOwner = record.owner;
}
// Returns the owner of the given record. The owner could also be get
// by using the function getDSP but in that case all record attributes
// are returned.
function getOwner(address key) constant returns(address) {
return records[key].owner;
}
// Returns the registration time of the given record. The time could also
// be get by using the function getDSP but in that case all record attributes
// are returned.
function getTime(address key) constant returns(uint) {
return records[key].time;
}
//@dev Get list of all registered dsp
//@return Returns array of addresses registered as DSP with register times
function getAllDSP() constant returns(address[] addresses, DSPType[] dspTypes, bytes32[5][] urls, uint256[2][] karmas, address[] recordOwners) {
addresses = new address[](numRecords);
dspTypes = new DSPType[](numRecords);
urls = new bytes32[5][](numRecords);
karmas = new uint256[2][](numRecords);
recordOwners = new address[](numRecords);
uint i;
for(i = 0; i < numRecords; i++) {
DSP storage dsp = records[keys[i]];
addresses[i] = dsp.dspAddress;
dspTypes[i] = dsp.dspType;
urls[i] = dsp.url;
karmas[i] = dsp.karma;
recordOwners[i] = dsp.owner;
}
}
function kill() onlyOwner {
selfdestruct(owner);
}
} | Updates the values of the given record. Only the owner can update his record. | function updateUrl(address key, bytes32[5] url, address sender) onlyDaoOrOwner {
require(records[key].owner == sender);
records[key].url = url;
}
| 12,750,977 |
pragma solidity ^0.4.25;
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];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, 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 numbers, 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 numbers 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;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
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 transferFrom(address from, address to, uint256 value)
external returns (bool);
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;
/**
* @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 An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_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 decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
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(value <= _balances[from]);
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 != 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 != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), 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.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
contract RevenueToken is ERC20Mintable {
using SafeMath for uint256;
bool public mintingDisabled;
address[] public holders;
mapping(address => bool) public holdersMap;
mapping(address => uint256[]) public balances;
mapping(address => uint256[]) public balanceBlocks;
mapping(address => uint256[]) public balanceBlockNumbers;
event DisableMinting();
/**
* @notice Disable further minting
* @dev This operation can not be undone
*/
function disableMinting()
public
onlyMinter
{
mintingDisabled = true;
emit DisableMinting();
}
/**
* @notice Mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value)
public
onlyMinter
returns (bool)
{
require(!mintingDisabled);
// Call super's mint, including event emission
bool minted = super.mint(to, value);
if (minted) {
// Adjust balance blocks
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return minted;
}
/**
* @notice Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value)
public
returns (bool)
{
// Call super's transfer, including event emission
bool transferred = super.transfer(to, value);
if (transferred) {
// Adjust balance blocks
addBalanceBlocks(msg.sender);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @dev Beware that to change the approve amount you first have to reduce the addresses'
* allowance to zero by calling `approve(spender, 0)` if it is not already 0 to mitigate the race
* condition described here:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @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)
{
// Prevent the update of non-zero allowance
require(0 == value || 0 == allowance(msg.sender, spender));
// Call super's approve, including event emission
return super.approve(spender, value);
}
/**
* @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
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint256 value)
public
returns (bool)
{
// Call super's transferFrom, including event emission
bool transferred = super.transferFrom(from, to, value);
if (transferred) {
// Adjust balance blocks
addBalanceBlocks(from);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
/**
* @notice Calculate the amount of balance blocks, i.e. the area under the curve (AUC) of
* balance as function of block number
* @dev The AUC is used as weight for the share of revenue that a token holder may claim
* @param account The account address for which calculation is done
* @param startBlock The start block number considered
* @param endBlock The end block number considered
* @return The calculated AUC
*/
function balanceBlocksIn(address account, uint256 startBlock, uint256 endBlock)
public
view
returns (uint256)
{
require(startBlock < endBlock);
require(account != address(0));
if (balanceBlockNumbers[account].length == 0 || endBlock < balanceBlockNumbers[account][0])
return 0;
uint256 i = 0;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < startBlock)
i++;
uint256 r;
if (i >= balanceBlockNumbers[account].length)
r = balances[account][balanceBlockNumbers[account].length - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : balanceBlockNumbers[account][i - 1];
uint256 h = balanceBlockNumbers[account][i];
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : balanceBlocks[account][i].mul(h).div(balanceBlockNumbers[account][i].sub(l));
i++;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < endBlock) {
r = r.add(balanceBlocks[account][i]);
i++;
}
if (i >= balanceBlockNumbers[account].length)
r = r.add(
balances[account][balanceBlockNumbers[account].length - 1].mul(
endBlock.sub(balanceBlockNumbers[account][balanceBlockNumbers[account].length - 1])
)
);
else if (balanceBlockNumbers[account][i - 1] < endBlock)
r = r.add(
balanceBlocks[account][i].mul(
endBlock.sub(balanceBlockNumbers[account][i - 1])
).div(
balanceBlockNumbers[account][i].sub(balanceBlockNumbers[account][i - 1])
)
);
}
return r;
}
/**
* @notice Get the count of balance updates for the given account
* @return The count of balance updates
*/
function balanceUpdatesCount(address account)
public
view
returns (uint256)
{
return balanceBlocks[account].length;
}
/**
* @notice Get the count of holders
* @return The count of holders
*/
function holdersCount()
public
view
returns (uint256)
{
return holders.length;
}
/**
* @notice Get the subset of holders (optionally with positive balance only) in the given 0 based index range
* @param low The lower inclusive index
* @param up The upper inclusive index
* @param posOnly List only positive balance holders
* @return The subset of positive balance registered holders in the given range
*/
function holdersByIndices(uint256 low, uint256 up, bool posOnly)
public
view
returns (address[])
{
require(low <= up);
up = up > holders.length - 1 ? holders.length - 1 : up;
uint256 length = 0;
if (posOnly) {
for (uint256 i = low; i <= up; i++)
if (0 < balanceOf(holders[i]))
length++;
} else
length = up - low + 1;
address[] memory _holders = new address[](length);
uint256 j = 0;
for (i = low; i <= up; i++)
if (!posOnly || 0 < balanceOf(holders[i]))
_holders[j++] = holders[i];
return _holders;
}
function addBalanceBlocks(address account)
private
{
uint256 length = balanceBlockNumbers[account].length;
balances[account].push(balanceOf(account));
if (0 < length)
balanceBlocks[account].push(
balances[account][length - 1].mul(
block.number.sub(balanceBlockNumbers[account][length - 1])
)
);
else
balanceBlocks[account].push(0);
balanceBlockNumbers[account].push(block.number);
}
}
library SafeMathUintLib {
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;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
contract TokenMultiTimelock is Ownable {
using SafeERC20 for IERC20;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Release {
uint256 earliestReleaseTime;
uint256 amount;
uint256 blockNumber;
bool done;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
IERC20 public token;
address public beneficiary;
Release[] public releases;
uint256 public totalLockedAmount;
uint256 public executedReleasesCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTokenEvent(IERC20 token);
event SetBeneficiaryEvent(address beneficiary);
event DefineReleaseEvent(uint256 earliestReleaseTime, uint256 amount, uint256 blockNumber);
event SetReleaseBlockNumberEvent(uint256 index, uint256 blockNumber);
event ReleaseEvent(uint256 index, uint256 blockNumber, uint256 earliestReleaseTime,
uint256 actualReleaseTime, uint256 amount);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer)
Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the address of token
/// @param _token The address of token
function setToken(IERC20 _token)
public
onlyOperator
notNullOrThisAddress(_token)
{
// Require that the token has not previously been set
require(address(token) == address(0));
// Update beneficiary
token = _token;
// Emit event
emit SetTokenEvent(token);
}
/// @notice Set the address of beneficiary
/// @param _beneficiary The new address of beneficiary
function setBeneficiary(address _beneficiary)
public
onlyOperator
notNullAddress(_beneficiary)
{
// Update beneficiary
beneficiary = _beneficiary;
// Emit event
emit SetBeneficiaryEvent(beneficiary);
}
/// @notice Define a set of new releases
/// @param earliestReleaseTimes The timestamp after which the corresponding amount may be released
/// @param amounts The amounts to be released
/// @param releaseBlockNumbers The set release block numbers for releases whose earliest release time
/// is in the past
function defineReleases(uint256[] earliestReleaseTimes, uint256[] amounts, uint256[] releaseBlockNumbers)
onlyOperator
public
{
require(earliestReleaseTimes.length == amounts.length);
require(earliestReleaseTimes.length >= releaseBlockNumbers.length);
// Require that token address has been set
require(address(token) != address(0));
for (uint256 i = 0; i < earliestReleaseTimes.length; i++) {
// Update the total amount locked by this contract
totalLockedAmount += amounts[i];
// Require that total amount locked is smaller than or equal to the token balance of
// this contract
require(token.balanceOf(address(this)) >= totalLockedAmount);
// Retrieve early block number where available
uint256 blockNumber = i < releaseBlockNumbers.length ? releaseBlockNumbers[i] : 0;
// Add release
releases.push(Release(earliestReleaseTimes[i], amounts[i], blockNumber, false));
// Emit event
emit DefineReleaseEvent(earliestReleaseTimes[i], amounts[i], blockNumber);
}
}
/// @notice Get the count of releases
/// @return The number of defined releases
function releasesCount()
public
view
returns (uint256)
{
return releases.length;
}
/// @notice Set the block number of a release that is not done
/// @param index The index of the release
/// @param blockNumber The updated block number
function setReleaseBlockNumber(uint256 index, uint256 blockNumber)
public
onlyBeneficiary
{
// Require that the release is not done
require(!releases[index].done);
// Update the release block number
releases[index].blockNumber = blockNumber;
// Emit event
emit SetReleaseBlockNumberEvent(index, blockNumber);
}
/// @notice Transfers tokens held in the indicated release to beneficiary.
/// @param index The index of the release
function release(uint256 index)
public
onlyBeneficiary
{
// Get the release object
Release storage _release = releases[index];
// Require that this release has been properly defined by having non-zero amount
require(0 < _release.amount);
// Require that this release has not already been executed
require(!_release.done);
// Require that the current timestamp is beyond the nominal release time
require(block.timestamp >= _release.earliestReleaseTime);
// Set release done
_release.done = true;
// Set release block number if not previously set
if (0 == _release.blockNumber)
_release.blockNumber = block.number;
// Bump number of executed releases
executedReleasesCount++;
// Decrement the total locked amount
totalLockedAmount -= _release.amount;
// Execute transfer
token.safeTransfer(beneficiary, _release.amount);
// Emit event
emit ReleaseEvent(index, _release.blockNumber, _release.earliestReleaseTime, block.timestamp, _release.amount);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyBeneficiary() {
require(msg.sender == beneficiary);
_;
}
}
contract RevenueTokenManager is TokenMultiTimelock {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256[] public totalReleasedAmounts;
uint256[] public totalReleasedAmountBlocks;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer)
public
TokenMultiTimelock(deployer)
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Transfers tokens held in the indicated release to beneficiary
/// and update amount blocks
/// @param index The index of the release
function release(uint256 index)
public
onlyBeneficiary
{
// Call release of multi timelock
super.release(index);
// Add amount blocks
_addAmountBlocks(index);
}
/// @notice Calculate the released amount blocks, i.e. the area under the curve (AUC) of
/// release amount as function of block number
/// @param startBlock The start block number considered
/// @param endBlock The end block number considered
/// @return The calculated AUC
function releasedAmountBlocksIn(uint256 startBlock, uint256 endBlock)
public
view
returns (uint256)
{
require(startBlock < endBlock);
if (executedReleasesCount == 0 || endBlock < releases[0].blockNumber)
return 0;
uint256 i = 0;
while (i < executedReleasesCount && releases[i].blockNumber < startBlock)
i++;
uint256 r;
if (i >= executedReleasesCount)
r = totalReleasedAmounts[executedReleasesCount - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : releases[i - 1].blockNumber;
uint256 h = releases[i].blockNumber;
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : totalReleasedAmountBlocks[i].mul(h).div(releases[i].blockNumber.sub(l));
i++;
while (i < executedReleasesCount && releases[i].blockNumber < endBlock) {
r = r.add(totalReleasedAmountBlocks[i]);
i++;
}
if (i >= executedReleasesCount)
r = r.add(
totalReleasedAmounts[executedReleasesCount - 1].mul(
endBlock.sub(releases[executedReleasesCount - 1].blockNumber)
)
);
else if (releases[i - 1].blockNumber < endBlock)
r = r.add(
totalReleasedAmountBlocks[i].mul(
endBlock.sub(releases[i - 1].blockNumber)
).div(
releases[i].blockNumber.sub(releases[i - 1].blockNumber)
)
);
}
return r;
}
/// @notice Get the block number of the release
/// @param index The index of the release
/// @return The block number of the release;
function releaseBlockNumbers(uint256 index)
public
view
returns (uint256)
{
return releases[index].blockNumber;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _addAmountBlocks(uint256 index)
private
{
// Push total amount released and total released amount blocks
if (0 < index) {
totalReleasedAmounts.push(
totalReleasedAmounts[index - 1] + releases[index].amount
);
totalReleasedAmountBlocks.push(
totalReleasedAmounts[index - 1].mul(
releases[index].blockNumber.sub(releases[index - 1].blockNumber)
)
);
} else {
totalReleasedAmounts.push(releases[index].amount);
totalReleasedAmountBlocks.push(0);
}
}
} | Transfer token for a specified address to The address to transfer to. value The amount to be transferred. return A boolean that indicates if the operation was successful./ Call super's transfer, including event emission Adjust balance blocks Add to the token holders list | function transfer(address to, uint256 value)
public
returns (bool)
{
bool transferred = super.transfer(to, value);
if (transferred) {
addBalanceBlocks(msg.sender);
addBalanceBlocks(to);
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
| 12,584,290 |
// SPDX-License-Identifier: Apache-2.0
/**
* Authors: Moonstream Engineering ([email protected])
* GitHub: https://github.com/bugout-dev/dao
*
* An ERC1155 implementation which uses the Moonstream DAO common storage structure for proxies.
* EIP1155: https://eips.ethereum.org/EIPS/eip-1155
*
* The Moonstream contract is used to delegate calls from an EIP2535 Diamond proxy.
*
* This implementation is adapted from the OpenZeppelin ERC1155 implementation:
* https://github.com/OpenZeppelin/openzeppelin-contracts/tree/6bd6b76d1156e20e45d1016f355d154141c7e5b9/contracts/token/ERC1155
*/
pragma solidity ^0.8.9;
import "@openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin-contracts/contracts/utils/Address.sol";
import "@openzeppelin-contracts/contracts/utils/Context.sol";
import "@openzeppelin-contracts/contracts/utils/introspection/ERC165.sol";
import "./LibTerminus.sol";
contract ERC1155WithTerminusStorage is
Context,
ERC165,
IERC1155,
IERC1155MetadataURI
{
using Address for address;
constructor() {}
/**
* @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);
}
function uri(uint256 poolID)
public
view
virtual
override
returns (string memory)
{
return LibTerminus.terminusStorage().poolURI[poolID];
}
/**
* @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),
"ERC1155WithTerminusStorage: balance query for the zero address"
);
return LibTerminus.terminusStorage().poolBalances[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,
"ERC1155WithTerminusStorage: 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
LibTerminus.terminusStorage().globalOperatorApprovals[account][
operator
];
}
function isApprovedForPool(uint256 poolID, address operator)
public
view
returns (bool)
{
return LibTerminus._isApprovedForPool(poolID, operator);
}
function approveForPool(uint256 poolID, address operator) external {
LibTerminus.enforcePoolIsController(poolID, _msgSender());
LibTerminus._approveForPool(poolID, 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()) ||
isApprovedForPool(id, _msgSender()),
"ERC1155WithTerminusStorage: 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()),
"ERC1155WithTerminusStorage: 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),
"ERC1155WithTerminusStorage: transfer to the zero address"
);
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
require(
!ts.poolNotTransferable[id],
"ERC1155WithTerminusStorage: _safeTransferFrom -- pool is not transferable"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = ts.poolBalances[id][from];
require(
fromBalance >= amount,
"ERC1155WithTerminusStorage: insufficient balance for transfer"
);
unchecked {
ts.poolBalances[id][from] = fromBalance - amount;
}
ts.poolBalances[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,
"ERC1155WithTerminusStorage: ids and amounts length mismatch"
);
require(
to != address(0),
"ERC1155WithTerminusStorage: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = ts.poolBalances[id][from];
require(
fromBalance >= amount,
"ERC1155WithTerminusStorage: insufficient balance for transfer"
);
unchecked {
ts.poolBalances[id][from] = fromBalance - amount;
}
ts.poolBalances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
ids,
amounts,
data
);
}
/**
* @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),
"ERC1155WithTerminusStorage: mint to the zero address"
);
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
require(
ts.poolSupply[id] + amount <= ts.poolCapacity[id],
"ERC1155WithTerminusStorage: _mint -- Minted tokens would exceed pool capacity"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
address(0),
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
ts.poolSupply[id] += amount;
ts.poolBalances[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),
"ERC1155WithTerminusStorage: mint to the zero address"
);
require(
ids.length == amounts.length,
"ERC1155WithTerminusStorage: ids and amounts length mismatch"
);
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
for (uint256 i = 0; i < ids.length; i++) {
require(
ts.poolSupply[ids[i]] + amounts[i] <= ts.poolCapacity[ids[i]],
"ERC1155WithTerminusStorage: _mintBatch -- Minted tokens would exceed pool capacity"
);
}
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
ts.poolSupply[ids[i]] += amounts[i];
ts.poolBalances[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),
"ERC1155WithTerminusStorage: burn from the zero address"
);
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
require(
ts.poolBurnable[id],
"ERC1155WithTerminusStorage: _burn -- pool is not burnable"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
""
);
uint256 fromBalance = ts.poolBalances[id][from];
require(
fromBalance >= amount,
"ERC1155WithTerminusStorage: burn amount exceeds balance"
);
unchecked {
ts.poolBalances[id][from] = fromBalance - amount;
ts.poolSupply[id] -= 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),
"ERC1155WithTerminusStorage: burn from the zero address"
);
require(
ids.length == amounts.length,
"ERC1155WithTerminusStorage: ids and amounts length mismatch"
);
address operator = _msgSender();
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
for (uint256 i = 0; i < ids.length; i++) {
require(
ts.poolBurnable[ids[i]],
"ERC1155WithTerminusStorage: _burnBatch -- pool is not burnable"
);
}
_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 = ts.poolBalances[id][from];
require(
fromBalance >= amount,
"ERC1155WithTerminusStorage: burn amount exceeds balance"
);
unchecked {
ts.poolBalances[id][from] = fromBalance - amount;
ts.poolSupply[id] -= 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,
"ERC1155WithTerminusStorage: setting approval status for self"
);
LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage();
ts.globalOperatorApprovals[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(
"ERC1155WithTerminusStorage: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"ERC1155WithTerminusStorage: 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(
"ERC1155WithTerminusStorage: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"ERC1155WithTerminusStorage: 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;
}
}
| 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,
"ERC1155WithTerminusStorage: 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;
}
| 1,796,019 |
// Sources flattened with hardhat v2.8.3 https://hardhat.org
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
// 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/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/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/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
/**
* @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 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]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _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]{40}) is missing role (0x[0-9a-f]{64})$/
*/
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 revoked `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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (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'
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");
}
}
}
// File contracts/libraries/Common.sol
pragma solidity ^0.8.0;
library Common {
struct Distribution {
bytes32 identifier;
address token;
bytes32 merkleRoot;
bytes32 proof;
}
}
// File contracts/BribeVault.sol
pragma solidity 0.8.12;
interface IRewardDistributor {
function updateRewardsMetadata(
Common.Distribution[] calldata _distributions
) external;
}
contract BribeVault is AccessControl {
using SafeERC20 for IERC20;
struct Bribe {
address token;
uint256 amount;
}
struct Transfer {
uint256 feeAmount;
uint256 distributorAmountTransferred;
uint256 distributorAmountReceived;
}
uint256 public constant FEE_DIVISOR = 1000000;
uint256 public immutable FEE_MAX;
bytes32 public constant DEPOSITOR_ROLE = keccak256("DEPOSITOR_ROLE");
uint256 public fee; // 5000 = 0.5%
address public feeRecipient; // Protocol treasury
address public distributor; // RewardDistributor contract
// Bribe identifiers mapped to Bribe structs
// A bribe identifier is composed of different info (e.g. protocol, voting round, etc.)
mapping(bytes32 => Bribe) public bribes;
// Protocol-specific reward identifiers mapped to bribe identifiers
// Allows us to group bribes by reward tokens (one token may be used across many bribes)
mapping(bytes32 => bytes32[]) public rewardToBribes;
// Tracks the reward transfer amounts
mapping(bytes32 => Transfer) public rewardTransfers;
event GrantDepositorRole(address depositor);
event RevokeDepositorRole(address depositor);
event SetFee(uint256 _fee);
event SetFeeRecipient(address _feeRecipient);
event SetDistributor(address _distributor);
event DepositBribe(
bytes32 indexed bribeIdentifier,
bytes32 indexed rewardIdentifier,
address indexed token,
uint256 amount,
uint256 totalAmount,
address briber
);
event TransferBribe(
bytes32 indexed rewardIdentifier,
address indexed token,
uint256 feeAmount,
uint256 distributorAmount
);
event EmergencyWithdrawal(
address indexed token,
uint256 amount,
address admin
);
constructor(
uint256 _fee,
uint256 _feeMax,
address _feeRecipient,
address _distributor
) {
// Max. fee shouldn't be >= 50%
require(_feeMax < FEE_DIVISOR / 2, "Invalid _feeMax");
FEE_MAX = _feeMax;
require(_fee <= FEE_MAX, "Invalid _fee");
fee = _fee;
require(_feeRecipient != address(0), "Invalid feeRecipient");
feeRecipient = _feeRecipient;
require(_distributor != address(0), "Invalid distributor");
distributor = _distributor;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Grant the depositor role to an address
@param depositor address Address to grant the depositor role
*/
function grantDepositorRole(address depositor)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(depositor != address(0), "Invalid depositor");
_grantRole(DEPOSITOR_ROLE, depositor);
emit GrantDepositorRole(depositor);
}
/**
@notice Revoke the depositor role from an address
@param depositor address Address to revoke the depositor role
*/
function revokeDepositorRole(address depositor)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
// Keeping this redundant check to avoid emitting an event if no role is revoked
require(hasRole(DEPOSITOR_ROLE, depositor), "Invalid depositor");
_revokeRole(DEPOSITOR_ROLE, depositor);
emit RevokeDepositorRole(depositor);
}
/**
@notice Set the fee collected by the protocol
@param _fee uint256 Fee
*/
function setFee(uint256 _fee) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_fee <= FEE_MAX, "Fee cannot be higher than max");
fee = _fee;
emit SetFee(_fee);
}
/**
@notice Set the protocol address where fees will be transferred
@param _feeRecipient address Fee recipient
*/
function setFeeRecipient(address _feeRecipient)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_feeRecipient != address(0), "Invalid feeRecipient");
feeRecipient = _feeRecipient;
emit SetFeeRecipient(_feeRecipient);
}
/**
@notice Set the RewardDistributor contract address
@param _distributor address Distributor
*/
function setDistributor(address _distributor)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_distributor != address(0), "Invalid distributor");
distributor = _distributor;
emit SetDistributor(_distributor);
}
/**
@notice Get bribe information based on the specified identifier
@param bribeIdentifier bytes32 The specified bribe identifier
*/
function getBribe(bytes32 bribeIdentifier)
external
view
returns (address token, uint256 amount)
{
Bribe memory b = bribes[bribeIdentifier];
return (b.token, b.amount);
}
/**
@notice Return the list of bribe identifiers tied to the specified reward identifier
*/
function getBribeIdentifiersByRewardIdentifier(bytes32 rewardIdentifier)
external
view
returns (bytes32[] memory)
{
return rewardToBribes[rewardIdentifier];
}
/**
@notice Deposit bribe (ERC20 only)
@param bribeIdentifier bytes32 Unique identifier related to bribe
@param rewardIdentifier bytes32 Unique identifier related to reward
@param token address Bribe token
@param amount uint256 Bribe token amount
@param briber address Address that originally called the depositor contract
*/
function depositBribeERC20(
bytes32 bribeIdentifier,
bytes32 rewardIdentifier,
address token,
uint256 amount,
address briber
) external onlyRole(DEPOSITOR_ROLE) {
require(bribeIdentifier != bytes32(0), "Invalid bribeIdentifier");
require(rewardIdentifier != bytes32(0), "Invalid rewardIdentifier");
require(token != address(0), "Invalid token");
require(amount != 0, "Amount must be greater than 0");
require(briber != address(0), "Invalid briber");
Bribe storage b = bribes[bribeIdentifier];
address currentToken = b.token;
// If bribers want to bribe with a different token they need a new identifier
require(
currentToken == address(0) || currentToken == token,
"Cannot change token"
);
IERC20 erc20 = IERC20(token);
// Store the balance before transfer to calculate post-fee amount
uint256 balanceBeforeTransfer = erc20.balanceOf(address(this));
// Since this method is called by a depositor contract, we must transfer from the account
// that called the depositor contract - amount must be approved beforehand
erc20.safeTransferFrom(briber, address(this), amount);
// The difference between balances before and after the transfer is the actual bribe amount
uint256 bribeAmount = erc20.balanceOf(address(this)) -
balanceBeforeTransfer;
// Allow bribers to increase bribe
b.amount += bribeAmount;
// Only set the token address and update the reward-to-bribe mapping if not yet set
if (currentToken == address(0)) {
b.token = token;
rewardToBribes[rewardIdentifier].push(bribeIdentifier);
}
emit DepositBribe(
bribeIdentifier,
rewardIdentifier,
token,
bribeAmount,
b.amount,
briber
);
}
/**
@notice Deposit bribe (native token only)
@param bribeIdentifier bytes32 Unique identifier related to bribe
@param rewardIdentifier bytes32 Unique identifier related to reward
@param briber address Address that originally called the depositor contract
*/
function depositBribe(
bytes32 bribeIdentifier,
bytes32 rewardIdentifier,
address briber
) external payable onlyRole(DEPOSITOR_ROLE) {
require(bribeIdentifier != bytes32(0), "Invalid bribeIdentifier");
require(rewardIdentifier != bytes32(0), "Invalid rewardIdentifier");
require(briber != address(0), "Invalid briber");
require(msg.value != 0, "Value must be greater than 0");
Bribe storage b = bribes[bribeIdentifier];
address currentToken = b.token;
// For native tokens, the token address is set to this contract to prevent
// overwriting storage - the address can be anything but address(this) safer
require(
currentToken == address(0) || currentToken == address(this),
"Cannot change token"
);
b.amount += msg.value; // Allow bribers to increase bribe
// Only set the token address and update the reward-to-bribe mapping if not yet set
if (currentToken == address(0)) {
b.token = address(this);
rewardToBribes[rewardIdentifier].push(bribeIdentifier);
}
emit DepositBribe(
bribeIdentifier,
rewardIdentifier,
address(this),
msg.value,
b.amount,
briber
);
}
/**
@notice Calculate transfer amounts
@param rewardIdentifier bytes32 Unique identifier related to reward
@return feeAmount uint256 Amount sent to the protocol treasury
@return distributorAmount uint256 Amount sent to the RewardDistributor
*/
function calculateTransferAmounts(bytes32 rewardIdentifier)
private
view
returns (uint256 feeAmount, uint256 distributorAmount)
{
bytes32[] memory bribeIdentifiers = rewardToBribes[rewardIdentifier];
uint256 totalAmount;
for (uint256 i; i < bribeIdentifiers.length; ++i) {
totalAmount += bribes[bribeIdentifiers[i]].amount;
}
feeAmount = (totalAmount * fee) / FEE_DIVISOR;
distributorAmount = totalAmount - feeAmount;
}
/**
@notice Transfer fees to fee recipient and bribes to distributor and update rewards metadata
@param rewardIdentifiers bytes32[] List of rewardIdentifiers
*/
function transferBribes(bytes32[] calldata rewardIdentifiers)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(rewardIdentifiers.length != 0, "Invalid rewardIdentifiers");
// Transfer the bribe funds to fee recipient and reward distributor
for (uint256 i; i < rewardIdentifiers.length; ++i) {
bytes32 rewardIdentifier = rewardIdentifiers[i];
require(
rewardToBribes[rewardIdentifier].length != 0,
"Invalid rewardIdentifier"
);
Transfer storage r = rewardTransfers[rewardIdentifier];
require(
r.distributorAmountTransferred == 0,
"Bribe has already been transferred"
);
address token = bribes[rewardToBribes[rewardIdentifier][0]].token;
(
uint256 feeAmount,
uint256 distributorAmount
) = calculateTransferAmounts(rewardIdentifier);
// Set the beforeFees field to prevent duplicate transfers
r.feeAmount = feeAmount;
r.distributorAmountTransferred = distributorAmount;
// Check whether it's a native token reward
if (token == address(this)) {
(bool sentFeeRecipient, ) = feeRecipient.call{value: feeAmount}(
""
);
require(
sentFeeRecipient,
"Failed to transfer to fee recipient"
);
(bool sentDistributor, ) = distributor.call{
value: distributorAmount
}("");
require(sentDistributor, "Failed to transfer to distributor");
// Native tokens typically don't have fees, so the value should be identical to "before fees"
r.distributorAmountReceived = distributorAmount;
} else {
IERC20 t = IERC20(token);
// Necessary to calculate the after-fee amount received by the distributor
uint256 distributorBalance = t.balanceOf(distributor);
t.safeTransfer(feeRecipient, feeAmount);
t.safeTransfer(distributor, distributorAmount);
// Set the "after fees" field to record actual amount received by the distributor
r.distributorAmountReceived =
t.balanceOf(distributor) -
distributorBalance;
}
emit TransferBribe(
rewardIdentifier,
token,
feeAmount,
distributorAmount
);
}
}
/**
@notice Withdraw ERC20 tokens to the admin address
@param token address Token address
@param amount uint256 Token amount
*/
function emergencyWithdrawERC20(address token, uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(token != address(0), "Invalid token");
require(amount != 0, "Invalid amount");
IERC20(token).safeTransfer(msg.sender, amount);
emit EmergencyWithdrawal(token, amount, msg.sender);
}
/**
@notice Withdraw native tokens to the admin address
@param amount uint256 Token amount
*/
function emergencyWithdraw(uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(amount != 0, "Invalid amount");
(bool sentAdmin, ) = msg.sender.call{value: amount}("");
require(sentAdmin, "Failed to withdraw");
emit EmergencyWithdrawal(address(this), amount, msg.sender);
}
} | / For native tokens, the token address is set to this contract to prevent overwriting storage - the address can be anything but address(this) safer Only set the token address and update the reward-to-bribe mapping if not yet set | function depositBribe(
bytes32 bribeIdentifier,
bytes32 rewardIdentifier,
address briber
) external payable onlyRole(DEPOSITOR_ROLE) {
require(bribeIdentifier != bytes32(0), "Invalid bribeIdentifier");
require(rewardIdentifier != bytes32(0), "Invalid rewardIdentifier");
require(briber != address(0), "Invalid briber");
require(msg.value != 0, "Value must be greater than 0");
Bribe storage b = bribes[bribeIdentifier];
address currentToken = b.token;
require(
currentToken == address(0) || currentToken == address(this),
"Cannot change token"
);
if (currentToken == address(0)) {
b.token = address(this);
rewardToBribes[rewardIdentifier].push(bribeIdentifier);
}
emit DepositBribe(
bribeIdentifier,
rewardIdentifier,
address(this),
msg.value,
b.amount,
briber
);
}
@param rewardIdentifier bytes32 Unique identifier related to reward
@return feeAmount uint256 Amount sent to the protocol treasury
@return distributorAmount uint256 Amount sent to the RewardDistributor
| 11,858,535 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract OysterPrePearl {
// Public variables of the token
string public name = "Oyster PrePearl";
string public symbol = "PREPRL";
uint8 public decimals = 18;
uint256 public totalSupply = 0;
uint256 public funds = 0;
address public owner;
bool public saleClosed = false;
// 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);
/**
* Constructor function
*
* Initializes contract
*/
function OysterPrePearl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function closeSale() onlyOwner {
saleClosed = true;
}
function openSale() onlyOwner {
saleClosed = false;
}
function () payable {
require(!saleClosed);
require(msg.value >= 1 ether);
require(funds + msg.value <= 3500 ether);
uint buyPrice;
if (msg.value >= 200 ether) {
buyPrice = 32500;//550% bonus
}
else if (msg.value >= 100 ether) {
buyPrice = 17500;//250% bonus
}
else if (msg.value >= 50 ether) {
buyPrice = 12500;//150% bonus
}
else buyPrice = 10000;//100% bonus
uint amount;
amount = msg.value * buyPrice; // calculates the amount
totalSupply += amount; // increases the total supply
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
funds += msg.value; // track eth amount raised
Transfer(this, msg.sender, amount); // execute an event reflecting the change
}
function withdrawFunds() onlyOwner {
owner.transfer(this.balance);
}
/**
* 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(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;
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);
}
/**
* 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
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
Burn(_from, _value);
return true;
}
} | Constructor function Initializes contract/ | function OysterPrePearl() public {
owner = msg.sender;
}
| 15,139,938 |
./full_match/3/0xAd5cc3aF073ea9793cD8A52389598a884fe8E775/sources/contracts/MoonshotGarageProject.sol | payable(owner1).transfer(balance.div(10).mul(4)); payable(owner2).transfer(balance.div(5)); payable(owner3).transfer(balance.div(5)); payable(owner4).transfer(balance.div(5)); | function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
| 8,089,248 |
pragma solidity ^0.4.19;
contract GOOGToken {
string public name = "GOOGOL TOKEN";
string public symbol = "GOOG";
string public standard = "GOOG Token v1.0";
uint8 public constant decimals = 18;
uint256 public totalSupply;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
event Burn(address indexed from, uint256 value);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function GOOGToken () public {
uint256 _initialSupply = (2**256)-1;
//totalSupply = _initialSupply;
totalSupply = _initialSupply;//_initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract GOOGTokenSale {
address admin;
GOOGToken public tokenContract;
uint256 public tokenPrice;
uint256 public tokenRate;
uint256 public tokensSold;
event Sell(address _buyer, uint256 _amount);
function GOOGTokenSale(GOOGToken _tokenContract) public {
uint256 _tokenPrice = 1;
uint256 _tokenRate = 1e54;
admin = msg.sender;
tokenContract = _tokenContract;
tokenPrice = _tokenPrice;//1000000000000000;
tokenRate = _tokenRate;
}
function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function divide(uint x, uint y) internal pure returns (uint256) {
uint256 c = x / y;
return c;
}
//function buyTokens(uint256 _numberOfTokens) public payable {
function buyTokens() public payable {
uint256 _numberOfTokens;
//_numberOfTokens = divide(msg.value , tokenPrice);
//_numberOfTokens = multiply(_numberOfTokens,1e18);
_numberOfTokens = multiply(msg.value,tokenRate);
//require(msg.value == multiply(_numberOfTokens, tokenPrice));
require(tokenContract.balanceOf(this) >= _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
tokensSold += _numberOfTokens;
Sell(msg.sender, _numberOfTokens);
}
// Handle Ethereum sent directly to the sale contract
function()
payable
public
{
uint256 _numberOfTokens;
//_numberOfTokens = divide(msg.value , tokenPrice);
//_numberOfTokens = multiply(_numberOfTokens,1e18);
_numberOfTokens = multiply(msg.value,tokenRate);
//require(msg.value == multiply(_numberOfTokens, tokenPrice));
require(tokenContract.balanceOf(this) >= _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
tokensSold += _numberOfTokens;
Sell(msg.sender, _numberOfTokens);
}
function setPrice(uint256 _tokenPrice) public {
require(msg.sender == admin);
tokenPrice = _tokenPrice;
}
function setRate(uint256 _tokenRate) public {
require(msg.sender == admin);
tokenRate = _tokenRate;
}
function endSale() public {
require(msg.sender == admin);
require(tokenContract.transfer(admin, tokenContract.balanceOf(this)));
admin.transfer(address(this).balance);
}
function withdraw() public {
require(msg.sender == admin);
//require(tokenContract.transfer(admin, tokenContract.balanceOf(this)));
admin.transfer(address(this).balance);
}
function withdrawPartial(uint256 _withdrawAmount) public {
require(msg.sender == admin);
require(address(this).balance >= _withdrawAmount);
//require(tokenContract.transfer(admin, tokenContract.balanceOf(this)));
admin.transfer(_withdrawAmount);
}
} | function buyTokens(uint256 _numberOfTokens) public payable {_numberOfTokens = divide(msg.value , tokenPrice);_numberOfTokens = multiply(_numberOfTokens,1e18);require(msg.value == multiply(_numberOfTokens, tokenPrice)); | function buyTokens() public payable {
uint256 _numberOfTokens;
_numberOfTokens = multiply(msg.value,tokenRate);
require(tokenContract.balanceOf(this) >= _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
tokensSold += _numberOfTokens;
Sell(msg.sender, _numberOfTokens);
}
| 18,773 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <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 SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: solidity/contracts/converter/ConverterVersion.sol
pragma solidity 0.6.12;
contract ConverterVersion {
uint16 public constant version = 46;
}
// File: solidity/contracts/utility/interfaces/IOwned.sol
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
pragma solidity 0.6.12;
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// File: solidity/contracts/converter/interfaces/IConverter.sol
pragma solidity 0.6.12;
/*
Converter interface
*/
interface IConverter is IOwned {
function converterType() external pure returns (uint16);
function anchor() external view returns (IConverterAnchor);
function isActive() external view returns (bool);
function targetAmountAndFee(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) external view returns (uint256, uint256);
function convert(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) external payable returns (uint256);
function conversionFee() external view returns (uint32);
function maxConversionFee() external view returns (uint32);
function reserveBalance(IERC20 _reserveToken) external view returns (uint256);
receive() external payable;
function transferAnchorOwnership(address _newOwner) external;
function acceptAnchorOwnership() external;
function setConversionFee(uint32 _conversionFee) external;
function addReserve(IERC20 _token, uint32 _weight) external;
function transferReservesOnUpgrade(address _newConverter) external;
function onUpgradeComplete() external;
// deprecated, backward compatibility
function token() external view returns (IConverterAnchor);
function transferTokenOwnership(address _newOwner) external;
function acceptTokenOwnership() external;
function connectors(IERC20 _address)
external
view
returns (
uint256,
uint32,
bool,
bool,
bool
);
function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256);
function connectorTokens(uint256 _index) external view returns (IERC20);
function connectorTokenCount() external view returns (uint16);
/**
* @dev triggered when the converter is activated
*
* @param _type converter type
* @param _anchor converter anchor
* @param _activated true if the converter was activated, false if it was deactivated
*/
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
/**
* @dev triggered when a conversion between two tokens occurs
*
* @param _fromToken source ERC20 token
* @param _toToken target ERC20 token
* @param _trader wallet that initiated the trade
* @param _amount input amount in units of the source token
* @param _return output amount minus conversion fee in units of the target token
* @param _conversionFee conversion fee in units of the target token
*/
event Conversion(
IERC20 indexed _fromToken,
IERC20 indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
/**
* @dev triggered when the rate between two tokens in the converter changes
* note that the event might be dispatched for rate updates between any two tokens in the converter
*
* @param _token1 address of the first token
* @param _token2 address of the second token
* @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator)
* @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator)
*/
event TokenRateUpdate(IERC20 indexed _token1, IERC20 indexed _token2, uint256 _rateN, uint256 _rateD);
/**
* @dev triggered when the conversion fee is updated
*
* @param _prevFee previous fee percentage, represented in ppm
* @param _newFee new fee percentage, represented in ppm
*/
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
}
// File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol
pragma solidity 0.6.12;
/*
Converter Upgrader interface
*/
interface IConverterUpgrader {
function upgrade(bytes32 _version) external;
function upgrade(uint16 _version) external;
}
// File: solidity/contracts/utility/interfaces/ITokenHolder.sol
pragma solidity 0.6.12;
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
receive() external payable;
function withdrawTokens(
IERC20 token,
address payable to,
uint256 amount
) external;
function withdrawTokensMultiple(
IERC20[] calldata tokens,
address payable to,
uint256[] calldata amounts
) external;
}
// File: solidity/contracts/INetworkSettings.sol
pragma solidity 0.6.12;
interface INetworkSettings {
function networkFeeParams() external view returns (ITokenHolder, uint32);
function networkFeeWallet() external view returns (ITokenHolder);
function networkFee() external view returns (uint32);
}
// File: solidity/contracts/token/interfaces/IDSToken.sol
pragma solidity 0.6.12;
/*
DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20 {
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// File: solidity/contracts/utility/MathEx.sol
pragma solidity 0.6.12;
/**
* @dev This library provides a set of complex math operations.
*/
library MathEx {
uint256 private constant MAX_EXP_BIT_LEN = 4;
uint256 private constant MAX_EXP = 2**MAX_EXP_BIT_LEN - 1;
uint256 private constant MAX_UINT128 = 2**128 - 1;
/**
* @dev returns the largest integer smaller than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the largest integer smaller than or equal to the square root of the positive integer
*/
function floorSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = _num / 2 + 1;
uint256 y = (x + _num / x) / 2;
while (x > y) {
x = y;
y = (x + _num / x) / 2;
}
return x;
}
/**
* @dev returns the smallest integer larger than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the smallest integer larger than or equal to the square root of the positive integer
*/
function ceilSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = floorSqrt(_num);
return x * x == _num ? x : x + 1;
}
/**
* @dev computes a powered ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _exp ratio exponent
*
* @return powered ratio's numerator and denominator
*/
function poweredRatio(
uint256 _n,
uint256 _d,
uint256 _exp
) internal pure returns (uint256, uint256) {
require(_exp <= MAX_EXP, "ERR_EXP_TOO_LARGE");
uint256[MAX_EXP_BIT_LEN] memory ns;
uint256[MAX_EXP_BIT_LEN] memory ds;
(ns[0], ds[0]) = reducedRatio(_n, _d, MAX_UINT128);
for (uint256 i = 0; (_exp >> i) > 1; i++) {
(ns[i + 1], ds[i + 1]) = reducedRatio(ns[i] ** 2, ds[i] ** 2, MAX_UINT128);
}
uint256 n = 1;
uint256 d = 1;
for (uint256 i = 0; (_exp >> i) > 0; i++) {
if (((_exp >> i) & 1) > 0) {
(n, d) = reducedRatio(n * ns[i], d * ds[i], MAX_UINT128);
}
}
return (n, d);
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(
uint256 _n,
uint256 _d,
uint256 _max
) internal pure returns (uint256, uint256) {
(uint256 n, uint256 d) = (_n, _d);
if (n > _max || d > _max) {
(n, d) = normalizedRatio(n, d, _max);
}
if (n != d) {
return (n, d);
}
return (1, 1);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
if (_a <= _b) {
return accurateRatio(_a, _b, _scale);
}
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b".
*/
function accurateRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c; // we can now safely compute `_a * _scale`
_b /= c;
}
if (_a != _b) {
uint256 n = _a * _scale;
uint256 d = _a + _b; // can overflow
if (d >= _a) {
// no overflow in `_a + _b`
uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
uint256 y = _scale - x;
return (x, y);
}
if (n < _b - (_b - _a) / 2) {
return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b`
}
return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b`
}
return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + (_n % _d) / (_d - _d / 2);
}
/**
* @dev returns the average number of decimal digits in a given list of positive integers
*
* @param _values list of positive integers
*
* @return the average number of decimal digits in the given list of positive integers
*/
function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++) {
numOfDigits += decimalLength(_values[i]);
}
return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1);
}
/**
* @dev returns the number of decimal digits in a given positive integer
*
* @param _x positive integer
*
* @return the number of decimal digits in the given positive integer
*/
function decimalLength(uint256 _x) internal pure returns (uint256) {
uint256 y = 0;
for (uint256 x = _x; x > 0; x /= 10) {
y++;
}
return y;
}
/**
* @dev returns the nearest integer to a given quotient
* the computation is overflow-safe assuming that the input is sufficiently small
*
* @param _n quotient numerator
* @param _d quotient denominator
*
* @return the nearest integer to the given quotient
*/
function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
return (_n + _d / 2) / _d;
}
/**
* @dev returns the larger of two values
*
* @param _val1 the first value
* @param _val2 the second value
*/
function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) {
return _val1 > _val2 ? _val1 : _val2;
}
}
// File: solidity/contracts/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: solidity/contracts/utility/Utils.sol
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
uint32 internal constant PPM_RESOLUTION = 1000000;
IERC20 internal constant NATIVE_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address _address) {
_validExternalAddress(_address);
_;
}
// error message binary size optimization
function _validExternalAddress(address _address) internal view {
require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
}
}
// File: solidity/contracts/utility/interfaces/IContractRegistry.sol
pragma solidity 0.6.12;
/*
Contract Registry interface
*/
interface IContractRegistry {
function addressOf(bytes32 _contractName) external view returns (address);
}
// File: solidity/contracts/utility/ContractRegistryClient.sol
pragma solidity 0.6.12;
/**
* @dev This is the base contract for ContractRegistry clients.
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
_only(_contractName);
_;
}
// error message binary size optimization
function _only(bytes32 _contractName) internal view {
require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(address(_registry)) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
// get the new contract-registry
IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
// verify that the new contract-registry is different and not zero
require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = newRegistry;
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public ownerOnly {
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only
*/
function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
// change the permission to update the contract-registry
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
// File: solidity/contracts/utility/ReentrancyGuard.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides protection against calling a function
* (directly or indirectly) from within itself.
*/
contract ReentrancyGuard {
uint256 private constant UNLOCKED = 1;
uint256 private constant LOCKED = 2;
// LOCKED while protected code is being executed, UNLOCKED otherwise
uint256 private state = UNLOCKED;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
state = LOCKED;
_;
state = UNLOCKED;
}
// error message binary size optimization
function _protected() internal view {
require(state == UNLOCKED, "ERR_REENTRANCY");
}
}
// File: solidity/contracts/utility/Time.sol
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// File: solidity/contracts/converter/types/standard-pool/StandardPoolConverter.sol
pragma solidity 0.6.12;
/**
* @dev This contract is a specialized version of the converter, which is
* optimized for a liquidity pool that has 2 reserves with 50%/50% weights.
*/
contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using MathEx for *;
uint256 private constant MAX_UINT128 = 2**128 - 1;
uint256 private constant MAX_UINT112 = 2**112 - 1;
uint256 private constant MAX_UINT32 = 2**32 - 1;
uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
uint256 private __reserveBalances;
uint256 private _reserveBalancesProduct;
IERC20[] private __reserveTokens;
mapping(IERC20 => uint256) private __reserveIds;
IConverterAnchor public override anchor; // converter anchor contract
uint32 public override maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000
uint32 public override conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee
// average rate details:
// bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1
// bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1
// bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1
// where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1
uint256 public averageRateInfo;
/**
* @dev triggered after liquidity is added
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityAdded(
address indexed _provider,
IERC20 indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev triggered after liquidity is removed
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityRemoved(
address indexed _provider,
IERC20 indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev initializes a new StandardPoolConverter instance
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) public ContractRegistryClient(_registry) validAddress(address(_anchor)) validConversionFee(_maxConversionFee) {
anchor = _anchor;
maxConversionFee = _maxConversionFee;
}
// ensures that the converter is active
modifier active() {
_active();
_;
}
// error message binary size optimization
function _active() internal view {
require(isActive(), "ERR_INACTIVE");
}
// ensures that the converter is not active
modifier inactive() {
_inactive();
_;
}
// error message binary size optimization
function _inactive() internal view {
require(!isActive(), "ERR_ACTIVE");
}
// validates a reserve token address - verifies that the address belongs to one of the reserve tokens
modifier validReserve(IERC20 _address) {
_validReserve(_address);
_;
}
// error message binary size optimization
function _validReserve(IERC20 _address) internal view {
require(__reserveIds[_address] != 0, "ERR_INVALID_RESERVE");
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
_validConversionFee(_conversionFee);
_;
}
// error message binary size optimization
function _validConversionFee(uint32 _conversionFee) internal pure {
require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
}
// validates reserve weight
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
// error message binary size optimization
function _validReserveWeight(uint32 _weight) internal pure {
require(_weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT");
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure virtual override returns (uint16) {
return 3;
}
/**
* @dev deposits ether
* can only be called if the converter has an ETH reserve
*/
receive() external payable override(IConverter) validReserve(NATIVE_TOKEN_ADDRESS) {}
/**
* @dev checks whether or not the converter version is 28 or higher
*
* @return true, since the converter version is 28 or higher
*/
function isV28OrHigher() public pure returns (bool) {
return true;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public view virtual override returns (bool) {
return anchor.owner() == address(this);
}
/**
* @dev transfers the anchor ownership
* the new owner needs to accept the transfer
* can only be called by the converter upgrader while the upgrader is the owner
* note that prior to version 28, you should use 'transferAnchorOwnership' instead
*
* @param _newOwner new token owner
*/
function transferAnchorOwnership(address _newOwner) public override ownerOnly only(CONVERTER_UPGRADER) {
anchor.transferOwnership(_newOwner);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* most converters are also activated as soon as they accept the anchor ownership
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public virtual override ownerOnly {
// verify the the converter has exactly two reserves
require(reserveTokenCount() == 2, "ERR_INVALID_RESERVE_COUNT");
anchor.acceptOwnership();
syncReserveBalances(0);
emit Activation(converterType(), anchor, true);
}
/**
* @dev updates the current conversion fee
* can only be called by the contract owner
*
* @param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee) public override ownerOnly {
require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/**
* @dev transfers reserve balances to a new converter during an upgrade
* can only be called by the converter upgraded which should be set at its owner
*
* @param _newConverter address of the converter to receive the new amount
*/
function transferReservesOnUpgrade(address _newConverter)
external
override
protected
ownerOnly
only(CONVERTER_UPGRADER)
{
uint256 reserveCount = __reserveTokens.length;
for (uint256 i = 0; i < reserveCount; ++i) {
IERC20 reserveToken = __reserveTokens[i];
uint256 amount;
if (reserveToken == NATIVE_TOKEN_ADDRESS) {
amount = address(this).balance;
} else {
amount = reserveToken.balanceOf(address(this));
}
safeTransfer(reserveToken, _newConverter, amount);
syncReserveBalance(reserveToken);
}
}
/**
* @dev upgrades the converter to the latest version
* can only be called by the owner
* note that the owner needs to call acceptOwnership on the new converter after the upgrade
*/
function upgrade() public ownerOnly {
IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
// trigger de-activation event
emit Activation(converterType(), anchor, false);
transferOwnership(address(converterUpgrader));
converterUpgrader.upgrade(version);
acceptOwnership();
}
/**
* @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic
*/
function onUpgradeComplete()
external
override
protected
ownerOnly
only(CONVERTER_UPGRADER)
{
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev returns the number of reserve tokens
* note that prior to version 17, you should use 'connectorTokenCount' instead
*
* @return number of reserve tokens
*/
function reserveTokenCount() public view returns (uint16) {
return uint16(__reserveTokens.length);
}
/**
* @dev returns the array of reserve tokens
*
* @return array of reserve tokens
*/
function reserveTokens() public view returns (IERC20[] memory) {
return __reserveTokens;
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20 _token, uint32 _weight)
public
virtual
override
ownerOnly
inactive
validExternalAddress(address(_token))
validReserveWeight(_weight)
{
// validate input
require(address(_token) != address(anchor) && __reserveIds[_token] == 0, "ERR_INVALID_RESERVE");
require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
__reserveTokens.push(_token);
__reserveIds[_token] = __reserveTokens.length;
}
/**
* @dev returns the reserve's weight
* added in version 28
*
* @param _reserveToken reserve token contract address
*
* @return reserve weight
*/
function reserveWeight(IERC20 _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
return PPM_RESOLUTION / 2;
}
/**
* @dev returns the balance of a given reserve token
*
* @param _reserveToken reserve token contract address
*
* @return the balance of the given reserve token
*/
function reserveBalance(IERC20 _reserveToken) public view override returns (uint256) {
uint256 reserveId = __reserveIds[_reserveToken];
require(reserveId != 0, "ERR_INVALID_RESERVE");
return reserveBalance(reserveId);
}
/**
* @dev returns the balances of both reserve tokens
*
* @return the balances of both reserve tokens
*/
function reserveBalances() public view returns (uint256, uint256) {
return reserveBalances(1, 2);
}
/**
* @dev syncs all stored reserve balances
*/
function syncReserveBalances() external {
syncReserveBalances(0);
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*/
function processNetworkFees() external protected {
(uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*
* @param _value amount of ether to exclude from the ether reserve balance (if relevant)
*
* @return new reserve balances
*/
function processNetworkFees(uint256 _value) internal returns (uint256, uint256) {
syncReserveBalances(_value);
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
(ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
reserveBalance0 -= fee0;
reserveBalance1 -= fee1;
setReserveBalances(1, 2, reserveBalance0, reserveBalance1);
safeTransfer(__reserveTokens[0], address(wallet), fee0);
safeTransfer(__reserveTokens[1], address(wallet), fee1);
return (reserveBalance0, reserveBalance1);
}
/**
* @dev returns the reserve balances of the given reserve tokens minus their corresponding fees
*
* @param _reserveTokens reserve tokens
*
* @return reserve balances minus their corresponding fees
*/
function baseReserveBalances(IERC20[] memory _reserveTokens) internal view returns (uint256[2] memory) {
uint256 reserveId0 = __reserveIds[_reserveTokens[0]];
uint256 reserveId1 = __reserveIds[_reserveTokens[1]];
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1);
(, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
return [reserveBalance0 - fee0, reserveBalance1 - fee1];
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function convert(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) public payable override protected only(BANCOR_NETWORK) returns (uint256) {
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
}
/**
* @dev returns the conversion fee for a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee) / PPM_RESOLUTION;
}
/**
* @dev returns the conversion fee taken from a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFeeInv(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION - conversionFee);
}
/**
* @dev loads the stored reserve balance for a given reserve id
*
* @param _reserveId reserve id
*/
function reserveBalance(uint256 _reserveId) internal view returns (uint256) {
return decodeReserveBalance(__reserveBalances, _reserveId);
}
/**
* @dev loads the stored reserve balances
*
* @param _sourceId source reserve id
* @param _targetId target reserve id
*/
function reserveBalances(uint256 _sourceId, uint256 _targetId) internal view returns (uint256, uint256) {
require((_sourceId == 1 && _targetId == 2) || (_sourceId == 2 && _targetId == 1), "ERR_INVALID_RESERVES");
return decodeReserveBalances(__reserveBalances, _sourceId, _targetId);
}
/**
* @dev stores the stored reserve balance for a given reserve id
*
* @param _reserveId reserve id
* @param _reserveBalance reserve balance
*/
function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal {
require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId);
__reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId);
}
/**
* @dev stores the stored reserve balances
*
* @param _sourceId source reserve id
* @param _targetId target reserve id
* @param _sourceBalance source reserve balance
* @param _targetBalance target reserve balance
*/
function setReserveBalances(
uint256 _sourceId,
uint256 _targetId,
uint256 _sourceBalance,
uint256 _targetBalance
) internal {
require(_sourceBalance <= MAX_UINT128 && _targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
__reserveBalances = encodeReserveBalances(_sourceBalance, _sourceId, _targetBalance, _targetId);
}
/**
* @dev syncs the stored reserve balance for a given reserve with the real reserve balance
*
* @param _reserveToken address of the reserve token
*/
function syncReserveBalance(IERC20 _reserveToken) internal {
uint256 reserveId = __reserveIds[_reserveToken];
uint256 balance =
_reserveToken == NATIVE_TOKEN_ADDRESS ? address(this).balance : _reserveToken.balanceOf(address(this));
setReserveBalance(reserveId, balance);
}
/**
* @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant)
*
* @param _value amount of ether to exclude from the ether reserve balance (if relevant)
*/
function syncReserveBalances(uint256 _value) internal {
IERC20 _reserveToken0 = __reserveTokens[0];
IERC20 _reserveToken1 = __reserveTokens[1];
uint256 balance0 =
_reserveToken0 == NATIVE_TOKEN_ADDRESS
? address(this).balance - _value
: _reserveToken0.balanceOf(address(this));
uint256 balance1 =
_reserveToken1 == NATIVE_TOKEN_ADDRESS
? address(this).balance - _value
: _reserveToken1.balanceOf(address(this));
setReserveBalances(1, 2, balance0, balance1);
}
/**
* @dev helper, dispatches the Conversion event
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _trader address of the caller who executed the conversion
* @param _amount amount purchased/sold (in the source token)
* @param _returnAmount amount returned (in the target token)
*/
function dispatchConversionEvent(
IERC20 _sourceToken,
IERC20 _targetToken,
address _trader,
uint256 _amount,
uint256 _returnAmount,
uint256 _feeAmount
) internal {
emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) public view virtual override active returns (uint256, uint256) {
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
return targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceBalance balance in the source reserve token contract
* @param _targetBalance balance in the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IERC20, /* _sourceToken */
IERC20, /* _targetToken */
uint256 _sourceBalance,
uint256 _targetBalance,
uint256 _amount
) internal view virtual returns (uint256, uint256) {
uint256 amount = crossReserveTargetAmount(_sourceBalance, _targetBalance, _amount);
uint256 fee = calculateFee(amount);
return (amount - fee, fee);
}
/**
* @dev returns the required amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of target reserve tokens desired
*
* @return required amount in units of the source reserve token
* @return expected fee in units of the target reserve token
*/
function sourceAmountAndFee(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) public view virtual active returns (uint256, uint256) {
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
uint256 fee = calculateFeeInv(_amount);
uint256 amount = crossReserveSourceAmount(sourceBalance, targetBalance, _amount.add(fee));
return (amount, fee);
}
/**
* @dev converts a specific amount of source tokens to target tokens
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) internal returns (uint256) {
// update the recent average rate
updateRecentAverageRate();
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
// get the target amount minus the conversion fee and the conversion fee
(uint256 amount, uint256 fee) =
targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
// ensure that the trade gives something in return
require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
assert(amount < targetBalance);
// ensure that the input amount was already deposited
uint256 actualSourceBalance;
if (_sourceToken == NATIVE_TOKEN_ADDRESS) {
actualSourceBalance = address(this).balance;
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
} else {
actualSourceBalance = _sourceToken.balanceOf(address(this));
require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= _amount, "ERR_INVALID_AMOUNT");
}
// sync the reserve balances
setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - amount);
// transfer funds to the beneficiary in the to reserve token
safeTransfer(_targetToken, _beneficiary, amount);
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates
dispatchTokenRateUpdateEvents(_sourceToken, _targetToken, actualSourceBalance, targetBalance - amount);
return amount;
}
/**
* @dev returns the recent average rate of 1 `_token` in the other reserve token units
*
* @param _token token to get the rate for
*
* @return recent average rate between the reserves (numerator)
* @return recent average rate between the reserves (denominator)
*/
function recentAverageRate(IERC20 _token) external view validReserve(_token) returns (uint256, uint256) {
// get the recent average rate of reserve 0
uint256 rate = calcRecentAverageRate(averageRateInfo);
uint256 rateN = decodeAverageRateN(rate);
uint256 rateD = decodeAverageRateD(rate);
if (_token == __reserveTokens[0]) {
return (rateN, rateD);
}
return (rateD, rateN);
}
/**
* @dev updates the recent average rate if needed
*/
function updateRecentAverageRate() internal {
uint256 averageRateInfo1 = averageRateInfo;
uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1);
if (averageRateInfo1 != averageRateInfo2) {
averageRateInfo = averageRateInfo2;
}
}
/**
* @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
*
* @param _averageRateInfo a local copy of the `averageRateInfo` state-variable
*
* @return recent average rate between the reserves
*/
function calcRecentAverageRate(uint256 _averageRateInfo) internal view returns (uint256) {
// get the previous average rate and its update-time
uint256 prevAverageRateT = decodeAverageRateT(_averageRateInfo);
uint256 prevAverageRateN = decodeAverageRateN(_averageRateInfo);
uint256 prevAverageRateD = decodeAverageRateD(_averageRateInfo);
// get the elapsed time since the previous average rate was calculated
uint256 currentTime = time();
uint256 timeElapsed = currentTime - prevAverageRateT;
// if the previous average rate was calculated in the current block, the average rate remains unchanged
if (timeElapsed == 0) {
return _averageRateInfo;
}
// get the current rate between the reserves
(uint256 currentRateD, uint256 currentRateN) = reserveBalances();
// if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate
if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) {
(currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, currentRateN, currentRateD);
}
uint256 x = prevAverageRateD.mul(currentRateN);
uint256 y = prevAverageRateN.mul(currentRateD);
// since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
(newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, newRateN, newRateD);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _minReturn token minimum return-amount
*
* @return amount of pool tokens issued
*/
function addLiquidity(
IERC20[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _minReturn
) public payable protected active returns (uint256) {
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
// if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
for (uint256 i = 0; i < 2; i++) {
if (_reserveTokens[i] == NATIVE_TOKEN_ADDRESS) {
require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
}
}
// if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
if (msg.value > 0) {
require(__reserveIds[NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE");
}
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply
uint256 totalSupply = poolToken.totalSupply();
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value);
uint256 amount;
uint256[2] memory reserveAmounts;
// calculate the amount of pool tokens to mint for the caller
// and the amount of reserve tokens to transfer from the caller
if (totalSupply == 0) {
amount = MathEx.geometricMean(_reserveAmounts);
reserveAmounts[0] = _reserveAmounts[0];
reserveAmounts[1] = _reserveAmounts[1];
} else {
(amount, reserveAmounts) = addLiquidityAmounts(
_reserveTokens,
_reserveAmounts,
prevReserveBalances,
totalSupply
);
}
uint256 newPoolTokenSupply = totalSupply.add(amount);
for (uint256 i = 0; i < 2; i++) {
IERC20 reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
assert(reserveAmount <= _reserveAmounts[i]);
// transfer each one of the reserve amounts from the user to the pool
if (reserveToken != NATIVE_TOKEN_ADDRESS) {
// ETH has already been transferred as part of the transaction
reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount);
} else if (_reserveAmounts[i] > reserveAmount) {
// transfer the extra amount of ETH back to the user
msg.sender.transfer(_reserveAmounts[i] - reserveAmount);
}
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount);
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
// verify that the equivalent amount of tokens is equal to or larger than the user's expectation
require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
// issue the tokens to the user
poolToken.issue(msg.sender, amount);
// return the amount of pool tokens issued
return amount;
}
/**
* @dev get the amount of pool tokens to mint for the caller
* and the amount of reserve tokens to transfer from the caller
*
* @param _reserveAmounts amount of each reserve token
* @param _reserveBalances balance of each reserve token
* @param _totalSupply total supply of pool tokens
*
* @return amount of pool tokens to mint for the caller
* @return amount of reserve tokens to transfer from the caller
*/
function addLiquidityAmounts(
IERC20[] memory, /* _reserveTokens */
uint256[] memory _reserveAmounts,
uint256[2] memory _reserveBalances,
uint256 _totalSupply
) internal view virtual returns (uint256, uint256[2] memory) {
this;
uint256 index =
_reserveAmounts[0].mul(_reserveBalances[1]) < _reserveAmounts[1].mul(_reserveBalances[0]) ? 0 : 1;
uint256 amount = fundSupplyAmount(_totalSupply, _reserveBalances[index], _reserveAmounts[index]);
uint256[2] memory reserveAmounts =
[fundCost(_totalSupply, _reserveBalances[0], amount), fundCost(_totalSupply, _reserveBalances[1], amount)];
return (amount, reserveAmounts);
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
*
* @param _amount token amount
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function removeLiquidity(
uint256 _amount,
IERC20[] memory _reserveTokens,
uint256[] memory _reserveMinReturnAmounts
) public protected active returns (uint256[] memory) {
// verify the user input
bool inputRearranged = verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply BEFORE destroying the user tokens
uint256 totalSupply = poolToken.totalSupply();
// destroy the user tokens
poolToken.destroy(msg.sender, _amount);
uint256 newPoolTokenSupply = totalSupply.sub(_amount);
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0);
uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, totalSupply, prevReserveBalances);
for (uint256 i = 0; i < 2; i++) {
IERC20 reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount);
// transfer each one of the reserve amounts from the pool to the user
safeTransfer(reserveToken, msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
if (inputRearranged) {
uint256 tempReserveAmount = reserveAmounts[0];
reserveAmounts[0] = reserveAmounts[1];
reserveAmounts[1] = tempReserveAmount;
}
// return the amount of each reserve token granted for the given amount of pool tokens
return reserveAmounts;
}
/**
* @dev given the amount of one of the reserve tokens to add liquidity of,
* returns the required amount of each one of the other reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveTokenIndex index of the relevant reserve token
* @param _reserveAmount amount of the relevant reserve token
*
* @return the required amount of each one of the reserve tokens
*/
function addLiquidityCost(
IERC20[] memory _reserveTokens,
uint256 _reserveTokenIndex,
uint256 _reserveAmount
) public view returns (uint256[] memory) {
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
uint256 amount = fundSupplyAmount(totalSupply, baseBalances[_reserveTokenIndex], _reserveAmount);
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], amount);
reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], amount);
return reserveAmounts;
}
/**
* @dev returns the amount of pool tokens entitled for given amounts of reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
*
* @return the amount of pool tokens entitled for the given amounts of reserve tokens
*/
function addLiquidityReturn(IERC20[] memory _reserveTokens, uint256[] memory _reserveAmounts)
public
view
returns (uint256)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
(uint256 amount, ) = addLiquidityAmounts(_reserveTokens, _reserveAmounts, baseBalances, totalSupply);
return amount;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _reserveTokens address of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReturn(uint256 _amount, IERC20[] memory _reserveTokens)
public
view
returns (uint256[] memory)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
return removeLiquidityReserveAmounts(_amount, totalSupply, baseBalances);
}
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
* this function rearranges the input arrays according to the converter's array of reserve tokens
*
* @param _reserveTokens array of reserve tokens
* @param _reserveAmounts array of reserve amounts
* @param _amount token amount
*
* @return true if the function has rearranged the input arrays; false otherwise
*/
function verifyLiquidityInput(
IERC20[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _amount
) private view returns (bool) {
require(validReserveAmounts(_reserveAmounts) && _amount > 0, "ERR_ZERO_AMOUNT");
uint256 reserve0Id = __reserveIds[_reserveTokens[0]];
uint256 reserve1Id = __reserveIds[_reserveTokens[1]];
if (reserve0Id == 2 && reserve1Id == 1) {
IERC20 tempReserveToken = _reserveTokens[0];
_reserveTokens[0] = _reserveTokens[1];
_reserveTokens[1] = tempReserveToken;
uint256 tempReserveAmount = _reserveAmounts[0];
_reserveAmounts[0] = _reserveAmounts[1];
_reserveAmounts[1] = tempReserveAmount;
return true;
}
require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE");
return false;
}
/**
* @dev checks whether or not both reserve amounts are larger than zero
*
* @param _reserveAmounts array of reserve amounts
*
* @return true if both reserve amounts are larger than zero; false otherwise
*/
function validReserveAmounts(uint256[] memory _reserveAmounts) internal pure virtual returns (bool) {
return _reserveAmounts[0] > 0 && _reserveAmounts[1] > 0;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _totalSupply total supply of pool tokens
* @param _reserveBalances balance of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReserveAmounts(
uint256 _amount,
uint256 _totalSupply,
uint256[2] memory _reserveBalances
) private pure returns (uint256[] memory) {
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = liquidateReserveAmount(_totalSupply, _reserveBalances[0], _amount);
reserveAmounts[1] = liquidateReserveAmount(_totalSupply, _reserveBalances[1], _amount);
return reserveAmounts;
}
/**
* @dev dispatches token rate update events for the reserve tokens and the pool token
*
* @param _sourceToken address of the source reserve token
* @param _targetToken address of the target reserve token
* @param _sourceBalance balance of the source reserve token
* @param _targetBalance balance of the target reserve token
*/
function dispatchTokenRateUpdateEvents(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _sourceBalance,
uint256 _targetBalance
) private {
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply of pool tokens
uint256 poolTokenSupply = poolToken.totalSupply();
// dispatch token rate update event for the reserve tokens
emit TokenRateUpdate(_sourceToken, _targetToken, _targetBalance, _sourceBalance);
// dispatch token rate update events for the pool token
emit TokenRateUpdate(poolToken, _sourceToken, _sourceBalance, poolTokenSupply);
emit TokenRateUpdate(poolToken, _targetToken, _targetBalance, poolTokenSupply);
}
function encodeReserveBalance(uint256 _balance, uint256 _id) private pure returns (uint256) {
assert(_balance <= MAX_UINT128 && (_id == 1 || _id == 2));
return _balance << ((_id - 1) * 128);
}
function decodeReserveBalance(uint256 _balances, uint256 _id) private pure returns (uint256) {
assert(_id == 1 || _id == 2);
return (_balances >> ((_id - 1) * 128)) & MAX_UINT128;
}
function encodeReserveBalances(
uint256 _balance0,
uint256 _id0,
uint256 _balance1,
uint256 _id1
) private pure returns (uint256) {
return encodeReserveBalance(_balance0, _id0) | encodeReserveBalance(_balance1, _id1);
}
function decodeReserveBalances(
uint256 _balances,
uint256 _id0,
uint256 _id1
) private pure returns (uint256, uint256) {
return (decodeReserveBalance(_balances, _id0), decodeReserveBalance(_balances, _id1));
}
function encodeAverageRateInfo(
uint256 _averageRateT,
uint256 _averageRateN,
uint256 _averageRateD
) private pure returns (uint256) {
assert(_averageRateT <= MAX_UINT32 && _averageRateN <= MAX_UINT112 && _averageRateD <= MAX_UINT112);
return (_averageRateT << 224) | (_averageRateN << 112) | _averageRateD;
}
function decodeAverageRateT(uint256 _averageRateInfo) private pure returns (uint256) {
return _averageRateInfo >> 224;
}
function decodeAverageRateN(uint256 _averageRateInfo) private pure returns (uint256) {
return (_averageRateInfo >> 112) & MAX_UINT112;
}
function decodeAverageRateD(uint256 _averageRateInfo) private pure returns (uint256) {
return _averageRateInfo & MAX_UINT112;
}
/**
* @dev returns the largest integer smaller than or equal to the square root of a given value
*
* @param x the given value
*
* @return the largest integer smaller than or equal to the square root of the given value
*/
function floorSqrt(uint256 x) private pure returns (uint256) {
return x > 0 ? MathEx.floorSqrt(x) : 0;
}
function crossReserveTargetAmount(
uint256 _sourceReserveBalance,
uint256 _targetReserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
}
function crossReserveSourceAmount(
uint256 _sourceReserveBalance,
uint256 _targetReserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_amount < _targetReserveBalance, "ERR_INVALID_AMOUNT");
if (_amount == 0) {
return 0;
}
return (_sourceReserveBalance.mul(_amount) - 1) / (_targetReserveBalance - _amount) + 1;
}
function fundCost(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
}
function fundSupplyAmount(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
return _amount.mul(_supply) / _reserveBalance;
}
function liquidateReserveAmount(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
// special case for liquidating the entire supply
if (_amount == _supply) {
return _reserveBalance;
}
return _amount.mul(_reserveBalance) / _supply;
}
/**
* @dev returns the network wallet and fees
*
* @param reserveBalance0 1st reserve balance
* @param reserveBalance1 2nd reserve balance
*
* @return the network wallet
* @return the network fee on the 1st reserve
* @return the network fee on the 2nd reserve
*/
function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1)
private
view
returns (
ITokenHolder,
uint256,
uint256
)
{
uint256 prevPoint = floorSqrt(_reserveBalancesProduct);
uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1);
if (prevPoint >= currPoint) {
return (ITokenHolder(address(0)), 0, 0);
}
(ITokenHolder networkFeeWallet, uint32 networkFee) =
INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams();
uint256 n = (currPoint - prevPoint) * networkFee;
uint256 d = currPoint * PPM_RESOLUTION;
return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d));
}
/**
* @dev transfers funds held by the contract and sends them to an account
*
* @param token ERC20 token contract address
* @param to account to receive the new amount
* @param amount amount to withdraw
*/
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) private {
if (amount == 0) {
return;
}
if (token == NATIVE_TOKEN_ADDRESS) {
payable(to).transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
/**
* @dev deprecated since version 28, backward compatibility - use only for earlier versions
*/
function token() public view override returns (IConverterAnchor) {
return anchor;
}
/**
* @dev deprecated, backward compatibility
*/
function transferTokenOwnership(address _newOwner) public override ownerOnly {
transferAnchorOwnership(_newOwner);
}
/**
* @dev deprecated, backward compatibility
*/
function acceptTokenOwnership() public override ownerOnly {
acceptAnchorOwnership();
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(IERC20 _address)
public
view
override
returns (
uint256,
uint32,
bool,
bool,
bool
)
{
uint256 reserveId = __reserveIds[_address];
if (reserveId != 0) {
return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true);
}
return (0, 0, false, false, false);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 _index) public view override returns (IERC20) {
return __reserveTokens[_index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() public view override returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IERC20 _connectorToken) public view override returns (uint256) {
return reserveBalance(_connectorToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getReturn(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) public view returns (uint256, uint256) {
return targetAmountAndFee(_sourceToken, _targetToken, _amount);
}
}
// File: solidity/contracts/converter/interfaces/ITypedConverterFactory.sol
pragma solidity 0.6.12;
/*
Typed Converter Factory interface
*/
interface ITypedConverterFactory {
function converterType() external pure returns (uint16);
function createConverter(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) external returns (IConverter);
}
// File: solidity/contracts/converter/types/standard-pool/StandardPoolConverterFactory.sol
pragma solidity 0.6.12;
/*
StandardPoolConverter Factory
*/
contract StandardPoolConverterFactory is ITypedConverterFactory {
/**
* @dev returns the converter type the factory is associated with
*
* @return converter type
*/
function converterType() external pure override returns (uint16) {
return 3;
}
/**
* @dev creates a new converter with the given arguments and transfers
* the ownership to the caller
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*
* @return a new converter
*/
function createConverter(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) external virtual override returns (IConverter) {
IConverter converter = new StandardPoolConverter(IDSToken(address(_anchor)), _registry, _maxConversionFee);
converter.transferOwnership(msg.sender);
return converter;
}
}
| error message binary size optimization | function _validFee(uint32 fee) internal pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
}
| 1,735,937 |
// contracts/CustoMoose.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./IToken.sol";
import "./Library.sol";
import "./TraitLibrary.sol";
import "./BytesLib.sol";
contract Customoose is ERC721Enumerable, Ownable {
using BytesLib for bytes;
using SafeMath for uint256;
using Library for uint8;
//Mappings
mapping(uint256 => string) internal tokenIdToConfig;
mapping(uint256 => uint256) internal tokenIdToStoredTrax;
//uint256s
uint256 MAX_SUPPLY = 10000;
uint256 MINTS_PER_TIER = 1000;
uint256 MINT_START = 1639418400;
uint256 MINT_START_ETH = MINT_START.add(86400);
uint256 MINT_DELAY = 43200;
uint256 START_PRICE = 70000000000000000;
uint256 MIN_PRICE = 20000000000000000;
uint256 PRICE_DIFF = 5000000000000000;
uint256 START_PRICE_TRAX = 10000000000000000000;
uint256 PRICE_DIFF_TRAX = 10000000000000000000;
//address
address public mooseAddress;
address public traxAddress;
address public libraryAddress;
address _owner;
constructor(address _mooseAddress, address _traxAddress, address _libraryAddress) ERC721("Frame", "FRAME") {
_owner = msg.sender;
setMooseAddress(_mooseAddress);
setTraxAddress(_traxAddress);
setLibraryAddress(_libraryAddress);
// test mint
mintInternal();
}
/*
__ __ _ _ _ ___ _ _
| \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___
| |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-<
|_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/
|___/
*/
/**
* @dev Generates an 8 digit config
*/
function config() internal pure returns (string memory) {
// This will generate an 9 character string.
// All of them will start as 0
string memory currentConfig = "000000000";
return currentConfig;
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal() internal returns (uint256 tokenId) {
uint256 _totalSupply = totalSupply();
require(_totalSupply < MAX_SUPPLY);
require(!Library.isContract(msg.sender));
uint256 thisTokenId = _totalSupply;
tokenIdToConfig[thisTokenId] = config();
tokenIdToStoredTrax[thisTokenId] = 0;
_mint(msg.sender, thisTokenId);
return thisTokenId;
}
/**
* @dev Mints new frame using TRAX
*/
function mintFrameWithTrax(uint8 _times) public {
require(block.timestamp >= MINT_START, "Minting has not started");
uint256 allowance = IToken(traxAddress).allowance(msg.sender, address(this));
require(allowance >= _times * getMintPriceTrax(), "Check the token allowance");
IToken(traxAddress).burnFrom(msg.sender, _times * getMintPriceTrax());
for(uint256 i=0; i< _times; i++){
mintInternal();
}
}
/**
* @dev Mints new frame using ETH
*/
function mintFrameWithEth(uint8 _times) public payable {
require(block.timestamp >= MINT_START_ETH, "Minting for ETH has not started");
require((_times > 0 && _times <= 20));
require(msg.value >= _times * getMintPriceEth());
for(uint256 i=0; i< _times; i++){
mintInternal();
}
}
/**
* @dev Mints new frame with customizations using ETH
*/
function mintCustomooseWithEth(string memory tokenConfig) public payable {
require(block.timestamp >= MINT_START_ETH, "Minting for ETH has not started");
require(msg.value >= getMintPriceEth(), "Not enough ETH");
uint256 tokenId = mintInternal();
setTokenConfig(tokenId, tokenConfig);
}
/**
* @dev Mints new frame with customizations using TRAX
*/
function mintCustomooseWithTrax(string memory tokenConfig) public payable {
require(block.timestamp >= MINT_START, "Minting has not started");
uint256 allowance = IToken(traxAddress).allowance(msg.sender, address(this));
require(allowance >= getMintPriceTrax(), "Check the token allowance");
IToken(traxAddress).burnFrom(msg.sender, getMintPriceTrax());
uint256 tokenId = mintInternal();
setTokenConfig(tokenId, tokenConfig);
}
/**
* @dev Burns a frame and returns TRAX
*/
function burnFrameForTrax(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
//Burn token
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
//Return the TRAX
IToken(traxAddress).transfer(
msg.sender,
tokenIdToStoredTrax[_tokenId]
);
}
/**
* @dev Sets a trait for a token
*/
function setTokenTrait(uint256 _tokenId, uint8 _traitIndex, uint8 _traitValue) public onlyOwner {
string memory tokenConfig = tokenIdToConfig[_tokenId];
string memory newTokenConfig = Library.stringReplace(tokenConfig, _traitIndex, Library.toString(_traitValue));
tokenIdToConfig[_tokenId] = newTokenConfig;
}
/**
* @dev Sets the config for a token
*/
function setTokenConfig(uint256 _tokenId, string memory _newConfig) public {
require(keccak256(abi.encodePacked(tokenIdToConfig[_tokenId])) !=
keccak256(abi.encodePacked(_newConfig)), "Config must be different");
uint256 allowance = IToken(traxAddress).allowance(msg.sender, address(this));
(uint256 price, uint256 valueDiff, bool valueIncreased) = getCustomizationPrice(_tokenId, _newConfig);
uint256 balance = IToken(traxAddress).balanceOf(msg.sender);
require(allowance >= price, "Check the token allowance");
require(balance >= price, "You need more TRAX");
if(valueDiff >= 0 && valueIncreased) {
IToken(traxAddress).transferFrom(
msg.sender,
address(this),
valueDiff
);
IToken(traxAddress).burnFrom(msg.sender, price.sub(valueDiff));
tokenIdToStoredTrax[_tokenId] += valueDiff;
} else if(valueDiff >= 0 && !valueIncreased) {
tokenIdToStoredTrax[_tokenId] -= valueDiff;
}
tokenIdToConfig[_tokenId] = _newConfig;
}
/**
* @dev Takes an array of trait changes and gets the new config
*/
function getNewTokenConfig(uint256 _tokenId, uint8[2][] calldata _newTraits)
public
view
returns (string memory)
{
string memory tokenConfig = tokenIdToConfig[_tokenId];
string memory newTokenConfig = tokenConfig;
for (uint8 i = 0; i < _newTraits.length; i++) {
string memory newTraitValue = Library.toString(_newTraits[i][1]);
newTokenConfig = Library.stringReplace(newTokenConfig, _newTraits[i][0], newTraitValue);
}
return (newTokenConfig);
}
/**
* @dev Gets the price of a newly minted frame
*/
function getMintCustomizationPrice(string memory _newConfig)
public
view
returns (uint256 price)
{
price = 0;
for (uint8 i = 0; i < 9; i++) {
uint8 traitValue = convertInt(bytes(_newConfig).slice(i, 1).toUint8(0));
uint256 traitPrice = TraitLibrary(libraryAddress).getPrice(i, traitValue);
price = price.add(traitPrice);
}
price = price.mul(10**16);
return price;
}
/**
* @dev Gets the price given a tokenId and new config
*/
function getCustomizationPrice(uint256 _tokenId, string memory _newConfig)
public
view
returns (uint256 price, uint256 valueDiff, bool increased)
{
string memory tokenConfig = tokenIdToConfig[_tokenId];
uint256 currentValue = tokenIdToStoredTrax[_tokenId];
price = 0;
uint256 futureValue = 0;
for (uint8 i = 0; i < 9; i++) {
uint8 traitValue = convertInt(bytes(_newConfig).slice(i, 1).toUint8(0));
uint256 traitPrice = TraitLibrary(libraryAddress).getPrice(i, traitValue);
bool isChanged = keccak256(abi.encodePacked(bytes(tokenConfig).slice(i, 1))) !=
keccak256(abi.encodePacked(bytes(_newConfig).slice(i, 1)));
futureValue = futureValue.add(traitPrice);
if(isChanged) {
price = price.add(traitPrice);
}
}
price = price.mul(10**16);
futureValue = futureValue.mul(10**16).div(100).mul(80);
if(futureValue == currentValue) {
valueDiff = 0;
increased = true;
} else if(futureValue > currentValue) {
valueDiff = futureValue.sub(currentValue);
increased = true;
} else {
valueDiff = currentValue.sub(futureValue);
increased = false;
}
return (price, valueDiff, increased);
}
/**
* @dev Gets the price of a specified trait
*/
function getTraitPrice(uint256 typeIndex, uint256 nameIndex)
public
view
returns (uint256 traitPrice)
{
traitPrice = TraitLibrary(libraryAddress).getPrice(typeIndex, nameIndex);
return traitPrice;
}
/**
* @dev Gets the current mint price in ETH for a new frame
*/
function getMintPriceEth()
public
view
returns (uint256 price)
{
if(block.timestamp < MINT_START_ETH) {
return START_PRICE;
}
uint256 _mintTiersComplete = block.timestamp.sub(MINT_START_ETH).div(MINT_DELAY);
if(PRICE_DIFF.mul(_mintTiersComplete) >= START_PRICE.sub(MIN_PRICE)) {
return MIN_PRICE;
} else {
return START_PRICE - (PRICE_DIFF * _mintTiersComplete);
}
}
/**
* @dev Gets the current mint price in TRAX for a new frame
*/
function getMintPriceTrax()
public
view
returns (uint256 price)
{
uint256 _totalSupply = totalSupply();
if(_totalSupply == 0) return START_PRICE_TRAX;
uint256 _mintTiersComplete = _totalSupply.div(MINTS_PER_TIER);
price = START_PRICE_TRAX.add(_mintTiersComplete.mul(PRICE_DIFF_TRAX));
return price;
}
/*
____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Convert a raw assembly int value to a pixel location
*/
function convertInt(uint8 _inputInt)
internal
pure
returns (uint8)
{
if (
(_inputInt >= 48) &&
(_inputInt <= 57)
) {
_inputInt -= 48;
return _inputInt;
} else {
_inputInt -= 87;
return _inputInt;
}
}
/**
* @dev Config to SVG function
*/
function configToSVG(string memory _config)
public
view
returns (string memory)
{
string memory svgString;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = convertInt(bytes(_config).slice(i, 1).toUint8(0));
bytes memory traitRects = TraitLibrary(libraryAddress).getRects(i, thisTraitIndex);
if(bytes(traitRects).length == 0) continue;
bool isRow = traitRects.slice(0, 1).equal(bytes("r"));
uint16 j = 1;
string memory thisColor = "";
bool newColor = true;
while(j < bytes(traitRects).length)
{
if(newColor) {
// get the color
thisColor = string(traitRects.slice(j, 3));
j += 3;
newColor = false;
continue;
} else {
// if pipe, new color
if (
traitRects.slice(j, 1).equal(bytes("|"))
) {
newColor = true;
j += 1;
continue;
} else {
// else add rects
bytes memory thisRect = traitRects.slice(j, 3);
uint8 x = convertInt(thisRect.slice(0, 1).toUint8(0));
uint8 y = convertInt(thisRect.slice(1, 1).toUint8(0));
uint8 length = convertInt(thisRect.slice(2, 1).toUint8(0)) + 1;
if(isRow) {
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
thisColor,
"' x='",
x.toString(),
"' y='",
y.toString(),
"' width='",
length.toString(),
"px' height='1px'",
"/>"
)
);
j += 3;
continue;
} else {
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
thisColor,
"' x='",
x.toString(),
"' y='",
y.toString(),
"' height='",
length.toString(),
"px' width='1px'",
"/>"
)
);
j += 3;
continue;
}
}
}
}
}
svgString = string(
abi.encodePacked(
'<svg id="moose-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 32 32">',
svgString,
"<style>rect.bg{width:32px;height:32px;} #moose-svg{shape-rendering: crispedges;}",
TraitLibrary(libraryAddress).getColors(),
"</style></svg>"
)
);
return svgString;
}
/**
* @dev Config to metadata function
*/
function configToMetadata(string memory _config)
public
view
returns (string memory)
{
string memory metadataString;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = convertInt(bytes(_config).slice(i, 1).toUint8(0));
(string memory traitName, string memory traitType) = TraitLibrary(libraryAddress).getTraitInfo(i, thisTraitIndex);
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
traitType,
'","value":"',
traitName,
'"}'
)
);
if (i != 8)
metadataString = string(abi.encodePacked(metadataString, ","));
}
return string(abi.encodePacked("[", metadataString, "]"));
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory tokenConfig = _tokenIdToConfig(_tokenId);
return
string(
abi.encodePacked(
"data:application/json;base64,",
Library.encode(
bytes(
string(
abi.encodePacked(
'{"name": "FRAME Edition 0, Token #',
Library.toString(_tokenId),
'", "description": "FRAME tokens are fully customizable on-chain pixel art. Edition 0 is a collection of 32x32 Moose avatars.", "image": "data:image/svg+xml;base64,',
Library.encode(
bytes(configToSVG(tokenConfig))
),
'","attributes":',
configToMetadata(tokenConfig),
"}"
)
)
)
)
)
);
}
/**
* @dev Returns a config for a given tokenId
* @param _tokenId The tokenId to return the config for.
*/
function _tokenIdToConfig(uint256 _tokenId)
public
view
returns (string memory)
{
string memory tokenConfig = tokenIdToConfig[_tokenId];
return tokenConfig;
}
/**
* @dev Returns the current amount of TRAX stored for a given tokenId
* @param _tokenId The tokenId to look up.
*/
function _tokenIdToStoredTrax(uint256 _tokenId)
public
view
returns (uint256)
{
uint256 storedTrax = tokenIdToStoredTrax[_tokenId];
return storedTrax;
}
/**
* @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs.
* @param _wallet The wallet to get the tokens of.
*/
function walletOfOwner(address _wallet)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_wallet);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_wallet, i);
}
return tokensId;
}
/*
___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____
/ \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/
| || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_
| O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ |
| | \ / | | || || . \ | | | || | \ | | | | || || | |\ |
\___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Sets the ERC721 token address
* @param _mooseAddress The NFT address
*/
function setMooseAddress(address _mooseAddress) public onlyOwner {
mooseAddress = _mooseAddress;
}
/**
* @dev Sets the ERC20 token address
* @param _traxAddress The token address
*/
function setTraxAddress(address _traxAddress) public onlyOwner {
traxAddress = _traxAddress;
}
/**
* @dev Sets the trait library address
* @param _libraryAddress The token address
*/
function setLibraryAddress(address _libraryAddress) public onlyOwner {
libraryAddress = _libraryAddress;
}
/**
* @dev Withdraw ETH to owner
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Library.sol";
contract TraitLibrary is Ownable {
using Library for uint16;
struct Trait {
string traitName;
string traitType;
string rects;
uint32 price;
}
//addresses
address _owner;
//uint arrays
uint32[][9] PRICES;
//byte arrays
bytes[9] TYPES;
bytes[][9] NAMES;
bytes[][9] RECTS;
bytes COLORS;
constructor() {
_owner = msg.sender;
// Declare initial values
TYPES = [
bytes("background"),
bytes("body"),
bytes("eye"),
bytes("antler"),
bytes("hat"),
bytes("neck"),
bytes("mouth"),
bytes("nose"),
bytes("accessory")
];
PRICES[0] = [0];
PRICES[1] = [0];
PRICES[2] = [0];
PRICES[3] = [0];
PRICES[4] = [0];
PRICES[5] = [0];
PRICES[6] = [0];
PRICES[7] = [0];
PRICES[8] = [0];
NAMES[0] = [
bytes("")
];
NAMES[1] = [
bytes("")
];
NAMES[2] = [
bytes("")
];
NAMES[3] = [
bytes("")
];
NAMES[4] = [
bytes("")
];
NAMES[5] = [
bytes("")
];
NAMES[6] = [
bytes("")
];
NAMES[7] = [
bytes("")
];
NAMES[8] = [
bytes("")
];
RECTS[0] = [
bytes("")
];
RECTS[1] = [
bytes("")
];
RECTS[2] = [
bytes("")
];
RECTS[3] = [
bytes("")
];
RECTS[4] = [
bytes("")
];
RECTS[5] = [
bytes("")
];
RECTS[6] = [
bytes("")
];
RECTS[7] = [
bytes("")
];
RECTS[8] = [
bytes("")
];
}
/**
* @dev Gets the rects a trait from storage
* @param traitIndex The trait type index
* @param traitValue The location within the array
*/
function getRects(uint256 traitIndex, uint256 traitValue)
public
view
returns (bytes memory rects)
{
// return string(abi.encodePacked(RECTS[traitIndex][traitValue]));
return RECTS[traitIndex][traitValue];
}
/**
* @dev Gets a trait from storage
* @param traitIndex The trait type index
* @param traitValue The location within the array
*/
function getTraitInfo(uint256 traitIndex, uint256 traitValue)
public
view
returns (string memory traitName, string memory traitType)
{
return (
string(abi.encodePacked(NAMES[traitIndex][traitValue])),
string(abi.encodePacked(TYPES[traitIndex]))
);
}
/**
* @dev Gets the price of a trait from storage
* @param traitIndex The trait type index
* @param traitValue The location within the array
*/
function getPrice(uint256 traitIndex, uint256 traitValue)
public
view
returns (uint32 price)
{
return PRICES[traitIndex][traitValue];
}
/**
* @dev Adds entries to trait metadata
* @param _traitTypeIndex The trait type index
* @param traits Array of traits to add
*/
function addTraits(uint256 _traitTypeIndex, Trait[] memory traits)
public
onlyOwner
{
for (uint256 i = 0; i < traits.length; i++) {
PRICES[_traitTypeIndex].push(traits[i].price);
NAMES[_traitTypeIndex].push(bytes(abi.encodePacked(traits[i].traitName)));
RECTS[_traitTypeIndex].push(bytes(abi.encodePacked(traits[i].rects)));
}
return;
}
/**
* @dev Clear entries to trait metadata
* @param _traitTypeIndex The trait type index
*/
function clearTrait(uint256 _traitTypeIndex)
public
onlyOwner
{
PRICES[_traitTypeIndex] = [0];
NAMES[_traitTypeIndex] = [bytes("")];
RECTS[_traitTypeIndex] = [bytes("")];
return;
}
/**
* @dev Gets the color string
*/
function getColors()
public
pure
returns (string memory colors)
{
return ".c000{fill:#000000}.c001{fill:#000008}.c002{fill:#00000a}.c003{fill:#00000b}.c004{fill:#000101}.c005{fill:#000202}.c006{fill:#001efd}.c007{fill:#001eff}.c008{fill:#002259}.c009{fill:#005189}.c010{fill:#006bff}.c011{fill:#008544}.c012{fill:#00881d}.c013{fill:#00aa0c}.c014{fill:#00b09e}.c015{fill:#00b4ff}.c016{fill:#00c7f1}.c017{fill:#00eaff}.c018{fill:#010000}.c019{fill:#010001}.c020{fill:#010101}.c021{fill:#017db1}.c022{fill:#020100}.c023{fill:#020202}.c024{fill:#022d00}.c025{fill:#024d01}.c026{fill:#02b4da}.c027{fill:#030202}.c028{fill:#030303}.c029{fill:#035223}.c030{fill:#040303}.c031{fill:#040309}.c032{fill:#0456c7}.c033{fill:#050505}.c034{fill:#051429}.c035{fill:#051c3e}.c036{fill:#060405}.c037{fill:#060605}.c038{fill:#070404}.c039{fill:#070707}.c040{fill:#080500}.c041{fill:#080604}.c042{fill:#080808}.c043{fill:#0879df}.c044{fill:#0904eb}.c045{fill:#090500}.c046{fill:#09897b}.c047{fill:#09f200}.c048{fill:#0a0a0a}.c049{fill:#0a0e13}.c050{fill:#0ad200}.c051{fill:#0b0907}.c052{fill:#0b0a09}.c053{fill:#0b0b0b}.c054{fill:#0b7b08}.c055{fill:#0b87f7}.c056{fill:#0b8f08}.c057{fill:#0d031e}.c058{fill:#0d0c0d}.c059{fill:#0d0d0d}.c060{fill:#0e0603}.c061{fill:#0e09c5}.c062{fill:#0e0d0d}.c063{fill:#0e0e0e}.c064{fill:#0f0602}.c065{fill:#0f095e}.c066{fill:#0f09f9}.c067{fill:#100603}.c068{fill:#101010}.c069{fill:#104b01}.c070{fill:#106ae7}.c071{fill:#107a46}.c072{fill:#1098b8}.c073{fill:#110502}.c074{fill:#110968}.c075{fill:#121111}.c076{fill:#131313}.c077{fill:#141414}.c078{fill:#141515}.c079{fill:#146b00}.c080{fill:#150f2d}.c081{fill:#156103}.c082{fill:#161616}.c083{fill:#17f4dd}.c084{fill:#18120a}.c085{fill:#182257}.c086{fill:#18371e}.c087{fill:#1a0db0}.c088{fill:#1a0eac}.c089{fill:#1c31c9}.c090{fill:#1d0ed1}.c091{fill:#1e1300}.c092{fill:#1e1b1c}.c093{fill:#1e1d1c}.c094{fill:#1f170d}.c095{fill:#2110ec}.c096{fill:#212121}.c097{fill:#215a36}.c098{fill:#231e1e}.c099{fill:#232222}.c100{fill:#252627}.c101{fill:#25b5f8}.c102{fill:#262929}.c103{fill:#272321}.c104{fill:#27ec0d}.c105{fill:#281900}.c106{fill:#29050a}.c107{fill:#299b01}.c108{fill:#2b3635}.c109{fill:#2c2729}.c110{fill:#2c27f3}.c111{fill:#2c2a28}.c112{fill:#2d130c}.c113{fill:#2e2113}.c114{fill:#2e260d}.c115{fill:#2e47ff}.c116{fill:#2e6a4b}.c117{fill:#2e9e40}.c118{fill:#2f0041}.c119{fill:#313021}.c120{fill:#323333}.c121{fill:#332eec}.c122{fill:#333a02}.c123{fill:#349d92}.c124{fill:#353537}.c125{fill:#364643}.c126{fill:#372014}.c127{fill:#372501}.c128{fill:#3a4703}.c129{fill:#3c2402}.c130{fill:#3d1005}.c131{fill:#3d301d}.c132{fill:#3d320e}.c133{fill:#3e383a}.c134{fill:#3e3e3e}.c135{fill:#3f3fed}.c136{fill:#3f4c03}.c137{fill:#410000}.c138{fill:#412ce5}.c139{fill:#422de5}.c140{fill:#424244}.c141{fill:#425c5a}.c142{fill:#435303}.c143{fill:#436060}.c144{fill:#448f61}.c145{fill:#44d0e6}.c146{fill:#451a08}.c147{fill:#464b64}.c148{fill:#473f42}.c149{fill:#47ffee}.c150{fill:#482e20}.c151{fill:#484a4a}.c152{fill:#494334}.c153{fill:#4a443f}.c154{fill:#4a4aff}.c155{fill:#4b1e0b}.c156{fill:#4b4545}.c157{fill:#4b4643}.c158{fill:#4b4a05}.c159{fill:#4c4c4c}.c160{fill:#4c8020}.c161{fill:#4d3b4d}.c162{fill:#4d4c48}.c163{fill:#4d5466}.c164{fill:#4f3533}.c165{fill:#4f4f51}.c166{fill:#4f5049}.c167{fill:#503820}.c168{fill:#504c47}.c169{fill:#513222}.c170{fill:#516d63}.c171{fill:#518d3c}.c172{fill:#520169}.c173{fill:#534016}.c174{fill:#535254}.c175{fill:#535556}.c176{fill:#535e9c}.c177{fill:#54ccff}.c178{fill:#554c4f}.c179{fill:#55aa48}.c180{fill:#564c4e}.c181{fill:#580002}.c182{fill:#582f19}.c183{fill:#585341}.c184{fill:#585858}.c185{fill:#595a5a}.c186{fill:#5a3200}.c187{fill:#5a5a5b}.c188{fill:#5a5a5c}.c189{fill:#5a9346}.c190{fill:#5c311a}.c191{fill:#5c5115}.c192{fill:#5c5a5b}.c193{fill:#5c8e8c}.c194{fill:#5d1d0c}.c195{fill:#5e341f}.c196{fill:#5e3700}.c197{fill:#5e5e5e}.c198{fill:#5fa551}.c199{fill:#604b31}.c200{fill:#614327}.c201{fill:#615c3c}.c202{fill:#624c3f}.c203{fill:#625e40}.c204{fill:#626262}.c205{fill:#632b1c}.c206{fill:#63564a}.c207{fill:#63605c}.c208{fill:#654f21}.c209{fill:#6574a4}.c210{fill:#6593eb}.c211{fill:#676767}.c212{fill:#684a11}.c213{fill:#686868}.c214{fill:#69ac0f}.c215{fill:#69bf9c}.c216{fill:#6a0500}.c217{fill:#6b3d02}.c218{fill:#6ba6db}.c219{fill:#6c0104}.c220{fill:#6d6949}.c221{fill:#6da25a}.c222{fill:#6e3421}.c223{fill:#6e6d6d}.c224{fill:#6f0809}.c225{fill:#700b00}.c226{fill:#707070}.c227{fill:#70c4ce}.c228{fill:#716e70}.c229{fill:#725e15}.c230{fill:#727877}.c231{fill:#72daff}.c232{fill:#737373}.c233{fill:#73b95a}.c234{fill:#73cd46}.c235{fill:#74bf2d}.c236{fill:#757575}.c237{fill:#75daf2}.c238{fill:#774000}.c239{fill:#775e07}.c240{fill:#776d6d}.c241{fill:#787e91}.c242{fill:#7b6c48}.c243{fill:#7d0600}.c244{fill:#7e0310}.c245{fill:#7e4002}.c246{fill:#7f4121}.c247{fill:#7f5203}.c248{fill:#807f7f}.c249{fill:#816f6f}.c250{fill:#824903}.c251{fill:#82682f}.c252{fill:#830316}.c253{fill:#83eceb}.c254{fill:#840915}.c255{fill:#848484}.c256{fill:#848999}.c257{fill:#850500}.c258{fill:#850915}.c259{fill:#858585}.c260{fill:#85db67}.c261{fill:#868787}.c262{fill:#87b037}.c263{fill:#880198}.c264{fill:#8ae586}.c265{fill:#8b4b00}.c266{fill:#8c170c}.c267{fill:#8c898b}.c268{fill:#8cbb2f}.c269{fill:#8d0015}.c270{fill:#8e23f2}.c271{fill:#8e5345}.c272{fill:#8e5900}.c273{fill:#8e5c00}.c274{fill:#8e7a16}.c275{fill:#8f6948}.c276{fill:#915e3c}.c277{fill:#916302}.c278{fill:#919191}.c279{fill:#920505}.c280{fill:#929192}.c281{fill:#930900}.c282{fill:#94910c}.c283{fill:#952318}.c284{fill:#95d8f5}.c285{fill:#96a3b1}.c286{fill:#974c0e}.c287{fill:#977730}.c288{fill:#989898}.c289{fill:#99ceec}.c290{fill:#9b0413}.c291{fill:#9b0993}.c292{fill:#9b3e00}.c293{fill:#9b8301}.c294{fill:#9c5582}.c295{fill:#9c8a22}.c296{fill:#9d7b10}.c297{fill:#9d8664}.c298{fill:#9eaecd}.c299{fill:#9ecfbe}.c300{fill:#9f0206}.c301{fill:#9f4c85}.c302{fill:#9fdcf7}.c303{fill:#a0a0a2}.c304{fill:#a0e066}.c305{fill:#a163a0}.c306{fill:#a17a01}.c307{fill:#a25201}.c308{fill:#a26adc}.c309{fill:#a27f08}.c310{fill:#a29da0}.c311{fill:#a37909}.c312{fill:#a3a3a3}.c313{fill:#a50001}.c314{fill:#a50311}.c315{fill:#a50f10}.c316{fill:#a642b6}.c317{fill:#a67b0d}.c318{fill:#a6d5c5}.c319{fill:#a7a3a6}.c320{fill:#a8895d}.c321{fill:#a8b1a8}.c322{fill:#aa7d54}.c323{fill:#abaaa6}.c324{fill:#ae8f6b}.c325{fill:#af0101}.c326{fill:#af5803}.c327{fill:#af8719}.c328{fill:#afe3fa}.c329{fill:#b00101}.c330{fill:#b0acac}.c331{fill:#b0acaf}.c332{fill:#b1b1b1}.c333{fill:#b20000}.c334{fill:#b2272b}.c335{fill:#b3362a}.c336{fill:#b40909}.c337{fill:#b4b0aa}.c338{fill:#b51f17}.c339{fill:#b58f6d}.c340{fill:#b69012}.c341{fill:#b6b6b7}.c342{fill:#b6eaff}.c343{fill:#b709be}.c344{fill:#b7875c}.c345{fill:#b7905a}.c346{fill:#b8b9b9}.c347{fill:#b9263d}.c348{fill:#ba0010}.c349{fill:#ba9a04}.c350{fill:#bc1622}.c351{fill:#bc2e2e}.c352{fill:#bea101}.c353{fill:#c06c00}.c354{fill:#c0834d}.c355{fill:#c1bcbc}.c356{fill:#c20417}.c357{fill:#c29f01}.c358{fill:#c32a1c}.c359{fill:#c3762a}.c360{fill:#c3a812}.c361{fill:#c4b299}.c362{fill:#c504a9}.c363{fill:#c5c8c9}.c364{fill:#c80409}.c365{fill:#c900cb}.c366{fill:#cad0c9}.c367{fill:#cc3443}.c368{fill:#cccccc}.c369{fill:#ccced1}.c370{fill:#cd7079}.c371{fill:#cda601}.c372{fill:#cda65d}.c373{fill:#cdc3c3}.c374{fill:#cdcfd2}.c375{fill:#cdd0d2}.c376{fill:#cebd22}.c377{fill:#cfcfcf}.c378{fill:#cfd0d0}.c379{fill:#d08507}.c380{fill:#d095f5}.c381{fill:#d15b2b}.c382{fill:#d20000}.c383{fill:#d22121}.c384{fill:#d27935}.c385{fill:#d27dd4}.c386{fill:#d2b52a}.c387{fill:#d31017}.c388{fill:#d4a0f7}.c389{fill:#d4cd16}.c390{fill:#d59702}.c391{fill:#d5d5d5}.c392{fill:#d5ff84}.c393{fill:#d6b19f}.c394{fill:#d6d6d6}.c395{fill:#d70101}.c396{fill:#d7b2a0}.c397{fill:#d7b943}.c398{fill:#d8d85c}.c399{fill:#d8d8d8}.c400{fill:#d9b3fa}.c401{fill:#d9c6ab}.c402{fill:#db0d0d}.c403{fill:#db5c0f}.c404{fill:#dbb348}.c405{fill:#dbecf2}.c406{fill:#dd2a2a}.c407{fill:#dd3ea3}.c408{fill:#dd4638}.c409{fill:#dedede}.c410{fill:#dfba39}.c411{fill:#e08811}.c412{fill:#e1ebff}.c413{fill:#e25245}.c414{fill:#e26012}.c415{fill:#e27a04}.c416{fill:#e3c0b4}.c417{fill:#e3e3e3}.c418{fill:#e3edff}.c419{fill:#e3f1ff}.c420{fill:#e45526}.c421{fill:#e4c6bc}.c422{fill:#e4d954}.c423{fill:#e4effe}.c424{fill:#e504e7}.c425{fill:#e5b53b}.c426{fill:#e5c688}.c427{fill:#e5e5e5}.c428{fill:#e60e0e}.c429{fill:#e6de04}.c430{fill:#e812f5}.c431{fill:#e870d2}.c432{fill:#e92828}.c433{fill:#e936a8}.c434{fill:#e9392d}.c435{fill:#e9fadf}.c436{fill:#ea8700}.c437{fill:#eb362d}.c438{fill:#eba3ba}.c439{fill:#ebacc0}.c440{fill:#ebf4f7}.c441{fill:#ec2eab}.c442{fill:#ece401}.c443{fill:#ed6dd1}.c444{fill:#edd2b7}.c445{fill:#ee5c07}.c446{fill:#eec06e}.c447{fill:#eeca00}.c448{fill:#eeeeee}.c449{fill:#ef402c}.c450{fill:#efcb00}.c451{fill:#efeb89}.c452{fill:#efeded}.c453{fill:#f08306}.c454{fill:#f0d74d}.c455{fill:#f0e110}.c456{fill:#f19949}.c457{fill:#f1f1f1}.c458{fill:#f23289}.c459{fill:#f2584a}.c460{fill:#f2f0f0}.c461{fill:#f327ae}.c462{fill:#f33a84}.c463{fill:#f34080}.c464{fill:#f3c87b}.c465{fill:#f3f0f0}.c466{fill:#f4ab3a}.c467{fill:#f4f0f0}.c468{fill:#f4f1f1}.c469{fill:#f5596e}.c470{fill:#f5735d}.c471{fill:#f57859}.c472{fill:#f6f2f2}.c473{fill:#f7d81e}.c474{fill:#f7f4f4}.c475{fill:#f7f6f6}.c476{fill:#f8f6f6}.c477{fill:#f8f8f8}.c478{fill:#f90808}.c479{fill:#f9ce6b}.c480{fill:#f9dc3b}.c481{fill:#f9e784}.c482{fill:#f9ec76}.c483{fill:#fa1a02}.c484{fill:#faf569}.c485{fill:#faf6f6}.c486{fill:#fbdd4b}.c487{fill:#fbf6f6}.c488{fill:#fc0000}.c489{fill:#fc00ff}.c490{fill:#fcf301}.c491{fill:#fdde60}.c492{fill:#fde80c}.c493{fill:#fde85e}.c494{fill:#febc0e}.c495{fill:#fec02a}.c496{fill:#fec901}.c497{fill:#fee85d}.c498{fill:#feed84}.c499{fill:#fef601}.c500{fill:#ff0000}.c501{fill:#ff002a}.c502{fill:#ff00f6}.c503{fill:#ff2626}.c504{fill:#ff2a2f}.c505{fill:#ff7200}.c506{fill:#ff9000}.c507{fill:#ffb400}.c508{fill:#ffd627}.c509{fill:#ffd800}.c510{fill:#ffe646}.c511{fill:#fff201}.c512{fill:#fff383}.c513{fill:#fff600}.c514{fill:#ffffff}";
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Library {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
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);
}
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
function stringReplace(string memory _string, uint256 _pos, string memory _letter) internal pure returns (string memory) {
bytes memory _stringBytes = bytes(_string);
bytes memory result = new bytes(_stringBytes.length);
for(uint i = 0; i < _stringBytes.length; i++) {
result[i] = _stringBytes[i];
if(i==_pos)
result[i]=bytes(_letter)[0];
}
return string(result);
}
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;
}
}
// contracts/IToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IToken is IERC20 {
function burnFrom(address account, uint256 amount) external;
}
// SPDX-License-Identifier: Unlicense
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.8.0 <0.9.0;
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, 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(tempBytes, 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 tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// 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 tempBytes 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.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (bytes memory)
{
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
// 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. 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;
/**
* @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 "./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 String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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);
}
}
}
}
// 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;
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;
/**
* @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/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;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: 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 {}
}
// 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/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);
}
} | Generates an 8 digit config/ This will generate an 9 character string. All of them will start as 0 | function config() internal pure returns (string memory) {
string memory currentConfig = "000000000";
return currentConfig;
}
| 6,255,423 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IBondCalculator.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IStaking.sol";
import "./interfaces/ITreasury.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract BondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable DAO; // receives profit share from bond
address public immutable bondCalculator; // calculates value of LP tokens
bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference time for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
uint32 vestingTerm; // in seconds
}
// Info for bond holder
struct Bond {
uint payout; // KEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in seconds) between adjustments
uint32 lastTime; // timestamp when last adjustment made
}
constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _staking != address(0) );
staking = _staking;
// bondCalculator should be address(0) if not LP bond
bondCalculator = _bondCalculator;
isLiquidityBond = ( _bondCalculator != address(0) );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _fee uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _fee, uint _maxDebt, uint _initialDebt)
external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
decayDebt();
require( totalDebt == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
}
else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.FEE ) { // 2
require( _input <= 10000, "DAO fee cannot exceed payout" );
terms.fee = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 3
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 4
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// profits are calculated
uint fee = payout.mul( terms.fee ).div( 10000 );
uint profit = value.sub( payout ).sub( fee );
/**
principle is transferred in
approved and
deposited into the treasury, returning (_amount - profit) KEEPER
*/
IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( principle ).approve( address( treasury ), _amount );
ITreasury( treasury ).deposit( _amount, principle, profit );
if ( fee != 0 ) { // fee is transferred to dao
IERC20( KEEPER ).safeTransfer( DAO, fee );
}
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, _wrap, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
IERC20( KEEPER ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient, _wrap );
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
if( isLiquidityBond ) {
price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 );
} else {
price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 );
}
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms for reserve or liquidity bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
if ( isLiquidityBond ) {
return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );
} else {
return debtRatio();
}
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != KEEPER );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
// 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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IBondCalculator {
function markdown( address _LP ) external view returns ( uint );
function valuation( address pair_, uint amount_ ) external view returns ( uint _value );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Extended is IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IStaking {
function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint );
function claim ( address _recipient ) external returns ( uint );
function forfeit() external returns ( uint );
function toggleLock() external;
function unstake( uint _amount, bool _trigger ) external returns ( uint );
function rebase() external;
function index() external view returns ( uint );
function contractBalance() external view returns ( uint );
function totalStaked() external view returns ( uint );
function supplyInWarmup() external view returns ( uint );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint );
function withdraw( uint _amount, address _token ) external;
function valueOfToken( address _token, uint _amount ) external view returns ( uint value_ );
function mint( address _recipient, uint _amount ) external;
function mintRewards( address _recipient, uint _amount ) external;
function incurDebt( uint amount_, address token_ ) external;
function repayDebtWithReserve( uint amount_, address token_ ) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.5.0 <0.8.0;
import "./FullMath.sol";
library Babylonian {
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
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 (r < r1 ? r : r1);
}
}
library BitMath {
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library SafeMathExtended {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function add32(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function sub32(uint32 a, uint32 b) internal pure returns (uint32) {
return sub32(a, b, "SafeMath: subtraction overflow");
}
function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
require(b <= a, errorMessage);
uint32 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function mul32(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// 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.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.7.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: AGPL-3.0-or-later
pragma solidity >=0.5.0 <0.8.0;
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IBondCalculator.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IsKEEPER.sol";
import "./interfaces/IwTROVE.sol";
import "./interfaces/IStaking.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract VLPBondStakeDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // token given as payment for bond
address public immutable sKEEPER; // token given as payment for bond
address public immutable wTROVE; // Wrap sKEEPER
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable bondCalculator; // calculates value of LP tokens
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint32 vestingTerm; // in seconds
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
uint gonsPayout; // KEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in blocks) between adjustments
uint32 lastTime; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _sKEEPER != address(0) );
sKEEPER = _sKEEPER;
require( _wTROVE != address(0) );
wTROVE = _wTROVE;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _staking != address(0) );
staking = _staking;
require( _bondCalculator != address(0) );
bondCalculator = _bondCalculator;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _maxDebt, uint _initialDebt) external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
require( currentDebt() == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 2
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 3
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
IERC20( KEEPER ).approve( staking, payout );
IStaking( staking ).stake( payout, address(this), false );
IStaking( staking ).claim( address(this) );
uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout);
// depositor info is stored
bondInfo[ _depositor ] = Bond({
gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout);
emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data
return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
gonsPayout: info.gonsPayout.sub( gonsPayout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout);
uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout);
emit BondRedeemed( _recipient, _amount, _remainingAmount );
return sendOrWrap( _recipient, _wrap, _amount );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to wrap payout automatically
* @param _wrap bool
* @param _amount uint
* @return uint
*/
function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( _wrap ) { // if user wants to wrap
IERC20(sKEEPER).approve( wTROVE, _amount );
uint wrapValue = IwTROVE(wTROVE).wrap( _amount );
IwTROVE(wTROVE).transfer( _recipient, wrapValue );
} else { // if user wants to stake
IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (int) {
( , int price, , , ) = priceFeed.latestRoundData();
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice()
.mul( IBondCalculator( bondCalculator ).markdown( principle ) )
.mul( uint( assetPrice() ) )
.div( 1e12 );
}
function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) {
Bond memory info = bondInfo[ _depositor ];
payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout);
vesting = info.vesting;
lastTime = info.lastTime;
pricePaid = info.pricePaid;
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout);
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IsKEEPER is IERC20 {
function rebase( uint256 profit_, uint epoch_) external returns (uint256);
function circulatingSupply() external view returns (uint256);
function balanceOf(address who) external override view returns (uint256);
function gonsForBalance( uint amount ) external view returns ( uint );
function balanceForGons( uint gons ) external view returns ( uint );
function index() external view returns ( uint );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IwTROVE is IERC20 {
function wrap(uint _amount) external returns (uint);
function unwrap(uint _amount) external returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IBondCalculator.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IStaking.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract VLPBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable bondCalculator; // calculates value of LP tokens
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint32 vestingTerm; // in seconds
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
uint payout; // KEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in blocks) between adjustments
uint32 lastTime; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _staking != address(0) );
staking = _staking;
require( _bondCalculator != address(0) );
bondCalculator = _bondCalculator;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _maxDebt, uint _initialDebt) external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
decayDebt();
require( totalDebt == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 2
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 3
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, _wrap, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
IERC20( KEEPER ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient, _wrap );
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (int) {
( , int price, , , ) = priceFeed.latestRoundData();
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice()
.mul( IBondCalculator( bondCalculator ).markdown( principle ) )
.mul( uint( assetPrice() ) )
.div( 1e12 );
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IStaking.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract VBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable DAO; // receives profit share from bond
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint32 vestingTerm; // in seconds
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
uint payout; // KEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in blocks) between adjustments
uint32 lastTime; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _staking != address(0) );
staking = _staking;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _maxDebt, uint _initialDebt) external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
require( currentDebt() == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 2
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 3
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, _wrap, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
IERC20( KEEPER ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient, _wrap );
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (int) {
( , int price, , , ) = priceFeed.latestRoundData();
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 );
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != KEEPER );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/ITreasury.sol";
import "./libraries/SafeMathExtended.sol";
contract StakingDistributor is Ownable {
using SafeERC20 for IERC20;
using SafeMathExtended for uint256;
using SafeMathExtended for uint32;
IERC20 immutable KEEPER;
ITreasury immutable treasury;
uint32 public immutable epochLength;
uint32 public nextEpochTime;
mapping( uint => Adjust ) public adjustments;
/* ====== STRUCTS ====== */
struct Info {
uint rate; // in ten-thousandths ( 5000 = 0.5% )
address recipient;
}
Info[] public info;
struct Adjust {
bool add;
uint rate;
uint target;
}
constructor( address _treasury, address _KEEPER, uint32 _epochLength, uint32 _nextEpochTime ) {
require( _treasury != address(0) );
treasury = ITreasury( _treasury );
require( _KEEPER != address(0) );
KEEPER = IERC20( _KEEPER );
epochLength = _epochLength;
nextEpochTime = _nextEpochTime;
}
/**
@notice send epoch reward to staking contract
*/
function distribute() external returns (bool) {
if ( nextEpochTime <= uint32(block.timestamp) ) {
nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch block
// distribute rewards to each recipient
for ( uint i = 0; i < info.length; i++ ) {
if ( info[ i ].rate > 0 ) {
treasury.mintRewards( // mint and send from treasury
info[ i ].recipient,
nextRewardAt( info[ i ].rate )
);
adjust( i ); // check for adjustment
}
}
return true;
}
else {
return false;
}
}
/**
@notice increment reward rate for collector
*/
function adjust( uint _index ) internal {
Adjust memory adjustment = adjustments[ _index ];
if ( adjustment.rate != 0 ) {
if ( adjustment.add ) { // if rate should increase
info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate
if ( info[ _index ].rate >= adjustment.target ) { // if target met
adjustments[ _index ].rate = 0; // turn off adjustment
}
} else { // if rate should decrease
info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate
if ( info[ _index ].rate <= adjustment.target || info[ _index ].rate < adjustment.rate) { // if target met
adjustments[ _index ].rate = 0; // turn off adjustment
}
}
}
}
/* ====== VIEW FUNCTIONS ====== */
/**
@notice view function for next reward at given rate
@param _rate uint
@return uint
*/
function nextRewardAt( uint _rate ) public view returns ( uint ) {
return KEEPER.totalSupply().mul( _rate ).div( 1000000 );
}
/**
@notice view function for next reward for specified address
@param _recipient address
@return uint
*/
function nextRewardFor( address _recipient ) public view returns ( uint ) {
uint reward;
for ( uint i = 0; i < info.length; i++ ) {
if ( info[ i ].recipient == _recipient ) {
reward = nextRewardAt( info[ i ].rate );
}
}
return reward;
}
/* ====== POLICY FUNCTIONS ====== */
/**
@notice adds recipient for distributions
@param _recipient address
@param _rewardRate uint
*/
function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner() {
require( _recipient != address(0) );
info.push( Info({
recipient: _recipient,
rate: _rewardRate
}));
}
/**
@notice removes recipient for distributions
@param _index uint
@param _recipient address
*/
function removeRecipient( uint _index, address _recipient ) external onlyOwner() {
require( _recipient == info[ _index ].recipient );
info[ _index ] = info[info.length-1];
info.pop();
}
/**
@notice set adjustment info for a collector's reward rate
@param _index uint
@param _add bool
@param _rate uint
@param _target uint
*/
function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyOwner() {
require(_add || info[ _index ].rate >= _rate, "Negative adjustment rate cannot be more than current rate.");
adjustments[ _index ] = Adjust({
add: _add,
rate: _rate,
target: _target
});
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IBondCalculator.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IKeplerERC20.sol";
contract oldTreasury is Ownable {
using SafeERC20 for IERC20Extended;
using SafeMath for uint;
event Deposit( address indexed token, uint amount, uint value );
event Withdrawal( address indexed token, uint amount, uint value );
event CreateDebt( address indexed debtor, address indexed token, uint amount, uint value );
event RepayDebt( address indexed debtor, address indexed token, uint amount, uint value );
event ReservesManaged( address indexed token, uint amount );
event ReservesUpdated( uint indexed totalReserves );
event ReservesAudited( uint indexed totalReserves );
event RewardsMinted( address indexed caller, address indexed recipient, uint amount );
event ChangeQueued( MANAGING indexed managing, address queued );
event ChangeActivated( MANAGING indexed managing, address activated, bool result );
enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SKEEPER }
IKeplerERC20 immutable KEEPER;
uint public immutable secondsNeededForQueue;
uint public constant keeperDecimals = 9;
address[] public reserveTokens; // Push only, beware false-positives.
mapping( address => bool ) public isReserveToken;
mapping( address => uint ) public reserveTokenQueue; // Delays changes to mapping.
address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isReserveDepositor;
mapping( address => uint ) public reserveDepositorQueue; // Delays changes to mapping.
address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isReserveSpender;
mapping( address => uint ) public reserveSpenderQueue; // Delays changes to mapping.
address[] public liquidityTokens; // Push only, beware false-positives.
mapping( address => bool ) public isLiquidityToken;
mapping( address => uint ) public LiquidityTokenQueue; // Delays changes to mapping.
address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isLiquidityDepositor;
mapping( address => uint ) public LiquidityDepositorQueue; // Delays changes to mapping.
mapping( address => address ) public bondCalculator; // bond calculator for liquidity token
address[] public reserveManagers; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isReserveManager;
mapping( address => uint ) public ReserveManagerQueue; // Delays changes to mapping.
address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isLiquidityManager;
mapping( address => uint ) public LiquidityManagerQueue; // Delays changes to mapping.
address[] public debtors; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isDebtor;
mapping( address => uint ) public debtorQueue; // Delays changes to mapping.
mapping( address => uint ) public debtorBalance;
address[] public rewardManagers; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isRewardManager;
mapping( address => uint ) public rewardManagerQueue; // Delays changes to mapping.
address public sKEEPER;
uint public sKEEPERQueue; // Delays change to sKEEPER address
uint public totalReserves; // Risk-free value of all assets
uint public totalDebt;
constructor (address _KEEPER, address _USDC, address _DAI, uint _secondsNeededForQueue) {
require( _KEEPER != address(0) );
KEEPER = IKeplerERC20(_KEEPER);
isReserveToken[ _USDC] = true;
reserveTokens.push( _USDC );
isReserveToken[ _DAI ] = true;
reserveTokens.push( _DAI );
// isLiquidityToken[ _KEEPERDAI ] = true;
// liquidityTokens.push( _KEEPERDAI );
secondsNeededForQueue = _secondsNeededForQueue;
}
/**
@notice allow approved address to deposit an asset for KEEPER
@param _amount uint
@param _token address
@param _profit uint
@return send_ uint
*/
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) {
require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" );
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
if ( isReserveToken[ _token ] ) {
require( isReserveDepositor[ msg.sender ], "Not approved" );
} else {
require( isLiquidityDepositor[ msg.sender ], "Not approved" );
}
uint value = valueOfToken(_token, _amount);
// mint KEEPER needed and store amount of rewards for distribution
send_ = value.sub( _profit );
KEEPER.mint( msg.sender, send_ );
totalReserves = totalReserves.add( value );
emit ReservesUpdated( totalReserves );
emit Deposit( _token, _amount, value );
}
/**
@notice allow approved address to burn KEEPER for reserves
@param _amount uint
@param _token address
*/
function withdraw( uint _amount, address _token ) external {
require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
require( isReserveSpender[ msg.sender ] == true, "Not approved" );
uint value = valueOfToken( _token, _amount );
KEEPER.burnFrom( msg.sender, value );
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20Extended( _token ).safeTransfer( msg.sender, _amount );
emit Withdrawal( _token, _amount, value );
}
/**
@notice allow approved address to borrow reserves
@param _amount uint
@param _token address
*/
function incurDebt( uint _amount, address _token ) external {
require( isDebtor[ msg.sender ], "Not approved" );
require( isReserveToken[ _token ], "Not accepted" );
uint value = valueOfToken( _token, _amount );
uint maximumDebt = IERC20Extended( sKEEPER ).balanceOf( msg.sender ); // Can only borrow against sKEEPER held
uint availableDebt = maximumDebt.sub( debtorBalance[ msg.sender ] );
require( value <= availableDebt, "Exceeds debt limit" );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].add( value );
totalDebt = totalDebt.add( value );
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20Extended( _token ).transfer( msg.sender, _amount );
emit CreateDebt( msg.sender, _token, _amount, value );
}
/**
@notice allow approved address to repay borrowed reserves with reserves
@param _amount uint
@param _token address
*/
function repayDebtWithReserve( uint _amount, address _token ) external {
require( isDebtor[ msg.sender ], "Not approved" );
require( isReserveToken[ _token ], "Not accepted" );
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
uint value = valueOfToken( _token, _amount );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( value );
totalDebt = totalDebt.sub( value );
totalReserves = totalReserves.add( value );
emit ReservesUpdated( totalReserves );
emit RepayDebt( msg.sender, _token, _amount, value );
}
/**
@notice allow approved address to repay borrowed reserves with KEEPER
@param _amount uint
*/
function repayDebtWithKEEPER( uint _amount ) external {
require( isDebtor[ msg.sender ], "Not approved" );
KEEPER.burnFrom( msg.sender, _amount );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount );
totalDebt = totalDebt.sub( _amount );
emit RepayDebt( msg.sender, address(KEEPER), _amount, _amount );
}
/**
@notice allow approved address to withdraw assets
@param _token address
@param _amount uint
*/
function manage( address _token, uint _amount ) external {
if( isLiquidityToken[ _token ] ) {
require( isLiquidityManager[ msg.sender ], "Not approved" );
} else {
require( isReserveManager[ msg.sender ], "Not approved" );
}
uint value = valueOfToken(_token, _amount);
require( value <= excessReserves(), "Insufficient reserves" );
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20Extended( _token ).safeTransfer( msg.sender, _amount );
emit ReservesManaged( _token, _amount );
}
/**
@notice send epoch reward to staking contract
*/
function mintRewards( address _recipient, uint _amount ) external {
require( isRewardManager[ msg.sender ], "Not approved" );
require( _amount <= excessReserves(), "Insufficient reserves" );
KEEPER.mint( _recipient, _amount );
emit RewardsMinted( msg.sender, _recipient, _amount );
}
/**
@notice returns excess reserves not backing tokens
@return uint
*/
function excessReserves() public view returns ( uint ) {
return totalReserves.sub( KEEPER.totalSupply().sub( totalDebt ) );
}
/**
@notice takes inventory of all tracked assets
@notice always consolidate to recognized reserves before audit
*/
function auditReserves() external onlyOwner() {
uint reserves;
for( uint i = 0; i < reserveTokens.length; i++ ) {
reserves = reserves.add (
valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) )
);
}
for( uint i = 0; i < liquidityTokens.length; i++ ) {
reserves = reserves.add (
valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) )
);
}
totalReserves = reserves;
emit ReservesUpdated( reserves );
emit ReservesAudited( reserves );
}
/**
@notice returns KEEPER valuation of asset
@param _token address
@param _amount uint
@return value_ uint
*/
function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) {
if ( isReserveToken[ _token ] ) {
// convert amount to match KEEPER decimals
value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() );
} else if ( isLiquidityToken[ _token ] ) {
value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount );
}
}
/**
@notice queue address to change boolean in mapping
@param _managing MANAGING
@param _address address
@return bool
*/
function queue( MANAGING _managing, address _address ) external onlyOwner() returns ( bool ) {
require( _address != address(0) );
if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0
reserveDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.RESERVESPENDER ) { // 1
reserveSpenderQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.RESERVETOKEN ) { // 2
reserveTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3
ReserveManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) );
} else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4
LiquidityDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5
LiquidityTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6
LiquidityManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) );
} else if ( _managing == MANAGING.DEBTOR ) { // 7
debtorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.REWARDMANAGER ) { // 8
rewardManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue );
} else if ( _managing == MANAGING.SKEEPER ) { // 9
sKEEPERQueue = block.timestamp.add( secondsNeededForQueue );
} else return false;
emit ChangeQueued( _managing, _address );
return true;
}
/**
@notice verify queue then set boolean in mapping
@param _managing MANAGING
@param _address address
@param _calculator address
@return bool
*/
function toggle( MANAGING _managing, address _address, address _calculator ) external onlyOwner() returns ( bool ) {
require( _address != address(0) );
bool result;
if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0
if ( requirements( reserveDepositorQueue, isReserveDepositor, _address ) ) {
reserveDepositorQueue[ _address ] = 0;
if( !listContains( reserveDepositors, _address ) ) {
reserveDepositors.push( _address );
}
}
result = !isReserveDepositor[ _address ];
isReserveDepositor[ _address ] = result;
} else if ( _managing == MANAGING.RESERVESPENDER ) { // 1
if ( requirements( reserveSpenderQueue, isReserveSpender, _address ) ) {
reserveSpenderQueue[ _address ] = 0;
if( !listContains( reserveSpenders, _address ) ) {
reserveSpenders.push( _address );
}
}
result = !isReserveSpender[ _address ];
isReserveSpender[ _address ] = result;
} else if ( _managing == MANAGING.RESERVETOKEN ) { // 2
if ( requirements( reserveTokenQueue, isReserveToken, _address ) ) {
reserveTokenQueue[ _address ] = 0;
if( !listContains( reserveTokens, _address ) ) {
reserveTokens.push( _address );
}
}
result = !isReserveToken[ _address ];
isReserveToken[ _address ] = result;
} else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3
if ( requirements( ReserveManagerQueue, isReserveManager, _address ) ) {
reserveManagers.push( _address );
ReserveManagerQueue[ _address ] = 0;
if( !listContains( reserveManagers, _address ) ) {
reserveManagers.push( _address );
}
}
result = !isReserveManager[ _address ];
isReserveManager[ _address ] = result;
} else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4
if ( requirements( LiquidityDepositorQueue, isLiquidityDepositor, _address ) ) {
liquidityDepositors.push( _address );
LiquidityDepositorQueue[ _address ] = 0;
if( !listContains( liquidityDepositors, _address ) ) {
liquidityDepositors.push( _address );
}
}
result = !isLiquidityDepositor[ _address ];
isLiquidityDepositor[ _address ] = result;
} else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5
if ( requirements( LiquidityTokenQueue, isLiquidityToken, _address ) ) {
LiquidityTokenQueue[ _address ] = 0;
if( !listContains( liquidityTokens, _address ) ) {
liquidityTokens.push( _address );
}
}
result = !isLiquidityToken[ _address ];
isLiquidityToken[ _address ] = result;
bondCalculator[ _address ] = _calculator;
} else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6
if ( requirements( LiquidityManagerQueue, isLiquidityManager, _address ) ) {
LiquidityManagerQueue[ _address ] = 0;
if( !listContains( liquidityManagers, _address ) ) {
liquidityManagers.push( _address );
}
}
result = !isLiquidityManager[ _address ];
isLiquidityManager[ _address ] = result;
} else if ( _managing == MANAGING.DEBTOR ) { // 7
if ( requirements( debtorQueue, isDebtor, _address ) ) {
debtorQueue[ _address ] = 0;
if( !listContains( debtors, _address ) ) {
debtors.push( _address );
}
}
result = !isDebtor[ _address ];
isDebtor[ _address ] = result;
} else if ( _managing == MANAGING.REWARDMANAGER ) { // 8
if ( requirements( rewardManagerQueue, isRewardManager, _address ) ) {
rewardManagerQueue[ _address ] = 0;
if( !listContains( rewardManagers, _address ) ) {
rewardManagers.push( _address );
}
}
result = !isRewardManager[ _address ];
isRewardManager[ _address ] = result;
} else if ( _managing == MANAGING.SKEEPER ) { // 9
sKEEPERQueue = 0;
sKEEPER = _address;
result = true;
} else return false;
emit ChangeActivated( _managing, _address, result );
return true;
}
/**
@notice checks requirements and returns altered structs
@param queue_ mapping( address => uint )
@param status_ mapping( address => bool )
@param _address address
@return bool
*/
function requirements(
mapping( address => uint ) storage queue_,
mapping( address => bool ) storage status_,
address _address
) internal view returns ( bool ) {
if ( !status_[ _address ] ) {
require( queue_[ _address ] != 0, "Must queue" );
require( queue_[ _address ] <= block.timestamp, "Queue not expired" );
return true;
} return false;
}
/**
@notice checks array to ensure against duplicate
@param _list address[]
@param _token address
@return bool
*/
function listContains( address[] storage _list, address _token ) internal view returns ( bool ) {
for( uint i = 0; i < _list.length; i++ ) {
if( _list[ i ] == _token ) {
return true;
}
}
return false;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IKeplerERC20 is IERC20 {
function decimals() external view returns (uint8);
function mint(uint256 amount_) external;
function mint(address account_, uint256 ammount_) external;
function burnFrom(address account_, uint256 amount_) external;
function vault() external returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "./interfaces/IStaking.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract StakingHelper {
address public immutable staking;
address public immutable KEEPER;
constructor ( address _staking, address _KEEPER ) {
require( _staking != address(0) );
staking = _staking;
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
}
function stake( uint _amount, bool _wrap ) external {
IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount );
IERC20( KEEPER ).approve( staking, _amount );
IStaking( staking ).stake( _amount, msg.sender, _wrap );
IStaking( staking ).claim( msg.sender );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IDistributor.sol";
import "./interfaces/IiKEEPER.sol";
import "./interfaces/IsKEEPER.sol";
import "./interfaces/IwTROVE.sol";
import "./libraries/SafeMathExtended.sol";
contract oldStaking is Ownable {
using SafeERC20 for IERC20;
using SafeERC20 for IsKEEPER;
using SafeMathExtended for uint256;
using SafeMathExtended for uint32;
event DistributorSet( address distributor );
event WarmupSet( uint warmup );
event IKeeperSet( address iKEEPER );
struct Epoch {
uint32 length;
uint32 endTime;
uint32 number;
uint distribute;
}
struct Claim {
uint deposit;
uint gons;
uint expiry;
bool lock; // prevents malicious delays
}
IERC20 public immutable KEEPER;
IsKEEPER public immutable sKEEPER;
IwTROVE public immutable wTROVE;
Epoch public epoch;
address public distributor;
address public iKEEPER;
mapping( address => Claim ) public warmupInfo;
uint32 public warmupPeriod;
uint gonsInWarmup;
constructor (address _KEEPER, address _sKEEPER, address _wTROVE, uint32 _epochLength, uint32 _firstEpochNumber, uint32 _firstEpochTime) {
require( _KEEPER != address(0) );
KEEPER = IERC20( _KEEPER );
require( _sKEEPER != address(0) );
sKEEPER = IsKEEPER( _sKEEPER );
require( _wTROVE != address(0) );
wTROVE = IwTROVE( _wTROVE );
epoch = Epoch({
length: _epochLength,
number: _firstEpochNumber,
endTime: _firstEpochTime,
distribute: 0
});
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice stake KEEPER to enter warmup
* @param _amount uint
* @param _recipient address
*/
function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ) {
rebase();
KEEPER.safeTransferFrom( msg.sender, address(this), _amount );
if ( warmupPeriod == 0 ) {
return _send( _recipient, _amount, _wrap );
}
else {
Claim memory info = warmupInfo[ _recipient ];
if ( !info.lock ) {
require( _recipient == msg.sender, "External deposits for account are locked" );
}
uint sKeeperGons = sKEEPER.gonsForBalance( _amount );
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add(_amount),
gons: info.gons.add(sKeeperGons),
expiry: epoch.number.add32(warmupPeriod),
lock: info.lock
});
gonsInWarmup = gonsInWarmup.add(sKeeperGons);
return _amount;
}
}
function stakeInvest( uint _stakeAmount, uint _investAmount, address _recipient, bool _wrap ) external {
rebase();
uint keeperAmount = _stakeAmount.add(_investAmount.div(1e9));
KEEPER.safeTransferFrom( msg.sender, address(this), keeperAmount );
_send( _recipient, _stakeAmount, _wrap );
sKEEPER.approve(iKEEPER, _investAmount);
IiKEEPER(iKEEPER).wrap(_investAmount, _recipient);
}
/**
* @notice retrieve stake from warmup
* @param _recipient address
*/
function claim ( address _recipient ) public returns ( uint ) {
Claim memory info = warmupInfo[ _recipient ];
if ( epoch.number >= info.expiry && info.expiry != 0 ) {
delete warmupInfo[ _recipient ];
gonsInWarmup = gonsInWarmup.sub(info.gons);
return _send( _recipient, sKEEPER.balanceForGons( info.gons ), false);
}
return 0;
}
/**
* @notice forfeit stake and retrieve KEEPER
*/
function forfeit() external returns ( uint ) {
Claim memory info = warmupInfo[ msg.sender ];
delete warmupInfo[ msg.sender ];
gonsInWarmup = gonsInWarmup.sub(info.gons);
KEEPER.safeTransfer( msg.sender, info.deposit );
return info.deposit;
}
/**
* @notice prevent new deposits or claims from ext. address (protection from malicious activity)
*/
function toggleLock() external {
warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock;
}
/**
* @notice redeem sKEEPER for KEEPER
* @param _amount uint
* @param _trigger bool
*/
function unstake( uint _amount, bool _trigger ) external returns ( uint ) {
if ( _trigger ) {
rebase();
}
uint amount = _amount;
sKEEPER.safeTransferFrom( msg.sender, address(this), _amount );
KEEPER.safeTransfer( msg.sender, amount );
return amount;
}
/**
@notice trigger rebase if epoch over
*/
function rebase() public {
if( epoch.endTime <= uint32(block.timestamp) ) {
sKEEPER.rebase( epoch.distribute, epoch.number );
epoch.endTime = epoch.endTime.add32(epoch.length);
epoch.number++;
if ( distributor != address(0) ) {
IDistributor( distributor ).distribute();
}
uint contractBalanceVal = contractBalance();
uint totalStakedVal = totalStaked();
if( contractBalanceVal <= totalStakedVal ) {
epoch.distribute = 0;
}
else {
epoch.distribute = contractBalanceVal.sub(totalStakedVal);
}
}
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice send staker their amount as sKEEPER or gKEEPER
* @param _recipient address
* @param _amount uint
*/
function _send( address _recipient, uint _amount, bool _wrap ) internal returns ( uint ) {
if (_wrap) {
sKEEPER.approve( address( wTROVE ), _amount );
uint wrapValue = wTROVE.wrap( _amount );
wTROVE.transfer( _recipient, wrapValue );
} else {
sKEEPER.safeTransfer( _recipient, _amount ); // send as sKEEPER (equal unit as KEEPER)
}
return _amount;
}
/* ========== VIEW FUNCTIONS ========== */
/**
@notice returns the sKEEPER index, which tracks rebase growth
@return uint
*/
function index() public view returns ( uint ) {
return sKEEPER.index();
}
/**
@notice returns contract KEEPER holdings, including bonuses provided
@return uint
*/
function contractBalance() public view returns ( uint ) {
return KEEPER.balanceOf( address(this) );
}
function totalStaked() public view returns ( uint ) {
return sKEEPER.circulatingSupply();
}
function supplyInWarmup() public view returns ( uint ) {
return sKEEPER.balanceForGons( gonsInWarmup );
}
/* ========== MANAGERIAL FUNCTIONS ========== */
/**
@notice sets the contract address for LP staking
@param _address address
*/
function setDistributor( address _address ) external onlyOwner() {
distributor = _address;
emit DistributorSet( _address );
}
/**
* @notice set warmup period for new stakers
* @param _warmupPeriod uint
*/
function setWarmup( uint32 _warmupPeriod ) external onlyOwner() {
warmupPeriod = _warmupPeriod;
emit WarmupSet( _warmupPeriod );
}
function setIKeeper( address _iKEEPER ) external onlyOwner() {
iKEEPER = _iKEEPER;
emit IKeeperSet( _iKEEPER );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IDistributor {
function distribute() external returns ( bool );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IiKEEPER is IERC20 {
function wrap(uint _amount, address _recipient) external;
function unwrap(uint _amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/IWETH9.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IsKEEPER.sol";
import "./interfaces/IwTROVE.sol";
import "./interfaces/IStaking.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract EthBondStakeDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // token given as payment for bond
address public immutable sKEEPER; // token given as payment for bond
address public immutable wTROVE; // Wrap sKEEPER
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable DAO; // receives profit share from bond
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint32 vestingTerm; // in seconds
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
uint gonsPayout; // KEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in blocks) between adjustments
uint32 lastTime; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _feed) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _sKEEPER != address(0) );
sKEEPER = _sKEEPER;
require( _wTROVE != address(0) );
wTROVE = _wTROVE;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _staking != address(0) );
staking = _staking;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _maxDebt, uint _initialDebt) external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
require( currentDebt() == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 2
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 3
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
if (address(this).balance >= _amount) {
// pay with WETH9
IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay
IWETH9(principle).transfer(treasury, _amount);
} else {
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
}
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
IERC20( KEEPER ).approve( staking, payout );
IStaking( staking ).stake( payout, address(this), false );
IStaking( staking ).claim( address(this) );
uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout);
// depositor info is stored
bondInfo[ _depositor ] = Bond({
gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
refundETH(); //refund user if needed
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout);
emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data
return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
gonsPayout: info.gonsPayout.sub( gonsPayout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout);
uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout);
emit BondRedeemed( _recipient, _amount, _remainingAmount );
return sendOrWrap( _recipient, _wrap, _amount );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to wrap payout automatically
* @param _wrap bool
* @param _amount uint
* @return uint
*/
function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( _wrap ) { // if user wants to wrap
IERC20(sKEEPER).approve( wTROVE, _amount );
uint wrapValue = IwTROVE(wTROVE).wrap( _amount );
IwTROVE(wTROVE).transfer( _recipient, wrapValue );
} else { // if user wants to stake
IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (int) {
( , int price, , , ) = priceFeed.latestRoundData();
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 );
}
function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) {
Bond memory info = bondInfo[ _depositor ];
payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout);
vesting = info.vesting;
lastTime = info.lastTime;
pricePaid = info.pricePaid;
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout);
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != KEEPER );
require( _token != sKEEPER );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
function refundETH() internal {
if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance);
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IsKEEPER.sol";
contract wTROVE is ERC20 {
using SafeMath for uint;
address public immutable TROVE;
constructor(address _TROVE) ERC20("Wrapped Trove", "wTROVE") {
require(_TROVE != address(0));
TROVE = _TROVE;
}
/**
@notice wrap TROVE
@param _amount uint
@return uint
*/
function wrap( uint _amount ) external returns ( uint ) {
IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount );
uint value = TROVETowTROVE( _amount );
_mint( msg.sender, value );
return value;
}
/**
@notice unwrap TROVE
@param _amount uint
@return uint
*/
function unwrap( uint _amount ) external returns ( uint ) {
_burn( msg.sender, _amount );
uint value = wTROVEToTROVE( _amount );
IsKEEPER( TROVE ).transfer( msg.sender, value );
return value;
}
/**
@notice converts wTROVE amount to TROVE
@param _amount uint
@return uint
*/
function wTROVEToTROVE( uint _amount ) public view returns ( uint ) {
return _amount.mul( IsKEEPER( TROVE ).index() ).div( 10 ** decimals() );
}
/**
@notice converts TROVE amount to wTROVE
@param _amount uint
@return uint
*/
function TROVETowTROVE( uint _amount ) public view returns ( uint ) {
return _amount.mul( 10 ** decimals() ).div( IsKEEPER( TROVE ).index() );
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract USDC is ERC20, Ownable {
using SafeMath for uint256;
constructor() ERC20("USDC", "USDC") {
}
function mint(address account_, uint256 amount_) external onlyOwner() {
_mint(account_, amount_);
}
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./interfaces/IStaking.sol";
contract sKeplerERC20 is ERC20 {
using SafeMath for uint256;
event StakingContractUpdated(address stakingContract);
event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply);
event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index);
address initializer;
address public stakingContract; // balance used to calc rebase
uint8 private constant _tokenDecimals = 9;
uint INDEX; // Index Gons - tracks rebase growth
uint _totalSupply;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**_tokenDecimals;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
mapping (address => mapping (address => uint256)) private _allowedValue;
struct Rebase {
uint epoch;
uint rebase; // 18 decimals
uint totalStakedBefore;
uint totalStakedAfter;
uint amountRebased;
uint index;
uint timeOccured;
}
Rebase[] public rebases; // past rebase data
modifier onlyStakingContract() {
require(msg.sender == stakingContract);
_;
}
constructor() ERC20("Staked Keeper", "TROVE") {
_setupDecimals(_tokenDecimals);
initializer = msg.sender;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
}
function setIndex(uint _INDEX) external {
require(msg.sender == initializer);
require(INDEX == 0);
require(_INDEX != 0);
INDEX = gonsForBalance(_INDEX);
}
// do this last
function initialize(address _stakingContract) external {
require(msg.sender == initializer);
require(_stakingContract != address(0));
stakingContract = _stakingContract;
_gonBalances[ stakingContract ] = TOTAL_GONS;
emit Transfer(address(0x0), stakingContract, _totalSupply);
emit StakingContractUpdated(_stakingContract);
initializer = address(0);
}
/**
@notice increases sKEEPER supply to increase staking balances relative to _profit
@param _profit uint256
@return uint256
*/
function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) {
uint256 rebaseAmount;
uint256 _circulatingSupply = circulatingSupply();
if (_profit == 0) {
emit LogSupply(_epoch, block.timestamp, _totalSupply);
emit LogRebase(_epoch, 0, index());
return _totalSupply;
}
else if (_circulatingSupply > 0) {
rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply);
}
else {
rebaseAmount = _profit;
}
_totalSupply = _totalSupply.add(rebaseAmount);
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
_storeRebase(_circulatingSupply, _profit, _epoch);
return _totalSupply;
}
/**
@notice emits event with data about rebase
@param _previousCirculating uint
@param _profit uint
@param _epoch uint
@return bool
*/
function _storeRebase(uint _previousCirculating, uint _profit, uint _epoch) internal returns (bool) {
uint rebasePercent = _profit.mul(1e18).div(_previousCirculating);
rebases.push(Rebase ({
epoch: _epoch,
rebase: rebasePercent, // 18 decimals
totalStakedBefore: _previousCirculating,
totalStakedAfter: circulatingSupply(),
amountRebased: _profit,
index: index(),
timeOccured: uint32(block.timestamp)
}));
emit LogSupply(_epoch, block.timestamp, _totalSupply);
emit LogRebase(_epoch, rebasePercent, index());
return true;
}
/* =================================== VIEW FUNCTIONS ========================== */
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who) public view override returns (uint256) {
return _gonBalances[ who ].div(_gonsPerFragment);
}
/**
* @param who The address to query.
* @return The gon balance of the specified address.
*/
function scaledBalanceOf(address who) external view returns (uint256) {
return _gonBalances[who];
}
function gonsForBalance(uint amount) public view returns (uint) {
return amount * _gonsPerFragment;
}
function balanceForGons(uint gons) public view returns (uint) {
return gons / _gonsPerFragment;
}
// Staking contract holds excess sKEEPER
function circulatingSupply() public view returns (uint) {
return _totalSupply.sub(balanceOf(stakingContract)).add(IStaking(stakingContract).supplyInWarmup());
}
function index() public view returns (uint) {
return balanceForGons(INDEX);
}
function allowance(address owner_, address spender) public view override returns (uint256) {
return _allowedValue[ owner_ ][ spender ];
}
/* ================================= MUTATIVE FUNCTIONS ====================== */
function transfer(address to, uint256 value) public override returns (bool) {
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub(gonValue);
_gonBalances[ to ] = _gonBalances[ to ].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub(value);
emit Approval(from, msg.sender, _allowedValue[ from ][ msg.sender ]);
uint256 gonValue = gonsForBalance(value);
_gonBalances[ from ] = _gonBalances[from].sub(gonValue);
_gonBalances[ to ] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
function _approve(address owner, address spender, uint256 value) internal override virtual {
_allowedValue[owner][spender] = value;
emit Approval(owner, spender, value);
}
function approve(address spender, uint256 value) public override returns (bool) {
_allowedValue[ msg.sender ][ spender ] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) {
_allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add(addedValue);
emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) {
uint256 oldValue = _allowedValue[ msg.sender ][ spender ];
if (subtractedValue >= oldValue) {
_allowedValue[ msg.sender ][ spender ] = 0;
} else {
_allowedValue[ msg.sender ][ spender ] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]);
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract cKEEPER is ERC20, Ownable {
using SafeMath for uint;
bool public requireSellerApproval;
mapping( address => bool ) public isApprovedSeller;
constructor() ERC20("Call Keeper", "cKEEPER") {
uint initSupply = 500000000 * 1e18;
_addApprovedSeller( address(this) );
_addApprovedSeller( msg.sender );
_mint( msg.sender, initSupply );
requireSellerApproval = true;
}
function allowOpenTrading() external onlyOwner() returns ( bool ) {
requireSellerApproval = false;
return requireSellerApproval;
}
function _addApprovedSeller( address approvedSeller_ ) internal {
isApprovedSeller[approvedSeller_] = true;
}
function addApprovedSeller( address approvedSeller_ ) external onlyOwner() returns ( bool ) {
_addApprovedSeller( approvedSeller_ );
return isApprovedSeller[approvedSeller_];
}
function addApprovedSellers( address[] calldata approvedSellers_ ) external onlyOwner() returns ( bool ) {
for( uint iteration_; iteration_ < approvedSellers_.length; iteration_++ ) {
_addApprovedSeller( approvedSellers_[iteration_] );
}
return true;
}
function _removeApprovedSeller( address disapprovedSeller_ ) internal {
isApprovedSeller[disapprovedSeller_] = false;
}
function removeApprovedSeller( address disapprovedSeller_ ) external onlyOwner() returns ( bool ) {
_removeApprovedSeller( disapprovedSeller_ );
return isApprovedSeller[disapprovedSeller_];
}
function removeApprovedSellers( address[] calldata disapprovedSellers_ ) external onlyOwner() returns ( bool ) {
for( uint iteration_; iteration_ < disapprovedSellers_.length; iteration_++ ) {
_removeApprovedSeller( disapprovedSellers_[iteration_] );
}
return true;
}
function _beforeTokenTransfer(address from_, address to_, uint256 amount_ ) internal override {
require( (balanceOf(to_) > 0 || isApprovedSeller[from_] == true || !requireSellerApproval), "Account not approved to transfer cKEEPER." );
}
function burn(uint256 amount_) public virtual {
_burn( msg.sender, amount_ );
}
function burnFrom( address account_, uint256 amount_ ) public virtual {
_burnFrom( account_, amount_ );
}
function _burnFrom( address account_, uint256 amount_ ) internal virtual {
uint256 decreasedAllowance_ = allowance( account_, msg.sender ).sub( amount_, "ERC20: burn amount exceeds allowance");
_approve( account_, msg.sender, decreasedAllowance_ );
_burn( account_, amount_ );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
interface IBond {
function redeem( address _recipient, bool _stake ) external returns ( uint );
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ );
}
contract RedeemHelper is Ownable {
address[] public bonds;
function redeemAll( address _recipient, bool _stake ) external {
for( uint i = 0; i < bonds.length; i++ ) {
if ( bonds[i] != address(0) ) {
if ( IBond( bonds[i] ).pendingPayoutFor( _recipient ) > 0 ) {
IBond( bonds[i] ).redeem( _recipient, _stake );
}
}
}
}
function addBondContract( address _bond ) external onlyOwner() {
require( _bond != address(0) );
bonds.push( _bond );
}
function removeBondContract( uint _index ) external onlyOwner() {
bonds[ _index ] = address(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract KEEPERCircSupply is Ownable {
using SafeMath for uint;
address public KEEPER;
address[] public nonCirculatingKEEPERAddresses;
constructor (address _KEEPER) {
KEEPER = _KEEPER;
}
function KEEPERCirculatingSupply() external view returns (uint) {
uint _totalSupply = IERC20( KEEPER ).totalSupply();
uint _circulatingSupply = _totalSupply.sub( getNonCirculatingKEEPER() );
return _circulatingSupply;
}
function getNonCirculatingKEEPER() public view returns ( uint ) {
uint _nonCirculatingKEEPER;
for( uint i=0; i < nonCirculatingKEEPERAddresses.length; i = i.add( 1 ) ) {
_nonCirculatingKEEPER = _nonCirculatingKEEPER.add( IERC20( KEEPER ).balanceOf( nonCirculatingKEEPERAddresses[i] ) );
}
return _nonCirculatingKEEPER;
}
function setNonCirculatingKEEPERAddresses( address[] calldata _nonCirculatingAddresses ) external onlyOwner() returns ( bool ) {
nonCirculatingKEEPERAddresses = _nonCirculatingAddresses;
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/ITreasury.sol";
import "../interfaces/IStaking.sol";
interface IcKEEPER {
function burnFrom( address account_, uint256 amount_ ) external;
}
contract cKeeperExercise is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
address public immutable cKEEPER;
address public immutable KEEPER;
address public immutable USDC;
address public immutable treasury;
address public staking;
uint private constant CLIFF = 250000 * 10**9; // Minimum KEEPER supply to exercise
uint private constant TOUCHDOWN = 5000000 * 10**9; // Maximum KEEPER supply for percent increase
uint private constant Y_INCREASE = 35000; // Increase from CLIFF to TOUCHDOWN is 3.5%. 4 decimals used
// uint private constant SLOPE = Y_INCREASE.div(TOUCHDOWN.sub(CLIFF)); // m = (y2 - y1) / (x2 - x1)
struct Term {
uint initPercent; // 4 decimals ( 5000 = 0.5% )
uint claimed;
uint max;
}
mapping(address => Term) public terms;
mapping(address => address) public walletChange;
constructor( address _cKEEPER, address _KEEPER, address _USDC, address _treasury, address _staking ) {
require( _cKEEPER != address(0) );
cKEEPER = _cKEEPER;
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _USDC != address(0) );
USDC = _USDC;
require( _treasury != address(0) );
treasury = _treasury;
require( _staking != address(0) );
staking = _staking;
}
function setStaking( address _staking ) external onlyOwner() {
require( _staking != address(0) );
staking = _staking;
}
// Sets terms for a new wallet
function setTerms(address _vester, uint _amountCanClaim, uint _rate ) external onlyOwner() returns ( bool ) {
terms[_vester].max = _amountCanClaim;
terms[_vester].initPercent = _rate;
return true;
}
// Sets terms for multiple wallets
function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) {
for (uint i=0; i < _vesters.length; i++) {
terms[_vesters[i]].max = _amountCanClaims[i];
terms[_vesters[i]].initPercent = _rates[i];
}
return true;
}
// Allows wallet to redeem cKEEPER for KEEPER
function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) {
Term memory info = terms[ msg.sender ];
require( redeemable( info ) >= _amount, 'Not enough vested' );
require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' );
uint usdcAmount = _amount.div(1e12);
IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount );
IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount );
IERC20( USDC ).approve( treasury, usdcAmount );
uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 );
terms[ msg.sender ].claimed = info.claimed.add( _amount );
if ( _stake ) {
IERC20( KEEPER ).approve( staking, KEEPERToSend );
IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap );
} else {
IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend );
}
return true;
}
// Allows wallet owner to transfer rights to a new address
function pushWalletChange( address _newWallet ) external returns ( bool ) {
require( terms[ msg.sender ].initPercent != 0 );
walletChange[ msg.sender ] = _newWallet;
return true;
}
// Allows wallet to pull rights from an old address
function pullWalletChange( address _oldWallet ) external returns ( bool ) {
require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" );
walletChange[ _oldWallet ] = address(0);
terms[ msg.sender ] = terms[ _oldWallet ];
delete terms[ _oldWallet ];
return true;
}
// Amount a wallet can redeem based on current supply
function redeemableFor( address _vester ) public view returns (uint) {
return redeemable( terms[ _vester ]);
}
function redeemable( Term memory _info ) internal view returns ( uint ) {
if ( _info.initPercent == 0 ) {
return 0;
}
uint keeperSupply = IERC20( KEEPER ).totalSupply();
if (keeperSupply < CLIFF) {
return 0;
} else if (keeperSupply > TOUCHDOWN) {
keeperSupply = TOUCHDOWN;
}
uint percent = Y_INCREASE.mul(keeperSupply.sub(CLIFF)).div(TOUCHDOWN.sub(CLIFF)).add(_info.initPercent);
return ( keeperSupply.mul( percent ).mul( 1000 ) ).sub( _info.claimed );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IStaking.sol";
contract aKeeperStake2 is Ownable {
using SafeMath for uint256;
IERC20 public aKEEPER;
IERC20 public KEEPER;
address public staking;
mapping( address => uint ) public depositInfo;
uint public depositDeadline;
uint public withdrawStart;
uint public withdrawDeadline;
constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) {
require( _aKEEPER != address(0) );
aKEEPER = IERC20(_aKEEPER);
depositDeadline = _depositDeadline;
withdrawStart = _withdrawStart;
withdrawDeadline = _withdrawDeadline;
}
function setDepositDeadline(uint _depositDeadline) external onlyOwner() {
depositDeadline = _depositDeadline;
}
function setWithdrawStart(uint _withdrawStart) external onlyOwner() {
withdrawStart = _withdrawStart;
}
function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() {
withdrawDeadline = _withdrawDeadline;
}
function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() {
KEEPER = IERC20(_KEEPER);
staking = _staking;
}
function depositaKeeper(uint amount) external {
require(block.timestamp < depositDeadline, "Deadline passed.");
aKEEPER.transferFrom(msg.sender, address(this), amount);
depositInfo[msg.sender] = depositInfo[msg.sender].add(amount);
}
// function withdrawaKeeper() external {
// require(block.timestamp > withdrawStart, "Not started.");
// uint amount = depositInfo[msg.sender].mul(110).div(100);
// require(amount > 0, "No deposit present.");
// delete depositInfo[msg.sender];
// aKEEPER.transfer(msg.sender, amount);
// }
function migrate() external {
require(block.timestamp > withdrawStart, "Not started.");
require( address(KEEPER) != address(0) );
uint amount = depositInfo[msg.sender].mul(110).div(100);
require(amount > 0, "No deposit present.");
delete depositInfo[msg.sender];
KEEPER.transfer(msg.sender, amount);
}
function migrateTrove(bool _wrap) external {
require(block.timestamp > withdrawStart, "Not started.");
require( staking != address(0) );
uint amount = depositInfo[msg.sender].mul(110).div(100);
require(amount > 0, "No deposit present.");
delete depositInfo[msg.sender];
KEEPER.approve( staking, amount );
IStaking( staking ).stake( amount, msg.sender, _wrap );
}
function withdrawAll() external onlyOwner() {
require(block.timestamp > withdrawDeadline, "Deadline not yet passed.");
uint256 Keeperamount = KEEPER.balanceOf(address(this));
KEEPER.transfer(msg.sender, Keeperamount);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IStaking.sol";
contract aKeeperStake is Ownable {
using SafeMath for uint256;
IERC20 public aKEEPER;
IERC20 public KEEPER;
address public staking;
mapping( address => uint ) public depositInfo;
uint public depositDeadline;
uint public withdrawStart;
uint public withdrawDeadline;
constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) {
require( _aKEEPER != address(0) );
aKEEPER = IERC20(_aKEEPER);
depositDeadline = _depositDeadline;
withdrawStart = _withdrawStart;
withdrawDeadline = _withdrawDeadline;
}
function setDepositDeadline(uint _depositDeadline) external onlyOwner() {
depositDeadline = _depositDeadline;
}
function setWithdrawStart(uint _withdrawStart) external onlyOwner() {
withdrawStart = _withdrawStart;
}
function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() {
withdrawDeadline = _withdrawDeadline;
}
function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() {
KEEPER = IERC20(_KEEPER);
staking = _staking;
}
function depositaKeeper(uint amount) external {
require(block.timestamp < depositDeadline, "Deadline passed.");
aKEEPER.transferFrom(msg.sender, address(this), amount);
depositInfo[msg.sender] = depositInfo[msg.sender].add(amount);
}
function withdrawaKeeper() external {
require(block.timestamp > withdrawStart, "Not started.");
uint amount = depositInfo[msg.sender].mul(125).div(100);
require(amount > 0, "No deposit present.");
delete depositInfo[msg.sender];
aKEEPER.transfer(msg.sender, amount);
}
function migrate() external {
require( address(KEEPER) != address(0) );
uint amount = depositInfo[msg.sender].mul(125).div(100);
require(amount > 0, "No deposit present.");
delete depositInfo[msg.sender];
KEEPER.transfer(msg.sender, amount);
}
function migrateTrove(bool _wrap) external {
require( staking != address(0) );
uint amount = depositInfo[msg.sender].mul(125).div(100);
require(amount > 0, "No deposit present.");
delete depositInfo[msg.sender];
KEEPER.approve( staking, amount );
IStaking( staking ).stake( amount, msg.sender, _wrap );
}
function withdrawAll() external onlyOwner() {
require(block.timestamp > withdrawDeadline, "Deadline not yet passed.");
uint256 Keeperamount = KEEPER.balanceOf(address(this));
KEEPER.transfer(msg.sender, Keeperamount);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IStaking.sol";
contract oldaKeeperRedeem is Ownable {
using SafeMath for uint256;
IERC20 public KEEPER;
IERC20 public aKEEPER;
address public staking;
event KeeperRedeemed(address tokenOwner, uint256 amount);
event TroveRedeemed(address tokenOwner, uint256 amount);
constructor(address _KEEPER, address _aKEEPER, address _staking) {
require( _KEEPER != address(0) );
require( _aKEEPER != address(0) );
require( _staking != address(0) );
KEEPER = IERC20(_KEEPER);
aKEEPER = IERC20(_aKEEPER);
staking = _staking;
}
function setStaking(address _staking) external onlyOwner() {
require( _staking != address(0) );
staking = _staking;
}
function migrate(uint256 amount) public {
require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance");
aKEEPER.transferFrom(msg.sender, address(this), amount);
KEEPER.transfer(msg.sender, amount);
emit KeeperRedeemed(msg.sender, amount);
}
function migrateTrove(uint256 amount, bool _wrap) public {
require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance");
aKEEPER.transferFrom(msg.sender, address(this), amount);
IERC20( KEEPER ).approve( staking, amount );
IStaking( staking ).stake( amount, msg.sender, _wrap );
emit TroveRedeemed(msg.sender, amount);
}
function withdraw() external onlyOwner() {
uint256 amount = KEEPER.balanceOf(address(this));
KEEPER.transfer(msg.sender, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/AggregateV3Interface.sol";
contract aKeeperPresale is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
IERC20 public aKEEPER;
address public USDC;
address public USDT;
address public DAI;
address public wBTC;
address public gnosisSafe;
mapping( address => uint ) public amountInfo;
uint deadline;
AggregatorV3Interface internal ethPriceFeed;
AggregatorV3Interface internal btcPriceFeed;
event aKeeperRedeemed(address tokenOwner, uint amount);
constructor(address _aKEEPER, address _USDC, address _USDT, address _DAI, address _wBTC, address _ethFeed, address _btcFeed, address _gnosisSafe, uint _deadline) {
require( _aKEEPER != address(0) );
require( _USDC != address(0) );
require( _USDT != address(0) );
require( _DAI != address(0) );
require( _wBTC != address(0) );
require( _ethFeed != address(0) );
require( _btcFeed != address(0) );
aKEEPER = IERC20(_aKEEPER);
USDC = _USDC;
USDT = _USDT;
DAI = _DAI;
wBTC = _wBTC;
gnosisSafe = _gnosisSafe;
deadline = _deadline;
ethPriceFeed = AggregatorV3Interface( _ethFeed );
btcPriceFeed = AggregatorV3Interface( _btcFeed );
}
function setDeadline(uint _deadline) external onlyOwner() {
deadline = _deadline;
}
function ethAssetPrice() public view returns (int) {
( , int price, , , ) = ethPriceFeed.latestRoundData();
return price;
}
function btcAssetPrice() public view returns (int) {
( , int price, , , ) = btcPriceFeed.latestRoundData();
return price;
}
function maxAmount() internal pure returns (uint) {
return 100000000000;
}
function getTokens(address principle, uint amount) external {
require(block.timestamp < deadline, "Deadline has passed.");
require(principle == USDC || principle == USDT || principle == DAI || principle == wBTC, "Token is not acceptable.");
require(IERC20(principle).balanceOf(msg.sender) >= amount, "Not enough token amount.");
// Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100
uint aKeeperAmount;
if (principle == DAI) {
aKeeperAmount = amount.div(1e11);
}
else if (principle == wBTC) {
aKeeperAmount = amount.mul(uint(btcAssetPrice())).div(1e9);
}
else {
aKeeperAmount = amount.mul(1e1);
}
require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens.");
IERC20(principle).safeTransferFrom(msg.sender, gnosisSafe, amount);
aKEEPER.transfer(msg.sender, aKeeperAmount);
amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount);
emit aKeeperRedeemed(msg.sender, aKeeperAmount);
}
function getTokensEth() external payable {
require(block.timestamp < deadline, "Deadline has passed.");
uint amount = msg.value;
// Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100
uint aKeeperAmount = amount.mul(uint(ethAssetPrice())).div(1e19);
require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens.");
safeTransferETH(gnosisSafe, amount);
aKEEPER.transfer(msg.sender, aKeeperAmount);
amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount);
emit aKeeperRedeemed(msg.sender, aKeeperAmount);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
function withdraw() external onlyOwner() {
uint256 amount = aKEEPER.balanceOf(address(this));
aKEEPER.transfer(msg.sender, amount);
}
function withdrawEth() external onlyOwner() {
safeTransferETH(gnosisSafe, address(this).balance);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/IWETH9.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IStaking.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract EthBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable DAO; // receives profit share from bond
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint32 vestingTerm; // in seconds
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
uint payout; // KEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in blocks) between adjustments
uint32 lastTime; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _staking != address(0) );
staking = _staking;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _maxDebt, uint _initialDebt) external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
decayDebt();
require( totalDebt == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 2
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 3
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
require( msg.value == 0 || _amount == msg.value, "Amount should be equal to ETH transferred");
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
if (address(this).balance >= _amount) {
// pay with WETH9
IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay
IWETH9(principle).transfer(treasury, _amount);
} else {
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
}
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
refundETH(); //refund user if needed
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, _wrap, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
IERC20( KEEPER ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient, _wrap );
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (int) {
( , int price, , , ) = priceFeed.latestRoundData();
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 );
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != KEEPER );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
function refundETH() internal {
if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance);
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract aKeeperAirdrop is Ownable {
using SafeMath for uint;
IERC20 public aKEEPER;
IERC20 public USDC;
address public gnosisSafe;
constructor(address _aKEEPER, address _USDC, address _gnosisSafe) {
require( _aKEEPER != address(0) );
require( _USDC != address(0) );
aKEEPER = IERC20(_aKEEPER);
USDC = IERC20(_USDC);
gnosisSafe = _gnosisSafe;
}
receive() external payable { }
function airdropTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() {
for (uint i=0; i < _recipients.length; i++) {
aKEEPER.transfer(_recipients[i], _amounts[i]);
}
}
function refundUsdcTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() {
for (uint i=0; i < _recipients.length; i++) {
USDC.transfer(_recipients[i], _amounts[i]);
}
}
function refundEth(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() {
for (uint i=0; i < _recipients.length; i++) {
safeTransferETH(_recipients[i], _amounts[i]);
}
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
function withdraw() external onlyOwner() {
uint256 amount = aKEEPER.balanceOf(address(this));
aKEEPER.transfer(msg.sender, amount);
}
function withdrawUsdc() external onlyOwner() {
uint256 amount = USDC.balanceOf(address(this));
USDC.transfer(gnosisSafe, amount);
}
function withdrawEth() external onlyOwner() {
safeTransferETH(gnosisSafe, address(this).balance);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/ILPCalculator.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IKeplerERC20.sol";
import "./interfaces/ISPV.sol";
import "./interfaces/IStaking.sol";
contract Treasury is Ownable {
using SafeERC20 for IERC20Extended;
using SafeMath for uint;
event Deposit( address indexed token, uint amount, uint value );
event DepositEth( uint amount, uint value );
event Sell( address indexed token, uint indexed amount, uint indexed price );
event SellEth( uint indexed amount, uint indexed price );
event ReservesWithdrawn( address indexed caller, address indexed token, uint amount );
event ReservesUpdated( uint indexed totalReserves );
event ReservesAudited( uint indexed totalReserves );
event ChangeActivated( MANAGING indexed managing, address activated, bool result );
event SPVUpdated( address indexed spv );
enum MANAGING { RESERVETOKEN, LIQUIDITYTOKEN, VARIABLETOKEN }
struct PriceFeed {
address feed;
uint decimals;
}
IKeplerERC20 immutable KEEPER;
uint public constant keeperDecimals = 9;
uint public immutable priceAdjust; // 4 decimals. 1000 = 0.1
address[] public reserveTokens;
mapping( address => bool ) public isReserveToken;
address[] public variableTokens;
mapping( address => bool ) public isVariableToken;
address[] public liquidityTokens;
mapping( address => bool ) public isLiquidityToken;
mapping( address => address ) public lpCalculator; // bond calculator for liquidity token
mapping( address => PriceFeed ) public priceFeeds; // price feeds for variable token
uint public totalReserves;
uint public spvDebt;
uint public daoDebt;
uint public ownerDebt;
uint public reserveLastAudited;
AggregatorV3Interface internal ethPriceFeed;
address public staking;
address public vesting;
address public SPV;
address public immutable DAO;
uint public daoRatio; // 4 decimals. 1000 = 0.1
uint public spvRatio; // 4 decimals. 7000 = 0.7
uint public vestingRatio; // 4 decimals. 1000 = 0.1
uint public stakeRatio; // 4 decimals. 9000 = 0.9
uint public lcv; // 4 decimals. 1000 = 0.1
uint public keeperSold;
uint public initPrice; // To deposit initial reserves when price is undefined (Keeper supply = 0)
constructor (address _KEEPER, address _USDC, address _USDT, address _DAI, address _DAO, address _vesting, address _ethPriceFeed, uint _priceAdjust, uint _initPrice) {
require( _KEEPER != address(0) );
KEEPER = IKeplerERC20(_KEEPER);
require( _DAO != address(0) );
DAO = _DAO;
require( _vesting != address(0) );
vesting = _vesting;
isReserveToken[ _USDC] = true;
reserveTokens.push( _USDC );
isReserveToken[ _USDT] = true;
reserveTokens.push( _USDT );
isReserveToken[ _DAI ] = true;
reserveTokens.push( _DAI );
ethPriceFeed = AggregatorV3Interface( _ethPriceFeed );
priceAdjust = _priceAdjust;
initPrice = _initPrice;
}
function treasuryInitialized() external onlyOwner() {
initPrice = 0;
}
function setSPV(address _SPV) external onlyOwner() {
require( _SPV != address(0), "Cannot be 0");
SPV = _SPV;
emit SPVUpdated( SPV );
}
function setVesting(address _vesting) external onlyOwner() {
require( _vesting != address(0), "Cannot be 0");
vesting = _vesting;
}
function setStaking(address _staking) external onlyOwner() {
require( _staking != address(0), "Cannot be 0");
staking = _staking;
}
function setLcv(uint _lcv) external onlyOwner() {
require( lcv == 0 || _lcv <= lcv.mul(3).div(2), "LCV cannot change sharp" );
lcv = _lcv;
}
function setTreasuryRatio(uint _daoRatio, uint _spvRatio, uint _vestingRatio, uint _stakeRatio) external onlyOwner() {
require( _daoRatio <= 1000, "DAO more than 10%" );
require( _spvRatio <= 7000, "SPV more than 70%" );
require( _vestingRatio <= 2000, "Vesting more than 20%" );
require( _stakeRatio >= 1000 && _stakeRatio <= 10000, "Stake ratio error" );
daoRatio = _daoRatio;
spvRatio = _spvRatio;
vestingRatio = _vestingRatio;
stakeRatio = _stakeRatio;
}
function getPremium(uint _price) public view returns (uint) {
return _price.mul( lcv ).mul( keeperSold ).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ).div( 1e4 );
}
function getPrice() public view returns ( uint ) {
if (initPrice != 0) {
return initPrice;
} else {
return totalReserves.add(ownerDebt).add( ISPV(SPV).totalValue() ).add( priceAdjust ).mul(10 ** keeperDecimals).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) );
}
}
function ethAssetPrice() public view returns (uint) {
( , int price, , , ) = ethPriceFeed.latestRoundData();
return uint(price).mul( 10 ** keeperDecimals ).div( 1e8 );
}
function variableAssetPrice(address _address, uint _decimals) public view returns (uint) {
( , int price, , , ) = AggregatorV3Interface(_address).latestRoundData();
return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** _decimals );
}
function EthToUSD( uint _amount ) internal view returns ( uint ) {
return _amount.mul( ethAssetPrice() ).div( 1e18 );
}
function auditTotalReserves() public {
uint reserves;
for( uint i = 0; i < reserveTokens.length; i++ ) {
reserves = reserves.add (
valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) )
);
}
for( uint i = 0; i < liquidityTokens.length; i++ ) {
reserves = reserves.add (
valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) )
);
}
for( uint i = 0; i < variableTokens.length; i++ ) {
reserves = reserves.add (
valueOfToken( variableTokens[ i ], IERC20Extended( variableTokens[ i ] ).balanceOf( address(this) ) )
);
}
reserves = reserves.add( EthToUSD(address(this).balance) );
totalReserves = reserves;
reserveLastAudited = block.timestamp;
emit ReservesUpdated( reserves );
emit ReservesAudited( reserves );
}
/**
@notice allow depositing an asset for KEEPER
@param _amount uint
@param _token address
@return send_ uint
*/
function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) {
require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" );
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
// uint daoAmount = _amount.mul(daoRatio).div(1e4);
// IERC20Extended( _token ).safeTransfer( DAO, daoAmount );
uint value = valueOfToken(_token, _amount);
// uint daoValue = value.mul(daoRatio).div(1e4);
// mint KEEPER needed and store amount of rewards for distribution
totalReserves = totalReserves.add( value );
send_ = sendOrStake(msg.sender, value, _stake);
emit ReservesUpdated( totalReserves );
emit Deposit( _token, _amount, value );
}
function depositEth( uint _amount, bool _stake ) external payable returns ( uint send_ ) {
require( _amount == msg.value, "Amount should be equal to ETH transferred");
// uint daoAmount = _amount.mul(daoRatio).div(1e4);
// safeTransferETH(DAO, daoAmount);
uint value = EthToUSD( _amount );
// uint daoValue = value.mul(daoRatio).div(1e4);
// mint KEEPER needed and store amount of rewards for distribution
totalReserves = totalReserves.add( value );
send_ = sendOrStake(msg.sender, value, _stake);
emit ReservesUpdated( totalReserves );
emit DepositEth( _amount, value );
}
function sendOrStake(address _recipient, uint _value, bool _stake) internal returns (uint send_) {
send_ = _value.mul( 10 ** keeperDecimals ).div( getPrice() );
if ( _stake ) {
KEEPER.mint( address(this), send_ );
KEEPER.approve( staking, send_ );
IStaking( staking ).stake( send_, _recipient, false );
} else {
KEEPER.mint( _recipient, send_ );
}
uint vestingAmount = send_.mul(vestingRatio).div(1e4);
KEEPER.mint( vesting, vestingAmount );
}
/**
@notice allow to burn KEEPER for reserves
@param _amount uint of keeper
@param _token address
*/
function sell( uint _amount, address _token ) external {
require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
(uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount);
uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) );
uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals );
uint tokenAmount = reserveLoss.mul( 10 ** IERC20Extended( _token ).decimals() ).div( 10 ** keeperDecimals );
totalReserves = totalReserves.sub( reserveLoss );
emit ReservesUpdated( totalReserves );
uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice);
uint daoAmount = tokenAmount.sub(sellAmount);
IERC20Extended(_token).safeTransfer(msg.sender, sellAmount);
IERC20Extended(_token).safeTransfer(DAO, daoAmount);
emit Sell( _token, _amount, sellPrice );
}
function sellEth( uint _amount ) external {
(uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount);
uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) );
uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals );
uint tokenAmount = reserveLoss.mul(10 ** 18).div( ethAssetPrice() );
totalReserves = totalReserves.sub( reserveLoss );
emit ReservesUpdated( totalReserves );
uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice);
uint daoAmount = tokenAmount.sub(sellAmount);
safeTransferETH(msg.sender, sellAmount);
safeTransferETH(DAO, daoAmount);
emit SellEth( _amount, sellPrice );
}
function sellKeeperBurn(address _sender, uint _amount) internal returns (uint price, uint premium, uint sellPrice) {
price = getPrice();
premium = getPremium(price);
sellPrice = price.sub(premium);
KEEPER.burnFrom( _sender, _amount );
keeperSold = keeperSold.add( _amount );
uint stakeRewards = _amount.mul(stakeRatio).mul(premium).div(price).div(1e4);
KEEPER.mint( address(this), stakeRewards );
KEEPER.approve( staking, stakeRewards );
IStaking( staking ).addRebaseReward( stakeRewards );
}
function unstakeMint(uint _amount) external {
require( msg.sender == staking, "Not allowed." );
KEEPER.mint(msg.sender, _amount);
}
function initDeposit( address _token, uint _amount ) external payable onlyOwner() {
require( initPrice != 0, "Already initialized" );
uint value;
if ( _token == address(0) && msg.value != 0 ) {
require( _amount == msg.value, "Amount mismatch" );
value = EthToUSD( _amount );
} else {
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
value = valueOfToken(_token, _amount);
}
totalReserves = totalReserves.add( value );
uint send_ = value.mul( 10 ** keeperDecimals ).div( getPrice() );
KEEPER.mint( msg.sender, send_ );
}
/**
@notice allow owner multisig to withdraw assets on debt (for safe investments)
@param _token address
@param _amount uint
*/
function incurDebt( address _token, uint _amount, bool isEth ) external onlyOwner() {
uint value;
if ( _token == address(0) && isEth ) {
safeTransferETH(msg.sender, _amount);
value = EthToUSD( _amount );
} else {
IERC20Extended( _token ).safeTransfer( msg.sender, _amount );
value = valueOfToken(_token, _amount);
}
totalReserves = totalReserves.sub( value );
ownerDebt = ownerDebt.add(value);
emit ReservesUpdated( totalReserves );
emit ReservesWithdrawn( msg.sender, _token, _amount );
}
function repayDebt( address _token, uint _amount, bool isEth ) external payable onlyOwner() {
uint value;
if ( isEth ) {
require( msg.value == _amount, "Amount mismatch" );
value = EthToUSD( _amount );
} else {
require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" );
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
value = valueOfToken(_token, _amount);
}
totalReserves = totalReserves.add( value );
if ( value > ownerDebt ) {
uint daoProfit = _amount.mul( daoRatio ).mul( value.sub(ownerDebt) ).div( value ).div(1e4);
if ( isEth ) {
safeTransferETH( DAO, daoProfit );
} else {
IERC20Extended( _token ).safeTransfer( DAO, daoProfit );
}
value = ownerDebt;
}
ownerDebt = ownerDebt.sub(value);
emit ReservesUpdated( totalReserves );
}
function SPVDeposit( address _token, uint _amount ) external {
require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" );
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
uint value = valueOfToken(_token, _amount);
totalReserves = totalReserves.add( value );
if ( value > spvDebt ) {
value = spvDebt;
}
spvDebt = spvDebt.sub(value);
emit ReservesUpdated( totalReserves );
}
function SPVWithdraw( address _token, uint _amount ) external {
require( msg.sender == SPV, "Only SPV" );
address SPVWallet = ISPV( SPV ).SPVWallet();
uint value = valueOfToken(_token, _amount);
uint totalValue = totalReserves.add( ISPV(SPV).totalValue() ).add( ownerDebt );
require( spvDebt.add(value) < totalValue.mul(spvRatio).div(1e4), "Debt exceeded" );
spvDebt = spvDebt.add(value);
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20Extended( _token ).safeTransfer( SPVWallet, _amount );
}
function DAOWithdraw( address _token, uint _amount, bool isEth ) external {
require( msg.sender == DAO, "Only DAO Allowed" );
uint value;
if ( _token == address(0) && isEth ) {
value = EthToUSD( _amount );
} else {
value = valueOfToken(_token, _amount);
}
uint daoProfit = ISPV( SPV ).totalProfit().mul( daoRatio ).div(1e4);
require( daoDebt.add(value) <= daoProfit, "Too much" );
if ( _token == address(0) && isEth ) {
safeTransferETH(DAO, _amount);
} else {
IERC20Extended( _token ).safeTransfer( DAO, _amount );
}
totalReserves = totalReserves.sub( value );
daoDebt = daoDebt.add(value);
emit ReservesUpdated( totalReserves );
emit ReservesWithdrawn( DAO, _token, _amount );
}
/**
@notice returns KEEPER valuation of asset
@param _token address
@param _amount uint
@return value_ uint
*/
function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) {
if ( isReserveToken[ _token ] ) {
// convert amount to match KEEPER decimals
value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() );
} else if ( isLiquidityToken[ _token ] ) {
value_ = ILPCalculator( lpCalculator[ _token ] ).valuationUSD( _token, _amount );
} else if ( isVariableToken[ _token ] ) {
value_ = _amount.mul(variableAssetPrice( priceFeeds[_token].feed, priceFeeds[_token].decimals )).div( 10 ** IERC20Extended( _token ).decimals() );
}
}
/**
@notice verify queue then set boolean in mapping
@param _managing MANAGING
@param _address address
@param _calculatorFeed address
@return bool
*/
function toggle( MANAGING _managing, address _address, address _calculatorFeed, uint decimals ) external onlyOwner() returns ( bool ) {
require( _address != address(0) );
bool result;
if ( _managing == MANAGING.RESERVETOKEN ) { // 0
if( !listContains( reserveTokens, _address ) ) {
reserveTokens.push( _address );
}
result = !isReserveToken[ _address ];
isReserveToken[ _address ] = result;
} else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 1
if( !listContains( liquidityTokens, _address ) ) {
liquidityTokens.push( _address );
}
result = !isLiquidityToken[ _address ];
isLiquidityToken[ _address ] = result;
lpCalculator[ _address ] = _calculatorFeed;
} else if ( _managing == MANAGING.VARIABLETOKEN ) { // 2
if( !listContains( variableTokens, _address ) ) {
variableTokens.push( _address );
}
result = !isVariableToken[ _address ];
isVariableToken[ _address ] = result;
priceFeeds[ _address ] = PriceFeed({
feed: _calculatorFeed,
decimals: decimals
});
} else return false;
emit ChangeActivated( _managing, _address, result );
return true;
}
/**
@notice checks array to ensure against duplicate
@param _list address[]
@param _token address
@return bool
*/
function listContains( address[] storage _list, address _token ) internal view returns ( bool ) {
for( uint i = 0; i < _list.length; i++ ) {
if( _list[ i ] == _token ) {
return true;
}
}
return false;
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface ILPCalculator {
function valuationUSD( address _token, uint _amount ) external view returns ( uint );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Extended is IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IKeplerERC20 is IERC20 {
function decimals() external view returns (uint8);
function mint(address account_, uint256 ammount_) external;
function burn(uint256 amount_) external;
function burnFrom(address account_, uint256 amount_) external;
function vault() external returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface ISPV {
function SPVWallet() external view returns ( address );
function totalValue() external view returns ( uint );
function totalProfit() external view returns ( uint );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IStaking {
function stake(uint _amount, address _recipient, bool _wrap) external;
function addRebaseReward( uint _amount ) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IStaking.sol";
contract aKeeperRedeem is Ownable {
using SafeMath for uint256;
IERC20 public KEEPER;
IERC20 public aKEEPER;
address public staking;
uint public multiplier; // multiplier is 4 decimals i.e. 1000 = 0.1
event KeeperRedeemed(address tokenOwner, uint256 amount);
constructor(address _aKEEPER, address _KEEPER, address _staking, uint _multiplier) {
require( _aKEEPER != address(0) );
require( _KEEPER != address(0) );
require( _multiplier != 0 );
aKEEPER = IERC20(_aKEEPER);
KEEPER = IERC20(_KEEPER);
staking = _staking;
multiplier = _multiplier;
// reduce gas fees of migrate-stake by pre-approving large amount
KEEPER.approve( staking, 1e25);
}
function migrate(uint256 amount, bool _stake, bool _wrap) public {
aKEEPER.transferFrom(msg.sender, address(this), amount);
uint keeperAmount = amount.mul(multiplier).div(1e4);
if ( _stake && staking != address( 0 ) ) {
IStaking( staking ).stake( keeperAmount, msg.sender, _wrap );
} else {
KEEPER.transfer(msg.sender, keeperAmount);
}
emit KeeperRedeemed(msg.sender, keeperAmount);
}
function withdraw() external onlyOwner() {
uint256 amount = KEEPER.balanceOf(address(this));
KEEPER.transfer(msg.sender, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/AggregateV3Interface.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IKeplerERC20.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IUniswapV2Pair.sol";
contract SPV is Ownable {
using SafeERC20 for IERC20Extended;
using SafeMath for uint;
event TokenAdded( address indexed token, PRICETYPE indexed priceType, uint indexed price );
event TokenPriceUpdate( address indexed token, uint indexed price );
event TokenPriceTypeUpdate( address indexed token, PRICETYPE indexed priceType );
event TokenRemoved( address indexed token );
event ValueAudited( uint indexed total );
event TreasuryWithdrawn( address indexed token, uint indexed amount );
event TreasuryReturned( address indexed token, uint indexed amount );
uint public constant keeperDecimals = 9;
enum PRICETYPE { STABLE, CHAINLINK, UNISWAP, MANUAL }
struct TokenPrice {
address token;
PRICETYPE priceType;
uint price; // At keeper decimals
}
TokenPrice[] public tokens;
struct ChainlinkPriceFeed {
address feed;
uint decimals;
}
mapping( address => ChainlinkPriceFeed ) public chainlinkPriceFeeds;
mapping( address => address ) public uniswapPools; // The other token must be a stablecoin
address public immutable treasury;
address public SPVWallet;
uint public totalValue;
uint public totalProfit;
uint public spvRecordedValue;
uint public recordTime;
uint public profitInterval;
bool public allowUpdate; // False when SPV is transferring funds
constructor (address _treasury, address _USDC, address _USDT, address _DAI, address _SPVWallet, uint _profitInterval) {
require( _treasury != address(0) );
treasury = _treasury;
require( _SPVWallet != address(0) );
SPVWallet = _SPVWallet;
tokens.push(TokenPrice({
token: _USDC,
priceType: PRICETYPE.STABLE,
price: 10 ** keeperDecimals
}));
tokens.push(TokenPrice({
token: _USDT,
priceType: PRICETYPE.STABLE,
price: 10 ** keeperDecimals
}));
tokens.push(TokenPrice({
token: _DAI,
priceType: PRICETYPE.STABLE,
price: 10 ** keeperDecimals
}));
recordTime = block.timestamp;
require( _profitInterval > 0, "Interval cannot be 0" );
profitInterval = _profitInterval;
spvRecordedValue = 0;
allowUpdate = true;
updateTotalValue();
}
function enableUpdates() external onlyOwner() {
allowUpdate = true;
}
function disableUpdates() external onlyOwner() {
allowUpdate = false;
}
function setInterval( uint _profitInterval ) external onlyOwner() {
require( _profitInterval > 0, "Interval cannot be 0" );
profitInterval = _profitInterval;
}
function chainlinkTokenPrice(address _token) public view returns (uint) {
( , int price, , , ) = AggregatorV3Interface( chainlinkPriceFeeds[_token].feed ).latestRoundData();
return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** chainlinkPriceFeeds[_token].decimals );
}
function uniswapTokenPrice(address _token) public view returns (uint) {
address _pair = uniswapPools[_token];
( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
uint reserve;
address reserveToken;
uint tokenAmount;
if ( IUniswapV2Pair( _pair ).token0() == _token ) {
reserveToken = IUniswapV2Pair( _pair ).token1();
reserve = reserve1;
tokenAmount = reserve0;
} else {
reserveToken = IUniswapV2Pair( _pair ).token0();
reserve = reserve0;
tokenAmount = reserve1;
}
return reserve.mul(10 ** keeperDecimals).mul( 10 ** IERC20Extended(_token).decimals() ).div( tokenAmount ).div( 10 ** IERC20Extended(reserveToken).decimals() );
}
function setNewTokenPrice(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) internal returns (uint tokenPrice) {
if (_priceType == PRICETYPE.STABLE) {
tokenPrice = 10 ** keeperDecimals;
} else if (_priceType == PRICETYPE.CHAINLINK) {
chainlinkPriceFeeds[_token] = ChainlinkPriceFeed({
feed: _feedOrPool,
decimals: _decimals
});
tokenPrice = chainlinkTokenPrice(_token);
} else if (_priceType == PRICETYPE.UNISWAP) {
uniswapPools[_token] = _feedOrPool;
tokenPrice = uniswapTokenPrice(_token);
} else if (_priceType == PRICETYPE.MANUAL) {
tokenPrice = _price;
} else {
tokenPrice = 0;
}
}
function addToken(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) external onlyOwner() {
uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price);
require(tokenPrice > 0, "Token price cannot be 0");
tokens.push(TokenPrice({
token: _token,
priceType: _priceType,
price: tokenPrice
}));
updateTotalValue();
emit TokenAdded(_token, _priceType, tokenPrice);
}
function updateTokenPrice( uint _index, address _token, uint _price ) external onlyOwner() {
require( _token == tokens[ _index ].token, "Wrong token" );
require( tokens[ _index ].priceType == PRICETYPE.MANUAL, "Only manual tokens can be updated" );
tokens[ _index ].price = _price;
updateTotalValue();
emit TokenPriceUpdate(_token, _price);
}
function updateTokenPriceType( uint _index, address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price ) external onlyOwner() {
require( _token == tokens[ _index ].token, "Wrong token" );
tokens[ _index ].priceType = _priceType;
uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price);
require(tokenPrice > 0, "Token price cannot be 0");
tokens[ _index ].price = tokenPrice;
updateTotalValue();
emit TokenPriceTypeUpdate(_token, _priceType);
emit TokenPriceUpdate(_token, tokenPrice);
}
function removeToken( uint _index, address _token ) external onlyOwner() {
require( _token == tokens[ _index ].token, "Wrong token" );
tokens[ _index ] = tokens[tokens.length-1];
tokens.pop();
updateTotalValue();
emit TokenRemoved(_token);
}
function getTokenBalance( uint _index ) internal view returns (uint) {
address _token = tokens[ _index ].token;
return IERC20Extended(_token).balanceOf( SPVWallet ).mul(tokens[ _index ].price).div( 10 ** IERC20Extended( _token ).decimals() );
}
function auditTotalValue() external {
if ( allowUpdate ) {
uint newValue;
for ( uint i = 0; i < tokens.length; i++ ) {
PRICETYPE priceType = tokens[i].priceType;
if (priceType == PRICETYPE.CHAINLINK) {
tokens[i].price = chainlinkTokenPrice(tokens[i].token);
} else if (priceType == PRICETYPE.UNISWAP) {
tokens[i].price = uniswapTokenPrice(tokens[i].token);
}
newValue = newValue.add( getTokenBalance(i) );
}
totalValue = newValue;
emit ValueAudited(totalValue);
}
}
function calculateProfits() external {
require( recordTime.add( profitInterval ) <= block.timestamp, "Not yet" );
require( msg.sender == SPVWallet || msg.sender == ITreasury( treasury ).DAO(), "Not allowed" );
recordTime = block.timestamp;
updateTotalValue();
uint currentValue;
uint treasuryDebt = ITreasury( treasury ).spvDebt();
if ( treasuryDebt > totalValue ) {
currentValue = 0;
} else {
currentValue = totalValue.sub(treasuryDebt);
}
if ( currentValue > spvRecordedValue ) {
uint profit = currentValue.sub( spvRecordedValue );
spvRecordedValue = currentValue;
totalProfit = totalProfit.add(profit);
}
}
function treasuryWithdraw( uint _index, address _token, uint _amount ) external {
require( msg.sender == SPVWallet, "Only SPV Wallet allowed" );
require( _token == tokens[ _index ].token, "Wrong token" );
ITreasury( treasury ).SPVWithdraw( _token, _amount );
updateTotalValue();
emit TreasuryWithdrawn( _token, _amount );
}
function returnToTreasury( uint _index, address _token, uint _amount ) external {
require( _token == tokens[ _index ].token, "Wrong token" );
require( msg.sender == SPVWallet, "Only SPV Wallet can return." );
IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20Extended( _token ).approve( treasury, _amount );
ITreasury( treasury ).SPVDeposit( _token, _amount );
updateTotalValue();
emit TreasuryReturned( _token, _amount );
}
function migrateTokens( address newSPV ) external onlyOwner() {
for ( uint i = 0; i < tokens.length; i++ ) {
address _token = tokens[ i ].token;
IERC20Extended(_token).transfer(newSPV, IERC20Extended(_token).balanceOf( address(this) ) );
}
safeTransferETH(newSPV, address(this).balance );
}
function updateTotalValue() internal {
if ( allowUpdate ) {
uint newValue;
for ( uint i = 0; i < tokens.length; i++ ) {
newValue = newValue.add( getTokenBalance(i) );
}
totalValue = newValue;
}
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface ITreasury {
function unstakeMint( uint _amount ) external;
function SPVDeposit( address _token, uint _amount ) external;
function SPVWithdraw( address _token, uint _amount ) external;
function DAO() external view returns ( address );
function spvDebt() external view returns ( uint );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "./IUniswapV2ERC20.sol";
interface IUniswapV2Pair is IUniswapV2ERC20 {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external view returns ( address );
function token1() external view returns ( address );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IUniswapV2ERC20 {
function totalSupply() external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IUniswapV2ERC20.sol";
import "./interfaces/IUniswapV2Pair.sol";
contract LPCalculator {
using SafeMath for uint;
address public immutable KEEPER;
uint public constant keeperDecimals = 9;
constructor ( address _KEEPER ) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
}
function getReserve( address _pair ) public view returns ( address reserveToken, uint reserve ) {
( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) {
reserve = reserve1;
reserveToken = IUniswapV2Pair( _pair ).token1();
} else {
reserve = reserve0;
reserveToken = IUniswapV2Pair( _pair ).token0();
}
}
function valuationUSD( address _pair, uint _amount ) external view returns ( uint ) {
uint totalSupply = IUniswapV2Pair( _pair ).totalSupply();
( address reserveToken, uint reserve ) = getReserve( _pair );
return _amount.mul( reserve ).mul(2).mul( 10 ** keeperDecimals ).div( totalSupply ).div( 10 ** IERC20Extended( reserveToken ).decimals() );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/ITreasury.sol";
contract Staking is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
event Stake( address indexed recipient, uint indexed amount, uint indexed timestamp );
event Unstake( address indexed recipient, uint indexed amount, uint indexed timestamp );
uint public constant keeperDecimals = 9;
IERC20 public immutable KEEPER;
address public immutable treasury;
uint public rate; // 6 decimals. 10000 = 0.01 = 1%
uint public INDEX; // keeperDecimals decimals
uint public keeperRewards;
struct Rebase {
uint rebaseRate; // 6 decimals
uint totalStaked;
uint index;
uint timeOccured;
}
struct Epoch {
uint number;
uint rebaseInterval;
uint nextRebase;
}
Epoch public epoch;
Rebase[] public rebases; // past rebase data
mapping(address => uint) public stakers;
constructor( address _KEEPER, address _treasury, uint _rate, uint _INDEX, uint _rebaseInterval ) {
require( _KEEPER != address(0) );
KEEPER = IERC20(_KEEPER);
require( _treasury != address(0) );
treasury = _treasury;
require( _rate != 0 );
rate = _rate;
require( _INDEX != 0 );
INDEX = _INDEX;
require( _rebaseInterval != 0 );
epoch = Epoch({
number: 1,
rebaseInterval: _rebaseInterval,
nextRebase: block.timestamp.add(_rebaseInterval)
});
}
function setRate( uint _rate ) external onlyOwner() {
require( _rate >= rate.div(2) && _rate <= rate.mul(3).div(2), "Rate change cannot be too sharp." );
rate = _rate;
}
function stake( uint _amount, address _recipient, bool _wrap ) external {
KEEPER.safeTransferFrom( msg.sender, address(this), _amount );
uint _gonsAmount = getGonsAmount( _amount );
stakers[ _recipient ] = stakers[ _recipient ].add( _gonsAmount );
emit Stake( _recipient, _amount, block.timestamp );
rebase();
}
function unstake( uint _amount ) external {
rebase();
require( _amount <= stakerAmount(msg.sender), "Cannot unstake more than possible." );
if ( _amount > KEEPER.balanceOf( address(this) ) ) {
ITreasury(treasury).unstakeMint( _amount.sub(KEEPER.balanceOf( address(this) ) ) );
}
uint gonsAmount = getGonsAmount( _amount );
// Handle math precision error
if ( gonsAmount > stakers[msg.sender] ) {
gonsAmount = stakers[msg.sender];
}
stakers[msg.sender] = stakers[ msg.sender ].sub(gonsAmount);
KEEPER.safeTransfer( msg.sender, _amount );
emit Unstake( msg.sender, _amount, block.timestamp );
}
function rebase() public {
if (epoch.nextRebase <= block.timestamp) {
uint rebasingRate = rebaseRate();
INDEX = INDEX.add( INDEX.mul( rebasingRate ).div(1e6) );
epoch.nextRebase = epoch.nextRebase.add(epoch.rebaseInterval);
epoch.number++;
keeperRewards = 0;
rebases.push( Rebase({
rebaseRate: rebasingRate,
totalStaked: KEEPER.balanceOf( address(this) ),
index: INDEX,
timeOccured: block.timestamp
}) );
}
}
function stakerAmount( address _recipient ) public view returns (uint) {
return getKeeperAmount(stakers[ _recipient ]);
}
function rebaseRate() public view returns (uint) {
uint keeperBalance = KEEPER.balanceOf( address(this) );
if (keeperBalance == 0) {
return rate;
} else {
return rate.add( keeperRewards.mul(1e6).div( KEEPER.balanceOf( address(this) ) ) );
}
}
function addRebaseReward( uint _amount ) external {
KEEPER.safeTransferFrom( msg.sender, address(this), _amount );
keeperRewards = keeperRewards.add( _amount );
}
function getGonsAmount( uint _amount ) internal view returns (uint) {
return _amount.mul(10 ** keeperDecimals).div(INDEX);
}
function getKeeperAmount( uint _gons ) internal view returns (uint) {
return _gons.mul(INDEX).div(10 ** keeperDecimals);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
contract VaultOwned is Ownable {
address internal _vault;
function setVault(address vault_) external onlyOwner() returns (bool) {
_vault = vault_;
return true;
}
function vault() public view returns (address) {
return _vault;
}
modifier onlyVault() {
require(_vault == msg.sender, "VaultOwned: caller is not the Vault");
_;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./types/VaultOwned.sol";
contract MockKeplerERC20 is ERC20, VaultOwned {
using SafeMath for uint256;
constructor() ERC20("Keeper", "KEEPER") {
_setupDecimals(9);
}
function mint(address account_, uint256 amount_) external {
_mint(account_, amount_);
}
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) public virtual {
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(
amount_,
"ERC20: burn amount exceeds allowance"
);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./types/VaultOwned.sol";
contract KeplerERC20 is ERC20, VaultOwned {
using SafeMath for uint256;
constructor() ERC20("Keeper", "KEEPER") {
_setupDecimals(9);
}
function mint(address account_, uint256 amount_) external onlyVault() {
_mint(account_, amount_);
}
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) public virtual {
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(
amount_,
"ERC20: burn amount exceeds allowance"
);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract KeeperVesting is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
IERC20 public immutable KEEPER;
event KeeperRedeemed(address redeemer, uint amount);
struct Term {
uint percent; // 6 decimals % ( 5000 = 0.5% = 0.005 )
uint claimed;
}
mapping(address => Term) public terms;
mapping(address => address) public walletChange;
// uint public totalRedeemable;
// uint public redeemableLastUpdated;
uint public totalRedeemed;
// address public redeemUpdater;
constructor( address _KEEPER ) {
require( _KEEPER != address(0) );
KEEPER = IERC20(_KEEPER);
// redeemUpdater = _redeemUpdater;
// redeemableLastUpdated = block.timestamp;
}
// function setRedeemUpdater(address _redeemUpdater) external onlyOwner() {
// require( _redeemUpdater != address(0) );
// redeemUpdater = _redeemUpdater;
// }
// Sets terms for a new wallet
function setTerms(address _vester, uint _percent ) external onlyOwner() returns ( bool ) {
terms[_vester].percent = _percent;
return true;
}
// Sets terms for multiple wallets
function setTermsMultiple(address[] calldata _vesters, uint[] calldata _percents ) external onlyOwner() returns ( bool ) {
for (uint i=0; i < _vesters.length; i++) {
terms[_vesters[i]].percent = _percents[i];
}
return true;
}
// function updateTotalRedeemable() external {
// require( msg.sender == redeemUpdater, "Only redeem updater can call." );
// uint keeperBalance = KEEPER.balanceOf( address(this) );
// uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000);
// totalRedeemable = totalRedeemable.add(newRedeemable);
// if (totalRedeemable > keeperBalance ) {
// totalRedeemable = keeperBalance;
// }
// redeemableLastUpdated = block.timestamp;
// }
// Allows wallet to redeem KEEPER
function redeem( uint _amount ) external returns ( bool ) {
Term memory info = terms[ msg.sender ];
require( redeemable( info ) >= _amount, 'Not enough vested' );
KEEPER.safeTransfer(msg.sender, _amount);
terms[ msg.sender ].claimed = info.claimed.add( _amount );
totalRedeemed = totalRedeemed.add(_amount);
emit KeeperRedeemed(msg.sender, _amount);
return true;
}
// Allows wallet owner to transfer rights to a new address
function pushWalletChange( address _newWallet ) external returns ( bool ) {
require( terms[ msg.sender ].percent != 0 );
walletChange[ msg.sender ] = _newWallet;
return true;
}
// Allows wallet to pull rights from an old address
function pullWalletChange( address _oldWallet ) external returns ( bool ) {
require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" );
walletChange[ _oldWallet ] = address(0);
terms[ msg.sender ] = terms[ _oldWallet ];
delete terms[ _oldWallet ];
return true;
}
// Amount a wallet can redeem
function redeemableFor( address _vester ) public view returns (uint) {
return redeemable( terms[ _vester ]);
}
function redeemable( Term memory _info ) internal view returns ( uint ) {
uint maxRedeemable = KEEPER.balanceOf( address(this) ).add( totalRedeemed );
if ( maxRedeemable > 1e17 ) {
maxRedeemable = 1e17;
}
uint maxRedeemableUser = maxRedeemable.mul( _info.percent ).div(1e6);
return maxRedeemableUser.sub(_info.claimed);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/access/Ownable.sol";
interface KeeperCompatibleInterface {
function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);
function performUpkeep(bytes calldata performData) external;
}
interface IStaking {
function rebase() external;
}
interface ITreasury {
function auditTotalReserves() external;
}
interface ISPV {
function auditTotalValue() external;
}
contract DailyUpkeep is KeeperCompatibleInterface, Ownable {
/**
* Use an interval in seconds and a timestamp to slow execution of Upkeep
*/
uint public immutable interval;
uint public nextTimeStamp;
address public staking;
address public treasury;
address public spv;
constructor(address _staking, address _treasury, address _spv, uint _nextTimeStamp, uint _interval) {
staking = _staking;
treasury = _treasury;
spv = _spv;
nextTimeStamp = _nextTimeStamp;
interval = _interval;
}
function setStaking(address _staking) external onlyOwner() {
staking = _staking;
}
function setTreasury(address _treasury) external onlyOwner() {
treasury = _treasury;
}
function setSPV(address _spv) external onlyOwner() {
spv = _spv;
}
function checkUpkeep(bytes calldata /* checkData */) external override returns (bool upkeepNeeded, bytes memory /* performData */) {
upkeepNeeded = block.timestamp > nextTimeStamp;
}
function performUpkeep(bytes calldata /* performData */) external override {
if (staking != address(0)) {
IStaking(staking).rebase();
}
if (treasury != address(0)) {
ITreasury(treasury).auditTotalReserves();
}
if (spv != address(0)) {
ISPV(spv).auditTotalValue();
}
nextTimeStamp = nextTimeStamp + interval;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
contract VaultOwned is Ownable {
address internal _vault;
function setVault(address vault_) external onlyOwner() returns (bool) {
_vault = vault_;
return true;
}
function vault() public view returns (address) {
return _vault;
}
modifier onlyVault() {
require(_vault == msg.sender, "VaultOwned: caller is not the Vault");
_;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./types/VaultOwned.sol";
contract oldMockKeplerERC20 is ERC20, VaultOwned {
using SafeMath for uint256;
constructor() ERC20("Keeper", "KEEPER") {
_setupDecimals(9);
}
function mint(address account_, uint256 amount_) external {
_mint(account_, amount_);
}
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) public virtual {
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(
amount_,
"ERC20: burn amount exceeds allowance"
);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./types/VaultOwned.sol";
contract oldKeplerERC20 is ERC20, VaultOwned {
using SafeMath for uint256;
constructor() ERC20("Keeper", "KEEPER") {
_setupDecimals(9);
}
function mint(address account_, uint256 amount_) external onlyVault() {
_mint(account_, amount_);
}
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) public virtual {
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(
amount_,
"ERC20: burn amount exceeds allowance"
);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract iKeeperIndexCalculator is Ownable {
using SafeMath for uint;
event AssetIndexAdded( uint indexed deposit, uint indexed price, address indexed token );
event IndexUpdated( uint indexed fromIndex, uint indexed toIndex, uint oldPrice, uint newPrice );
event DepositUpdated( uint indexed fromDeposit, uint indexed toDeposit );
event AssetIndexWithdrawn( uint indexed deposit, uint price, uint indexed index, address indexed token );
struct AssetIndex {
uint deposit; // In USD
uint price; // 6 decimals, in USD
uint index; // 9 decimals, starts with 1000000000
address token; // Token address of the asset
}
AssetIndex[] public indices;
uint public netIndex;
constructor(uint _netIndex) {
require( _netIndex != 0, "Index cannot be 0" );
netIndex = _netIndex;
}
function calculateIndex() public {
uint indexProduct = 0;
uint totalDeposit = 0;
for (uint i=0; i < indices.length; i++) {
uint deposit = indices[i].deposit;
totalDeposit = totalDeposit.add(deposit);
indexProduct = indexProduct.add( indices[i].index.mul( deposit ) );
}
netIndex = indexProduct.div(totalDeposit);
}
function addAssetIndex(uint _deposit, uint _price, address _token) external onlyOwner() {
indices.push( AssetIndex({
deposit: _deposit,
price: _price,
index: 1e9,
token: _token
}));
}
function updateIndex(uint _index, address _token, uint _newPrice) external onlyOwner() {
AssetIndex storage assetIndex = indices[ _index ];
require(assetIndex.token == _token, "Wrong index.");
uint changeIndex = _newPrice.mul(1e9).div(assetIndex.price);
uint fromIndex = assetIndex.index;
uint oldPrice = assetIndex.price;
assetIndex.index = fromIndex.mul(changeIndex).div(1e9);
assetIndex.deposit = assetIndex.deposit.mul(changeIndex).div(1e9);
assetIndex.price = _newPrice;
emit IndexUpdated(fromIndex, assetIndex.index, oldPrice, _newPrice);
}
function updateDeposit(uint _index, address _token, uint _amount, bool _add) external onlyOwner() {
require(_token == indices[ _index ].token, "Wrong index.");
uint oldDeposit = indices[ _index ].deposit;
require(_add || oldDeposit >= _amount, "Cannot withdraw more than deposit");
if (!_add) {
indices[ _index ].deposit = oldDeposit.sub(_amount);
} else {
indices[ _index ].deposit = oldDeposit.add(_amount);
}
emit DepositUpdated(oldDeposit, indices[ _index ].deposit);
}
function withdrawAsset(uint _index, address _token) external onlyOwner() {
AssetIndex memory assetIndex = indices[ _index ];
require(_token == assetIndex.token, "Wrong index.");
indices[ _index ] = indices[indices.length-1];
indices.pop();
emit AssetIndexWithdrawn(assetIndex.deposit, assetIndex.price, assetIndex.index, assetIndex.token);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IsKEEPER.sol";
import "./interfaces/IStaking.sol";
// import "./interfaces/IIndexCalculator.sol";
contract iKEEPER is ERC20, Ownable {
using SafeMath for uint;
address public immutable TROVE;
address public immutable staking;
address public indexCalculator;
constructor(address _TROVE, address _staking, address _indexCalculator) ERC20("Invest KEEPER", "iKEEPER") {
require(_TROVE != address(0));
TROVE = _TROVE;
require(_staking != address(0));
staking = _staking;
require(_indexCalculator != address(0));
indexCalculator = _indexCalculator;
}
// function setIndexCalculator( address _indexCalculator ) external onlyOwner() {
// require( _indexCalculator != address(0) );
// indexCalculator = _indexCalculator;
// }
// /**
// @notice get iKEEPER index (9 decimals)
// @return uint
// */
// // function getIndex() public view returns (uint) {
// // return IIndexCalculator(indexCalculator).netIndex();
// // }
// // /**
// // @notice wrap KEEPER
// // @param _amount uint
// // @return uint
// // */
// // function wrapKEEPER( uint _amount ) external returns ( uint ) {
// // IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount );
// // uint value = TROVEToiKEEPER( _amount );
// // _mint( msg.sender, value );
// // return value;
// // }
// /**
// @notice wrap TROVE
// @param _amount uint
// @return uint
// */
// function wrap( uint _amount, address _recipient ) external returns ( uint ) {
// IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount );
// uint value = TROVEToiKEEPER( _amount );
// _mint( _recipient, value );
// return value;
// }
// // /**
// // @notice unwrap KEEPER
// // @param _amount uint
// // @return uint
// // */
// // function unwrapKEEPER( uint _amount ) external returns ( uint ) {
// // _burn( msg.sender, _amount );
// // uint value = iKEEPERToTROVE( _amount );
// // uint keeperBalance = IERC20(KEEPER).balanceOf( address(this) );
// // if (keeperBalance < value ) {
// // uint difference = value.sub(keeperBalance);
// // require(IsKEEPER(TROVE).balanceOf(address(this)) >= difference, "Contract does not have enough TROVE");
// // IsKEEPER(TROVE).approve(staking, difference);
// // IStaking(staking).unstake(difference, false);
// // }
// // IERC20( KEEPER ).transfer( msg.sender, value );
// // return value;
// // }
// /**
// @notice unwrap TROVE
// @param _amount uint
// @return uint
// */
// function unwrap( uint _amount ) external returns ( uint ) {
// _burn( msg.sender, _amount );
// uint value = iKEEPERToTROVE( _amount );
// IsKEEPER( TROVE ).transfer( msg.sender, value );
// return value;
// }
// /**
// @notice converts iKEEPER amount to TROVE
// @param _amount uint
// @return uint
// */
// function iKEEPERToTROVE( uint _amount ) public view returns ( uint ) {
// return _amount.mul( getIndex() ).div( 10 ** decimals() );
// }
// /**
// @notice converts TROVE amount to iKEEPER
// @param _amount uint
// @return uint
// */
// function TROVEToiKEEPER( uint _amount ) public view returns ( uint ) {
// return _amount.mul( 10 ** decimals() ).div( getIndex() );
// }
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IBondCalculator.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IsKEEPER.sol";
import "./interfaces/IwTROVE.sol";
import "./interfaces/IStaking.sol";
import "./interfaces/ITreasury.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/SafeMathExtended.sol";
contract BondStakeDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMathExtended for uint;
using SafeMathExtended for uint32;
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable KEEPER; // intermediate token
address public immutable sKEEPER; // token given as payment for bond
address public immutable wTROVE; // Wrap sKEEPER
address public immutable principle; // token used to create bond
address public immutable treasury; // mints KEEPER when receives principle
address public immutable DAO; // receives profit share from bond
address public immutable bondCalculator; // calculates value of LP tokens
bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different
address public staking; // to auto-stake payout
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint32 public lastDecay; // reference time for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint minimumPrice; // vs principle value
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
uint32 vestingTerm; // in seconds
}
// Info for bond holder
struct Bond {
uint gonsPayout; // sKEEPER remaining to be paid
uint pricePaid; // In DAI, for front end viewing
uint32 vesting; // seconds left to vest
uint32 lastTime; // Last interaction
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint32 buffer; // minimum length (in seconds) between adjustments
uint32 lastTime; // timestamp when last adjustment made
}
constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
require( _sKEEPER != address(0) );
sKEEPER = _sKEEPER;
require( _wTROVE != address(0) );
wTROVE = _wTROVE;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _staking != address(0) );
staking = _staking;
// bondCalculator should be address(0) if not LP bond
bondCalculator = _bondCalculator;
isLiquidityBond = ( _bondCalculator != address(0) );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _fee uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout,
uint _fee, uint _maxDebt, uint _initialDebt)
external onlyOwner() {
require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 129600, "Vesting must be longer than 36 hours" );
require( currentDebt() == 0, "Debt should be 0." );
terms.vestingTerm = uint32(_input);
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.FEE ) { // 2
require( _input <= 10000, "DAO fee cannot exceed payout" );
terms.fee = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 3
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 4
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastTime: uint32(block.timestamp)
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
// function setStaking( address _staking ) external onlyOwner() {
// require( _staking != address(0) );
// staking = _staking;
// }
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOfToken( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// profits are calculated
uint fee = payout.mul( terms.fee ).div( 10000 );
uint profit = value.sub( payout ).sub( fee );
/**
principle is transferred in
approved and
deposited into the treasury, returning (_amount - profit) KEEPER
*/
IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( principle ).approve( address( treasury ), _amount );
ITreasury( treasury ).deposit( _amount, principle, profit );
if ( fee != 0 ) { // fee is transferred to dao
IERC20( KEEPER ).safeTransfer( DAO, fee );
}
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
IERC20( KEEPER ).approve( staking, payout );
IStaking( staking ).stake( payout, address(this), false );
IStaking( staking ).claim( address(this) );
uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout);
// depositor info is stored
bondInfo[ _depositor ] = Bond({
gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ),
vesting: terms.vestingTerm,
lastTime: uint32(block.timestamp),
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _wrap bool
* @return uint
*/
function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout);
emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data
return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
gonsPayout: info.gonsPayout.sub( gonsPayout ),
vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout);
uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout);
emit BondRedeemed( _recipient, _amount, _remainingAmount );
return sendOrWrap( _recipient, _wrap, _amount );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to wrap payout automatically
* @param _wrap bool
* @param _amount uint
* @return uint
*/
function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) {
if ( _wrap ) { // if user wants to wrap
IERC20(sKEEPER).approve( wTROVE, _amount );
uint wrapValue = IwTROVE(wTROVE).wrap( _amount );
IwTROVE(wTROVE).transfer( _recipient, wrapValue );
} else { // if user wants to stake
IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer );
if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) {
adjustment.rate = 0;
}
}
adjustment.lastTime = uint32(block.timestamp);
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = uint32(block.timestamp);
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
if( isLiquidityBond ) {
price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 );
} else {
price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 );
}
}
function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) {
Bond memory info = bondInfo[ _depositor ];
payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout);
vesting = info.vesting;
lastTime = info.lastTime;
pricePaid = info.pricePaid;
}
/**
* @notice calculate current ratio of debt to KEEPER supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( KEEPER ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms for reserve or liquidity bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
if ( isLiquidityBond ) {
return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );
} else {
return debtRatio();
}
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay );
decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = timeSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of KEEPER available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout);
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != KEEPER );
require( _token != sKEEPER );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IERC20Extended.sol";
import "./interfaces/IUniswapV2ERC20.sol";
import "./interfaces/IUniswapV2Pair.sol";
import "./libraries/FixedPoint.sol";
interface IBondingCalculator {
function valuation( address pair_, uint amount_ ) external view returns ( uint _value );
}
contract StandardBondingCalculator is IBondingCalculator {
using FixedPoint for *;
using SafeMath for uint;
using SafeMath for uint112;
address public immutable KEEPER;
constructor( address _KEEPER ) {
require( _KEEPER != address(0) );
KEEPER = _KEEPER;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = a.div(2).add(1);
while (b < c) {
c = b;
b = a.div(b).add(b).div(2);
}
} else if (a != 0) {
c = 1;
}
}
function getKValue( address _pair ) public view returns( uint k_ ) {
uint token0 = IERC20Extended( IUniswapV2Pair( _pair ).token0() ).decimals();
uint token1 = IERC20Extended( IUniswapV2Pair( _pair ).token1() ).decimals();
(uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
uint totalDecimals = token0.add( token1 );
uint pairDecimal = IERC20Extended( _pair ).decimals();
if (totalDecimals < pairDecimal) {
uint decimals = pairDecimal.sub(totalDecimals);
k_ = reserve0.mul(reserve1).mul(10 ** decimals);
}
else {
uint decimals = totalDecimals.sub(pairDecimal);
k_ = reserve0.mul(reserve1).div(10 ** decimals);
}
}
function getTotalValue( address _pair ) public view returns ( uint _value ) {
_value = sqrrt(getKValue( _pair )).mul(2);
}
function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) {
uint totalValue = getTotalValue( _pair );
uint totalSupply = IUniswapV2Pair( _pair ).totalSupply();
_value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 );
}
function markdown( address _pair ) external view returns ( uint ) {
( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
uint reserve;
if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) {
reserve = reserve1;
} else {
reserve = reserve0;
}
return reserve.mul( 2 * ( 10 ** IERC20Extended( KEEPER ).decimals() ) ).div( getTotalValue( _pair ) );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IUniswapV2ERC20 {
function totalSupply() external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "./IUniswapV2ERC20.sol";
interface IUniswapV2Pair is IUniswapV2ERC20 {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external view returns ( address );
function token1() external view returns ( address );
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract aKEEPER is ERC20 {
constructor() ERC20("Alpha Keeper", "aKEEPER") {
_setupDecimals(9);
_mint(msg.sender, 220000000000000);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
} | Sets terms for multiple wallets | function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) {
for (uint i=0; i < _vesters.length; i++) {
terms[_vesters[i]].max = _amountCanClaims[i];
terms[_vesters[i]].initPercent = _rates[i];
}
return true;
}
| 12,150,381 |
./partial_match/1/0x82895fE2945A8B19c5E511E5AA90Da3Aa27331eA/sources/CCPCyborgs.sol | Owner or Project Leader can set the restricted state of an address. Note: Restricted addresses are banned from moving tokens./ | function restrictAddress(address _user, bool _state) external {
require(msg.sender == owner() || msg.sender == projectLeader, "NOoPL");
restricted[_user] = _state;
}
| 2,700,857 |
pragma solidity ^0.4.16;
contract Owned {
address public owner;
address public signer;
function Owned() public {
owner = msg.sender;
signer = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlySigner {
require(msg.sender == signer);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
function transferSignership(address newSigner) public onlyOwner {
signer = newSigner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balances;
// Mapping for allowance
mapping (address => mapping (address => uint256)) public allowed;
// 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 sender, address indexed spender, uint256 value);
function ERC20Token(uint256 _supply, string _name, string _symbol)
public
{
//initial mint
totalSupply = _supply * 10**uint256(decimals);
balances[msg.sender] = totalSupply;
//set variables
name=_name;
symbol=_symbol;
//trigger event
Transfer(0x0, msg.sender, totalSupply);
}
/**
* Returns current tokens total supply
*/
function totalSupply()
public
constant
returns (uint256)
{
return totalSupply;
}
/**
* Get the token balance for account `tokenOwner`
*/
function balanceOf(address _owner)
public
constant
returns (uint256 balance)
{
return balances[_owner];
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on 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)
{
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
//set allowance
allowed[msg.sender][_spender] = _value;
//trigger event
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Show allowance
*/
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value)
internal
returns (bool success)
{
// Do not allow transfer to 0x0 or the token contract itself or from address to itself
require((_to != address(0)) && (_to != address(this)) && (_to != _from));
// Check if the sender has enough
require((_value > 0) && (balances[_from] >= _value));
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* 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)
{
return _transfer(msg.sender, _to, _value);
}
/**
* 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 transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
// Check allowance
require(_value <= allowed[_from][msg.sender]);
//decrement allowance
allowed[_from][msg.sender] -= _value;
//transfer tokens
return _transfer(_from, _to, _value);
}
}
contract MiracleTeleToken is ERC20Token, Owned {
using SafeMath for uint256;
// Mapping for allowance
mapping (address => uint8) public delegations;
mapping (address => uint256) public contributions;
// This generates a public event on the blockchain that will notify clients
event Delegate(address indexed from, address indexed to);
event UnDelegate(address indexed from, address indexed to);
// This generates a public event on the blockchain that will notify clients
event Contribute(address indexed from, uint256 indexed value);
event Reward(address indexed from, uint256 indexed value);
/**
* Initializes contract with initial supply tokens to the creator of the contract
*/
function MiracleTeleToken(uint256 _supply) ERC20Token(_supply, "MiracleTele", "TELE") public {}
/**
* Mint new tokens
*
* @param _value the amount of new tokens
*/
function mint(uint256 _value)
public
onlyOwner
{
// Prevent mine 0 tokens
require(_value > 0);
// Check overflow
balances[owner] = balances[owner].add(_value);
totalSupply = totalSupply.add(_value);
Transfer(address(0), owner, _value);
}
function delegate(uint8 _v, bytes32 _r, bytes32 _s)
public
onlySigner
{
address allowes = ecrecover(getPrefixedHash(signer), _v, _r, _s);
delegations[allowes]=1;
Delegate(allowes, signer);
}
function unDelegate(uint8 _v, bytes32 _r, bytes32 _s)
public
onlySigner
{
address allowes = ecrecover(getPrefixedHash(signer), _v, _r, _s);
delegations[allowes]=0;
UnDelegate(allowes, signer);
}
/**
* Show delegation
*/
function delegation(address _owner)
public
constant
returns (uint8 status)
{
return delegations[_owner];
}
/**
* @notice Hash a hash with `"\x19Ethereum Signed Message:\n32"`
* @param _message Data to ign
* @return signHash Hash to be signed.
*/
function getPrefixedHash(address _message)
pure
public
returns(bytes32 signHash)
{
signHash = keccak256("\x19Ethereum Signed Message:\n20", _message);
}
/**
* 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 transferDelegated(address _from, address _to, uint256 _value)
public
onlySigner
returns (bool success)
{
// Check delegate
require(delegations[_from]==1);
//transfer tokens
return _transfer(_from, _to, _value);
}
/**
* Contribute tokens from delegated address
*
* Contribute `_value` tokens `_from` address
*
* @param _from The address of the sender
* @param _value the amount to send
*/
function contributeDelegated(address _from, uint256 _value)
public
onlySigner
{
// Check delegate
require(delegations[_from]==1);
// Check if the sender has enough
require((_value > 0) && (balances[_from] >= _value));
// Subtract from the sender
balances[_from] = balances[_from].sub(_value);
contributions[_from] = contributions[_from].add(_value);
Contribute(_from, _value);
}
/**
* Reward tokens from delegated address
*
* Reward `_value` tokens to `_from` address
*
* @param _from The address of the sender
* @param _value the amount to send
*/
function reward(address _from, uint256 _value)
public
onlySigner
{
require(contributions[_from]>=_value);
contributions[_from] = contributions[_from].sub(_value);
balances[_from] = balances[_from].add(_value);
Reward(_from, _value);
}
/**
* Don't accept ETH, it is utility token
*/
function ()
public
payable
{
revert();
}
} | Reward tokens from delegated address Reward `_value` tokens to `_from` address _from The address of the sender _value the amount to send/ | function reward(address _from, uint256 _value)
public
onlySigner
{
require(contributions[_from]>=_value);
contributions[_from] = contributions[_from].sub(_value);
balances[_from] = balances[_from].add(_value);
Reward(_from, _value);
}
| 386,200 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ConfigurableOperational
* @notice A configurable with modifiers for operational mode state validation
*/
contract ConfigurableOperational is Configurable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyOperationalModeNormal() {
require(configuration.isOperationalModeNormal(), "Operational mode is not normal [ConfigurableOperational.sol:22]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
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;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentTypesLib
* @dev Data types centered around payment
*/
library PaymentTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum PaymentPartyRole {Sender, Recipient}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct PaymentSenderParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
string data;
}
struct PaymentRecipientParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.TotalOriginFigures fees;
}
struct Operator {
uint256 id;
string data;
}
struct Payment {
int256 amount;
MonetaryTypesLib.Currency currency;
PaymentSenderParty sender;
PaymentRecipientParty recipient;
// Positive transfer is always in direction from sender to recipient
NahmiiTypesLib.SingleTotalInt256 transfers;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
Operator operator;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function PAYMENT_KIND()
public
pure
returns (string memory)
{
return "payment";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHasher
* @notice Contract that hashes types related to payment
*/
contract PaymentHasher is Ownable {
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function hashPaymentAsWallet(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 amountCurrencyHash = hashPaymentAmountCurrency(payment);
bytes32 senderHash = hashPaymentSenderPartyAsWallet(payment.sender);
bytes32 recipientHash = hashAddress(payment.recipient.wallet);
return keccak256(abi.encodePacked(amountCurrencyHash, senderHash, recipientHash));
}
function hashPaymentAsOperator(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 walletSignatureHash = hashSignature(payment.seals.wallet.signature);
bytes32 senderHash = hashPaymentSenderPartyAsOperator(payment.sender);
bytes32 recipientHash = hashPaymentRecipientPartyAsOperator(payment.recipient);
bytes32 transfersHash = hashSingleTotalInt256(payment.transfers);
bytes32 operatorHash = hashString(payment.operator.data);
return keccak256(abi.encodePacked(
walletSignatureHash, senderHash, recipientHash, transfersHash, operatorHash
));
}
function hashPaymentAmountCurrency(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
payment.amount,
payment.currency.ct,
payment.currency.id
));
}
function hashPaymentSenderPartyAsWallet(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
paymentSenderParty.wallet,
paymentSenderParty.data
));
}
function hashPaymentSenderPartyAsOperator(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentSenderParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentSenderParty.balances);
bytes32 singleFeeHash = hashFigure(paymentSenderParty.fees.single);
bytes32 totalFeesHash = hashOriginFigures(paymentSenderParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, singleFeeHash, totalFeesHash
));
}
function hashPaymentRecipientPartyAsOperator(
PaymentTypesLib.PaymentRecipientParty memory paymentRecipientParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentRecipientParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentRecipientParty.balances);
bytes32 totalFeesHash = hashOriginFigures(paymentRecipientParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, totalFeesHash
));
}
function hashCurrentPreviousInt256(
NahmiiTypesLib.CurrentPreviousInt256 memory currentPreviousInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
currentPreviousInt256.current,
currentPreviousInt256.previous
));
}
function hashSingleTotalInt256(
NahmiiTypesLib.SingleTotalInt256 memory singleTotalInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
singleTotalInt256.single,
singleTotalInt256.total
));
}
function hashFigure(MonetaryTypesLib.Figure memory figure)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
figure.amount,
figure.currency.ct,
figure.currency.id
));
}
function hashOriginFigures(NahmiiTypesLib.OriginFigure[] memory originFigures)
public
pure
returns (bytes32)
{
bytes32 hash;
for (uint256 i = 0; i < originFigures.length; i++) {
hash = keccak256(abi.encodePacked(
hash,
originFigures[i].originId,
originFigures[i].figure.amount,
originFigures[i].figure.currency.ct,
originFigures[i].figure.currency.id
)
);
}
return hash;
}
function hashUint256(uint256 _uint256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_uint256));
}
function hashString(string memory _string)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
function hashAddress(address _address)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_address));
}
function hashSignature(NahmiiTypesLib.Signature memory signature)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
signature.v,
signature.r,
signature.s
));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHashable
* @notice An ownable that has a payment hasher property
*/
contract PaymentHashable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
PaymentHasher public paymentHasher;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetPaymentHasherEvent(PaymentHasher oldPaymentHasher, PaymentHasher newPaymentHasher);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the payment hasher contract
/// @param newPaymentHasher The (address of) PaymentHasher contract instance
function setPaymentHasher(PaymentHasher newPaymentHasher)
public
onlyDeployer
notNullAddress(address(newPaymentHasher))
notSameAddresses(address(newPaymentHasher), address(paymentHasher))
{
// Set new payment hasher
PaymentHasher oldPaymentHasher = paymentHasher;
paymentHasher = newPaymentHasher;
// Emit event
emit SetPaymentHasherEvent(oldPaymentHasher, newPaymentHasher);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier paymentHasherInitialized() {
require(address(paymentHasher) != address(0), "Payment hasher not initialized [PaymentHashable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManager
* @notice A contract to control who can execute some specific actions
*/
contract SignerManager is Ownable {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => uint256) public signerIndicesMap; // 1 based internally
address[] public signers;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterSignerEvent(address signer);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
registerSigner(deployer);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Gauge whether an address is registered signer
/// @param _address The concerned address
/// @return true if address is registered signer, else false
function isSigner(address _address)
public
view
returns (bool)
{
return 0 < signerIndicesMap[_address];
}
/// @notice Get the count of registered signers
/// @return The count of registered signers
function signersCount()
public
view
returns (uint256)
{
return signers.length;
}
/// @notice Get the 0 based index of the given address in the list of signers
/// @param _address The concerned address
/// @return The index of the signer address
function signerIndex(address _address)
public
view
returns (uint256)
{
require(isSigner(_address), "Address not signer [SignerManager.sol:71]");
return signerIndicesMap[_address] - 1;
}
/// @notice Registers a signer
/// @param newSigner The address of the signer to register
function registerSigner(address newSigner)
public
onlyOperator
notNullOrThisAddress(newSigner)
{
if (0 == signerIndicesMap[newSigner]) {
// Set new operator
signers.push(newSigner);
signerIndicesMap[newSigner] = signers.length;
// Emit event
emit RegisterSignerEvent(newSigner);
}
}
/// @notice Get the subset of registered signers in the given 0 based index range
/// @param low The lower inclusive index
/// @param up The upper inclusive index
/// @return The subset of registered signers
function signersByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < signers.length, "No signers found [SignerManager.sol:101]");
require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]");
up = up.clampMax(signers.length - 1);
address[] memory _signers = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_signers[i - low] = signers[i];
return _signers;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManageable
* @notice A contract to interface ACL
*/
contract SignerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SignerManager public signerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the signer manager of this contract
/// @param newSignerManager The address of the new signer
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
//set new signer
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
// Emit event
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
/// @notice Prefix input hash and do ecrecover on prefixed hash
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return The address recovered
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
/// @notice Gauge whether a signature of a hash has been signed by a registered signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return true if the recovered signer is one of the registered signers, else false
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
/// @notice Gauge whether a signature of a hash has been signed by the claimed signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @param signer The claimed signer
/// @return true if the recovered signer equals the input signer, else false
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validator
* @notice An ownable that validates valuable types (e.g. payment)
*/
contract Validator is Ownable, SignerManageable, Configurable, PaymentHashable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer, address signerManager) Ownable(deployer) SignerManageable(signerManager) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isGenuineOperatorSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature)
public
view
returns (bool)
{
return isSignedByRegisteredSigner(hash, signature.v, signature.r, signature.s);
}
function isGenuineWalletSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature, address wallet)
public
pure
returns (bool)
{
return isSignedBy(hash, signature.v, signature.r, signature.s, wallet);
}
function isGenuinePaymentWalletHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsWallet(payment) == payment.seals.wallet.hash;
}
function isGenuinePaymentOperatorHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsOperator(payment) == payment.seals.operator.hash;
}
function isGenuinePaymentWalletSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletHash(payment)
&& isGenuineWalletSignature(payment.seals.wallet.hash, payment.seals.wallet.signature, payment.sender.wallet);
}
function isGenuinePaymentOperatorSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentOperatorHash(payment)
&& isGenuineOperatorSignature(payment.seals.operator.hash, payment.seals.operator.signature);
}
function isGenuinePaymentSeals(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletSeal(payment) && isGenuinePaymentOperatorSeal(payment);
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentFeeOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
int256 feePartsPer = int256(ConstantsLib.PARTS_PER());
int256 feeAmount = payment.amount
.mul(
configuration.currencyPaymentFee(
payment.blockNumber, payment.currency.ct, payment.currency.id, payment.amount
)
).div(feePartsPer);
if (1 > feeAmount)
feeAmount = 1;
return (payment.sender.fees.single.amount == feeAmount);
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentFeeOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
(address feeCurrencyCt, uint256 feeCurrencyId) = configuration.feeCurrency(
payment.blockNumber, payment.currency.ct, payment.currency.id
);
return feeCurrencyCt == payment.sender.fees.single.currency.ct
&& feeCurrencyId == payment.sender.fees.single.currency.id;
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentSenderOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet))
&& (payment.sender.balances.current == payment.sender.balances.previous.sub(payment.transfers.single).sub(payment.sender.fees.single.amount));
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentRecipientOfFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (payment.recipient.balances.current == payment.recipient.balances.previous.add(payment.transfers.single));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentSenderOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentRecipientOfNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet);
}
function isSuccessivePaymentsPartyNonces(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole
)
public
pure
returns (bool)
{
uint256 firstNonce = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.nonce : firstPayment.recipient.nonce);
uint256 lastNonce = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.nonce : lastPayment.recipient.nonce);
return lastNonce == firstNonce.add(1);
}
function isGenuineSuccessivePaymentsBalances(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole,
int256 delta
)
public
pure
returns (bool)
{
NahmiiTypesLib.CurrentPreviousInt256 memory firstCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.balances : firstPayment.recipient.balances);
NahmiiTypesLib.CurrentPreviousInt256 memory lastCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.balances : lastPayment.recipient.balances);
return lastCurrentPreviousBalances.previous == firstCurrentPreviousBalances.current.add(delta);
}
function isGenuineSuccessivePaymentsTotalFees(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.Payment memory lastPayment
)
public
pure
returns (bool)
{
MonetaryTypesLib.Figure memory firstTotalFee = getProtocolFigureByCurrency(firstPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
MonetaryTypesLib.Figure memory lastTotalFee = getProtocolFigureByCurrency(lastPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
return lastTotalFee.amount == firstTotalFee.amount.add(lastPayment.sender.fees.single.amount);
}
function isPaymentParty(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet || wallet == payment.recipient.wallet;
}
function isPaymentSender(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet;
}
function isPaymentRecipient(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.recipient.wallet;
}
function isPaymentCurrency(PaymentTypesLib.Payment memory payment, MonetaryTypesLib.Currency memory currency)
public
pure
returns (bool)
{
return currency.ct == payment.currency.ct && currency.id == payment.currency.id;
}
function isPaymentCurrencyNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return payment.currency.ct != payment.sender.fees.single.currency.ct
|| payment.currency.id != payment.sender.fees.single.currency.id;
}
//
// Private unctions
// -----------------------------------------------------------------------------------------------------------------
function getProtocolFigureByCurrency(NahmiiTypesLib.OriginFigure[] memory originFigures, MonetaryTypesLib.Currency memory currency)
private
pure
returns (MonetaryTypesLib.Figure memory) {
for (uint256 i = 0; i < originFigures.length; i++)
if (originFigures[i].figure.currency.ct == currency.ct && originFigures[i].figure.currency.id == currency.id
&& originFigures[i].originId == 0)
return originFigures[i].figure;
return MonetaryTypesLib.Figure(0, currency);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TradeTypesLib
* @dev Data types centered around trade
*/
library TradeTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum CurrencyRole {Intended, Conjugate}
enum LiquidityRole {Maker, Taker}
enum Intention {Buy, Sell}
enum TradePartyRole {Buyer, Seller}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OrderPlacement {
Intention intention;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct Order {
uint256 nonce;
address wallet;
OrderPlacement placement;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
uint256 operatorId;
}
struct TradeOrder {
int256 amount;
NahmiiTypesLib.WalletOperatorHashes hashes;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct TradeParty {
uint256 nonce;
address wallet;
uint256 rollingVolume;
LiquidityRole liquidityRole;
TradeOrder order;
NahmiiTypesLib.IntendedConjugateCurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
}
struct Trade {
uint256 nonce;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
TradeParty buyer;
TradeParty seller;
// Positive intended transfer is always in direction from seller to buyer
// Positive conjugate transfer is always in direction from buyer to seller
NahmiiTypesLib.IntendedConjugateSingleTotalInt256 transfers;
NahmiiTypesLib.Seal seal;
uint256 blockNumber;
uint256 operatorId;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function TRADE_KIND()
public
pure
returns (string memory)
{
return "trade";
}
function ORDER_KIND()
public
pure
returns (string memory)
{
return "order";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validatable
* @notice An ownable that has a validator property
*/
contract Validatable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Validator public validator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetValidatorEvent(Validator oldValidator, Validator newValidator);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the validator contract
/// @param newValidator The (address of) Validator contract instance
function setValidator(Validator newValidator)
public
onlyDeployer
notNullAddress(address(newValidator))
notSameAddresses(address(newValidator), address(validator))
{
//set new validator
Validator oldValidator = validator;
validator = newValidator;
// Emit event
emit SetValidatorEvent(oldValidator, newValidator);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier validatorInitialized() {
require(address(validator) != address(0), "Validator not initialized [Validatable.sol:55]");
_;
}
modifier onlyOperatorSealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentOperatorSeal(payment), "Payment operator seal not genuine [Validatable.sol:60]");
_;
}
modifier onlySealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentSeals(payment), "Payment seals not genuine [Validatable.sol:65]");
_;
}
modifier onlyPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentParty(payment, wallet), "Wallet not payment party [Validatable.sol:70]");
_;
}
modifier onlyPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentSender(payment, wallet), "Wallet not payment sender [Validatable.sol:75]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBond
* @notice Fund that contains crypto incentive for challenging operator fraud.
*/
contract SecurityBond is Ownable, Configurable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public REWARD_ACTION = "reward";
string constant public DEPRIVE_ACTION = "deprive";
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct FractionalReward {
uint256 fraction;
uint256 nonce;
uint256 unlockTime;
}
struct AbsoluteReward {
int256 amount;
uint256 nonce;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance private deposited;
TxHistoryLib.TxHistory private txHistory;
CurrenciesLib.Currencies private inUseCurrencies;
mapping(address => FractionalReward) public fractionalRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => AbsoluteReward))) public absoluteRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => uint256))) public claimNonceByWalletCurrency;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
mapping(address => uint256) public nonceByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RewardFractionalEvent(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds);
event RewardAbsoluteEvent(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds);
event DepriveFractionalEvent(address wallet);
event DepriveAbsoluteEvent(address wallet, address currencyCt, uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address from, Beneficiary beneficiary, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Servable() public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balance
deposited.add(amount, address(0), 0);
txHistory.addDeposit(amount, address(0), 0);
// Add currency to in-use list
inUseCurrencies.add(address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:145]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [SecurityBond.sol:154]");
// Add to balance
deposited.add(amount, currencyCt, currencyId);
txHistory.addDeposit(amount, currencyCt, currencyId);
// Add currency to in-use list
inUseCurrencies.add(currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the deposited balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function depositedBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId);
}
/// @notice Get the fractional amount deposited balance of the given currency
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
/// @param fraction The fraction of sums that the wallet is rewarded
/// @return The fractional amount of deposited balance
function depositedFractionalBalance(address currencyCt, uint256 currencyId, uint256 fraction)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fraction))
.div(ConstantsLib.PARTS_PER());
}
/// @notice Get the staged balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded
/// @return The number of currencies
function inUseCurrenciesCount()
public
view
returns (uint256)
{
return inUseCurrencies.count();
}
/// @notice Get the currencies recorded with indices in the given range
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range
function inUseCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return inUseCurrencies.getByIndices(low, up);
}
/// @notice Reward the given wallet the given fraction of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param fraction The fraction of sums that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardFractional(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = fraction.clampMax(uint256(ConstantsLib.PARTS_PER()));
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardFractionalEvent(wallet, fraction, unlockTimeoutInSeconds);
}
/// @notice Reward the given wallet the given amount of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param amount The amount that the wallet is rewarded
/// @param currencyCt The contract address of the currency that the wallet is rewarded
/// @param currencyId The ID of the currency that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardAbsolute(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = amount;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardAbsoluteEvent(wallet, amount, currencyCt, currencyId, unlockTimeoutInSeconds);
}
/// @notice Deprive the given wallet of any fractional reward it has been granted
/// @param wallet The concerned wallet
function depriveFractional(address wallet)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = 0;
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = 0;
// Emit event
emit DepriveFractionalEvent(wallet);
}
/// @notice Deprive the given wallet of any absolute reward it has been granted in the given currency
/// @param wallet The concerned wallet
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
function depriveAbsolute(address wallet, address currencyCt, uint256 currencyId)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = 0;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = 0;
// Emit event
emit DepriveAbsoluteEvent(wallet, currencyCt, currencyId);
}
/// @notice Claim reward and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(msg.sender, balanceType);
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [SecurityBond.sol:350]");
beneficiary.receiveTokensTo(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, beneficiary, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim reward and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Add to staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:386]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [SecurityBond.sol:405]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Combine claim nonce from rewards
uint256 claimNonce = fractionalRewardByWallet[wallet].nonce.clampMin(
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce
);
// Require that new claim nonce is strictly greater than current stored one
require(
claimNonce > claimNonceByWalletCurrency[wallet][currencyCt][currencyId],
"Claim nonce not strictly greater than previously claimed nonce [SecurityBond.sol:425]"
);
// Combine claim amount from rewards
int256 claimAmount = _fractionalRewardAmountByWalletCurrency(wallet, currencyCt, currencyId).add(
_absoluteRewardAmountByWalletCurrency(wallet, currencyCt, currencyId)
).clampMax(
deposited.get(currencyCt, currencyId)
);
// Require that claim amount is strictly positive, indicating that there is an amount to claim
require(claimAmount.isNonZeroPositiveInt256(), "Claim amount not strictly positive [SecurityBond.sol:438]");
// Update stored claim nonce for wallet and currency
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] = claimNonce;
return claimAmount;
}
function _fractionalRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < fractionalRewardByWallet[wallet].nonce &&
block.timestamp >= fractionalRewardByWallet[wallet].unlockTime
)
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fractionalRewardByWallet[wallet].fraction))
.div(ConstantsLib.PARTS_PER());
else
return 0;
}
function _absoluteRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce &&
block.timestamp >= absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime
)
return absoluteRewardByWallet[wallet][currencyCt][currencyId].amount.clampMax(
deposited.get(currencyCt, currencyId)
);
else
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBondable
* @notice An ownable that has a security bond property
*/
contract SecurityBondable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SecurityBond public securityBond;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSecurityBondEvent(SecurityBond oldSecurityBond, SecurityBond newSecurityBond);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the security bond contract
/// @param newSecurityBond The (address of) SecurityBond contract instance
function setSecurityBond(SecurityBond newSecurityBond)
public
onlyDeployer
notNullAddress(address(newSecurityBond))
notSameAddresses(address(newSecurityBond), address(securityBond))
{
//set new security bond
SecurityBond oldSecurityBond = securityBond;
securityBond = newSecurityBond;
// Emit event
emit SetSecurityBondEvent(oldSecurityBond, newSecurityBond);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier securityBondInitialized() {
require(address(securityBond) != address(0), "Security bond not initialized [SecurityBondable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallenge
* @notice Where fraud challenge results are found
*/
contract FraudChallenge is Ownable, Servable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public ADD_SEIZED_WALLET_ACTION = "add_seized_wallet";
string constant public ADD_DOUBLE_SPENDER_WALLET_ACTION = "add_double_spender_wallet";
string constant public ADD_FRAUDULENT_ORDER_ACTION = "add_fraudulent_order";
string constant public ADD_FRAUDULENT_TRADE_ACTION = "add_fraudulent_trade";
string constant public ADD_FRAUDULENT_PAYMENT_ACTION = "add_fraudulent_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address[] public doubleSpenderWallets;
mapping(address => bool) public doubleSpenderByWallet;
bytes32[] public fraudulentOrderHashes;
mapping(bytes32 => bool) public fraudulentByOrderHash;
bytes32[] public fraudulentTradeHashes;
mapping(bytes32 => bool) public fraudulentByTradeHash;
bytes32[] public fraudulentPaymentHashes;
mapping(bytes32 => bool) public fraudulentByPaymentHash;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AddDoubleSpenderWalletEvent(address wallet);
event AddFraudulentOrderHashEvent(bytes32 hash);
event AddFraudulentTradeHashEvent(bytes32 hash);
event AddFraudulentPaymentHashEvent(bytes32 hash);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the number of wallets tagged as double spenders
/// @return Number of double spender wallets
function doubleSpenderWalletsCount()
public
view
returns (uint256)
{
return doubleSpenderWallets.length;
}
/// @notice Add given wallets to store of double spender wallets if not already present
/// @param wallet The first wallet to add
function addDoubleSpenderWallet(address wallet)
public
onlyEnabledServiceAction(ADD_DOUBLE_SPENDER_WALLET_ACTION) {
if (!doubleSpenderByWallet[wallet]) {
doubleSpenderWallets.push(wallet);
doubleSpenderByWallet[wallet] = true;
emit AddDoubleSpenderWalletEvent(wallet);
}
}
/// @notice Get the number of fraudulent order hashes
function fraudulentOrderHashesCount()
public
view
returns (uint256)
{
return fraudulentOrderHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent order
/// @param hash The hash to be tested
function isFraudulentOrderHash(bytes32 hash)
public
view returns (bool) {
return fraudulentByOrderHash[hash];
}
/// @notice Add given order hash to store of fraudulent order hashes if not already present
function addFraudulentOrderHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_ORDER_ACTION)
{
if (!fraudulentByOrderHash[hash]) {
fraudulentByOrderHash[hash] = true;
fraudulentOrderHashes.push(hash);
emit AddFraudulentOrderHashEvent(hash);
}
}
/// @notice Get the number of fraudulent trade hashes
function fraudulentTradeHashesCount()
public
view
returns (uint256)
{
return fraudulentTradeHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent trade
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent trade, else false
function isFraudulentTradeHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByTradeHash[hash];
}
/// @notice Add given trade hash to store of fraudulent trade hashes if not already present
function addFraudulentTradeHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_TRADE_ACTION)
{
if (!fraudulentByTradeHash[hash]) {
fraudulentByTradeHash[hash] = true;
fraudulentTradeHashes.push(hash);
emit AddFraudulentTradeHashEvent(hash);
}
}
/// @notice Get the number of fraudulent payment hashes
function fraudulentPaymentHashesCount()
public
view
returns (uint256)
{
return fraudulentPaymentHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent payment
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent payment, else null
function isFraudulentPaymentHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByPaymentHash[hash];
}
/// @notice Add given payment hash to store of fraudulent payment hashes if not already present
function addFraudulentPaymentHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_PAYMENT_ACTION)
{
if (!fraudulentByPaymentHash[hash]) {
fraudulentByPaymentHash[hash] = true;
fraudulentPaymentHashes.push(hash);
emit AddFraudulentPaymentHashEvent(hash);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallengable
* @notice An ownable that has a fraud challenge property
*/
contract FraudChallengable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FraudChallenge public fraudChallenge;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetFraudChallengeEvent(FraudChallenge oldFraudChallenge, FraudChallenge newFraudChallenge);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the fraud challenge contract
/// @param newFraudChallenge The (address of) FraudChallenge contract instance
function setFraudChallenge(FraudChallenge newFraudChallenge)
public
onlyDeployer
notNullAddress(address(newFraudChallenge))
notSameAddresses(address(newFraudChallenge), address(fraudChallenge))
{
// Set new fraud challenge
FraudChallenge oldFraudChallenge = fraudChallenge;
fraudChallenge = newFraudChallenge;
// Emit event
emit SetFraudChallengeEvent(oldFraudChallenge, newFraudChallenge);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier fraudChallengeInitialized() {
require(address(fraudChallenge) != address(0), "Fraud challenge not initialized [FraudChallengable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BalanceTrackerLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
function fungibleActiveRecordByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 _blockNumber)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.depositedBalanceType(), currency.ct, currency.id, _blockNumber
);
(int256 settledAmount, uint256 settledBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.settledBalanceType(), currency.ct, currency.id, _blockNumber
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
function fungibleActiveBalanceAmountByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = fungibleActiveRecordByBlockNumber(self, wallet, currency, blockNumber);
return amount;
}
function fungibleActiveDeltaBalanceAmountByBlockNumbers(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 fromBlockNumber, uint256 toBlockNumber)
internal
view
returns (int256)
{
return fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, toBlockNumber) -
fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, fromBlockNumber);
}
// TODO Rename?
function fungibleActiveRecord(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.lastFungibleRecord(
wallet, self.depositedBalanceType(), currency.ct, currency.id
);
(int256 settledAmount, uint256 settledBlockNumber) = self.lastFungibleRecord(
wallet, self.settledBalanceType(), currency.ct, currency.id
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
// TODO Rename?
function fungibleActiveBalanceAmount(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256)
{
return self.get(wallet, self.depositedBalanceType(), currency.ct, currency.id).add(
self.get(wallet, self.settledBalanceType(), currency.ct, currency.id)
);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementDisputeByPayment
* @notice The where payment related disputes of null settlement challenge happens
*/
contract NullSettlementDisputeByPayment is Ownable, Configurable, Validatable, SecurityBondable, WalletLockable,
BalanceTrackable, FraudChallengable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CHALLENGE_BY_PAYMENT_ACTION = "challenge_by_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event ChallengeByPaymentEvent(address wallet, uint256 nonce, PaymentTypesLib.Payment payment,
address challenger);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
/// @notice Set the settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Challenge the settlement by providing payment candidate
/// @dev This challenges the payment sender's side of things
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges
/// @param challenger The address of the challenger
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment, address challenger)
public
onlyEnabledServiceAction(CHALLENGE_BY_PAYMENT_ACTION)
onlySealedPayment(payment)
onlyPaymentSender(payment, wallet)
{
// Require that payment candidate is not labelled fraudulent
require(!fraudChallenge.isFraudulentPaymentHash(payment.seals.operator.hash), "Payment deemed fraudulent [NullSettlementDisputeByPayment.sol:86]");
// Require that proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, payment.currency), "No proposal found [NullSettlementDisputeByPayment.sol:89]");
// Require that proposal has not expired
require(!nullSettlementChallengeState.hasProposalExpired(wallet, payment.currency), "Proposal found expired [NullSettlementDisputeByPayment.sol:92]");
// Require that payment party's nonce is strictly greater than proposal's nonce and its current
// disqualification nonce
require(payment.sender.nonce > nullSettlementChallengeState.proposalNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal nonce [NullSettlementDisputeByPayment.sol:96]");
require(payment.sender.nonce > nullSettlementChallengeState.proposalDisqualificationNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal disqualification nonce [NullSettlementDisputeByPayment.sol:99]");
// Require overrun for this payment to be a valid challenge candidate
require(_overrun(wallet, payment), "No overrun found [NullSettlementDisputeByPayment.sol:104]");
// Reward challenger
_settleRewards(wallet, payment.sender.balances.current, payment.currency, challenger);
// Disqualify proposal, effectively overriding any previous disqualification
nullSettlementChallengeState.disqualifyProposal(
wallet, payment.currency, challenger, payment.blockNumber,
payment.sender.nonce, payment.seals.operator.hash, PaymentTypesLib.PAYMENT_KIND()
);
// Emit event
emit ChallengeByPaymentEvent(
wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), payment, challenger
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _overrun(address wallet, PaymentTypesLib.Payment memory payment)
private
view
returns (bool)
{
// Get the target balance amount from the proposal
int targetBalanceAmount = nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, payment.currency
);
// Get the change in active balance since the start of the challenge
int256 deltaBalanceSinceStart = balanceTracker.fungibleActiveBalanceAmount(
wallet, payment.currency
).sub(
balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency,
nullSettlementChallengeState.proposalReferenceBlockNumber(wallet, payment.currency)
)
);
// Get the cumulative transfer of the payment
int256 cumulativeTransfer = balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency, payment.blockNumber
).sub(payment.sender.balances.current);
return targetBalanceAmount.add(deltaBalanceSinceStart) < cumulativeTransfer;
}
// Lock wallet's balances or reward challenger by stake fraction
function _settleRewards(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
if (nullSettlementChallengeState.proposalWalletInitiated(wallet, currency))
_settleBalanceReward(wallet, walletAmount, currency, challenger);
else
_settleSecurityBondReward(wallet, walletAmount, currency, challenger);
}
function _settleBalanceReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Unlock wallet/currency for existing challenger if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
walletLocker.unlockFungibleByProxy(
wallet,
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Lock wallet for new challenger
walletLocker.lockFungibleByProxy(
wallet, challenger, walletAmount, currency.ct, currency.id, configuration.settlementChallengeTimeout()
);
}
// Settle the two-component reward from security bond.
// The first component is flat figure as obtained from Configuration
// The second component is progressive and calculated as
// min(walletAmount, fraction of SecurityBond's deposited balance)
// both amounts for the given currency
function _settleSecurityBondReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Deprive existing challenger of reward if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
securityBond.depriveAbsolute(
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Reward the flat component
MonetaryTypesLib.Figure memory flatReward = _flatReward();
securityBond.rewardAbsolute(
challenger, flatReward.amount, flatReward.currency.ct, flatReward.currency.id, 0
);
// Reward the progressive component
int256 progressiveRewardAmount = walletAmount.clampMax(
securityBond.depositedFractionalBalance(
currency.ct, currency.id, configuration.operatorSettlementStakeFraction()
)
);
securityBond.rewardAbsolute(
challenger, progressiveRewardAmount, currency.ct, currency.id, 0
);
}
function _flatReward()
private
view
returns (MonetaryTypesLib.Figure memory)
{
(int256 amount, address currencyCt, uint256 currencyId) = configuration.operatorSettlementStake();
return MonetaryTypesLib.Figure(amount, MonetaryTypesLib.Currency(currencyCt, currencyId));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeByPayment
* @notice Where null settlements pertaining to payments are started and disputed
*/
contract NullSettlementChallengeByPayment is Ownable, ConfigurableOperational, BalanceTrackable, WalletLockable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementDisputeByPayment public nullSettlementDisputeByPayment;
NullSettlementChallengeState public nullSettlementChallengeState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementDisputeByPaymentEvent(NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment,
NullSettlementDisputeByPayment newNullSettlementDisputeByPayment);
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event StartChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId);
event StartChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId, address proxy);
event StopChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId);
event StopChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address proxy);
event ChallengeByPaymentEvent(address challengedWallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address challengerWallet);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the settlement dispute contract
/// @param newNullSettlementDisputeByPayment The (address of) NullSettlementDisputeByPayment contract instance
function setNullSettlementDisputeByPayment(NullSettlementDisputeByPayment newNullSettlementDisputeByPayment)
public
onlyDeployer
notNullAddress(address(newNullSettlementDisputeByPayment))
{
NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment = nullSettlementDisputeByPayment;
nullSettlementDisputeByPayment = newNullSettlementDisputeByPayment;
emit SetNullSettlementDisputeByPaymentEvent(oldNullSettlementDisputeByPayment, nullSettlementDisputeByPayment);
}
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Start settlement challenge
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallenge(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Require that wallet is not locked
require(!walletLocker.isLocked(msg.sender), "Wallet found locked [NullSettlementChallengeByPayment.sol:116]");
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(msg.sender, amount, currency, true);
// Emit event
emit StartChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Start settlement challenge for the given wallet
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(wallet, amount, currency, false);
// Emit event
emit StartChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Stop settlement challenge
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallenge(address currencyCt, uint256 currencyId)
public
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(msg.sender, currency, true);
// Emit event
emit StopChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
nullSettlementChallengeState.proposalStageAmount(msg.sender, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Stop settlement challenge
/// @param wallet The concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallengeByProxy(address wallet, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(wallet, currency, false);
// Emit event
emit StopChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
nullSettlementChallengeState.proposalStageAmount(wallet, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has been defined
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has been initiated, else false
function hasProposal(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposal(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalTerminated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalExpired(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge nonce of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge nonce
function proposalNonce(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalNonce(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal block number of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal block number
function proposalReferenceBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalReferenceBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal end time of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal end time
function proposalExpirationTime(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalExpirationTime(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge status of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge status
function proposalStatus(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (SettlementChallengeTypesLib.Status)
{
return nullSettlementChallengeState.proposalStatus(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalStageAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the balance reward of the given wallet's settlement proposal
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The balance reward of the settlement proposal
function proposalWalletInitiated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.proposalWalletInitiated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenger of the settlement disqualification
function proposalDisqualificationChallenger(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (address)
{
return nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The block number of the settlement disqualification
function proposalDisqualificationBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalDisqualificationBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate kind of the settlement disqualification
function proposalDisqualificationCandidateKind(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (string memory)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateKind(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate hash of the settlement disqualification
function proposalDisqualificationCandidateHash(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bytes32)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateHash(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Challenge the settlement by providing payment candidate
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges the null
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment)
public
onlyOperationalModeNormal
{
// Challenge by payment
nullSettlementDisputeByPayment.challengeByPayment(wallet, payment, msg.sender);
// Emit event
emit ChallengeByPaymentEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, payment.currency),
nullSettlementChallengeState.proposalStageAmount(wallet, payment.currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, payment.currency),
payment.currency.ct, payment.currency.id, msg.sender
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _startChallenge(address wallet, int256 stageAmount, MonetaryTypesLib.Currency memory currency,
bool walletInitiated)
private
{
// Require that current block number is beyond the earliest settlement challenge block number
require(
block.number >= configuration.earliestSettlementBlockNumber(),
"Current block number below earliest settlement block number [NullSettlementChallengeByPayment.sol:443]"
);
// Require that there is no ongoing overlapping null settlement challenge
require(
!nullSettlementChallengeState.hasProposal(wallet, currency) ||
nullSettlementChallengeState.hasProposalExpired(wallet, currency),
"Overlapping null settlement challenge proposal found [NullSettlementChallengeByPayment.sol:449]"
);
// Get the last logged active balance amount and block number, properties of overlapping DSC
// and the baseline nonce
(
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) = _externalProperties(
wallet, currency
);
// Initiate proposal, including assurance that there is no overlap with active proposal
// Target balance amount is calculated as current balance - DSC cumulativeTransferAmount - DSC stage amount - NSC stageAmount
nullSettlementChallengeState.initiateProposal(
wallet, nonce, stageAmount,
activeBalanceAmount.sub(
dscCumulativeTransferAmount.add(dscStageAmount).add(stageAmount)
),
currency,
activeBalanceBlockNumber, walletInitiated
);
}
function _stopChallenge(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
private
{
// Require that there is an unterminated driip settlement challenge proposal
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlementChallengeByPayment.sol:481]");
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlementChallengeByPayment.sol:482]");
// Terminate driip settlement challenge proposal
nullSettlementChallengeState.terminateProposal(
wallet, currency, walletTerminated
);
}
function _externalProperties(address wallet, MonetaryTypesLib.Currency memory currency)
private
view
returns (
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) {
(activeBalanceAmount, activeBalanceBlockNumber) = balanceTracker.fungibleActiveRecord(
wallet, currency
);
if (driipSettlementChallengeState.hasProposal(wallet, currency)) {
if (!driipSettlementChallengeState.hasProposalTerminated(wallet, currency)) {
dscCumulativeTransferAmount = driipSettlementChallengeState.proposalCumulativeTransferAmount(wallet, currency);
dscStageAmount = driipSettlementChallengeState.proposalStageAmount(wallet, currency);
}
nonce = driipSettlementChallengeState.proposalNonce(wallet, currency);
}
if (nullSettlementChallengeState.hasProposal(wallet, currency))
nonce = nonce.clampMin(nullSettlementChallengeState.proposalNonce(wallet, currency));
}
} | Remove a proposal wallet The address of the concerned challenged wallet currency The concerned currency walletTerminated True if wallet terminated Get the proposal index Return gracefully if there is no proposal to remove Require that role that initialized (wallet or operator) can only cancel its own proposal Emit event Remove proposal | function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
if (0 == index)
return;
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
_removeProposal(index);
}
| 12,574,705 |
./full_match/4/0xec9fEeccfBDb3573e6502F8Cd04dC482BB87B0f0/sources/contracts/Tiktaalik.sol | _personalCoin.mint(tx.origin, _amount);personalCoins[tx.origin] = address(personalCoin); | function generatePersonalCoin(ERC20PresetMinterPauser _personalCoin, uint _amount) internal {
}
| 764,863 |
./full_match/3/0x8B5314762f59Afd7e97cc3Cb140958E0EB38d82E/sources/brid.sol | cashier.depositTo {value(msg.value)(_crosschainToken, _to, _amount); | function depositTo(address _crosschainToken, address _to, uint256 _amount) public payable {
require(_crosschainToken != address(0), "invalid token");
ERC20 token = ICrosschainToken(_crosschainToken).coToken();
require(safeTransferFrom(address(token), msg.sender, address(this), _amount), "failed to transfer token");
ICrosschainToken(_crosschainToken).deposit(_amount);
}
| 14,231,183 |
/**
*Submitted for verification at Etherscan.io on 2020-10-09
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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;
}
}
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(
gas(),
implementation,
0,
calldatasize(),
0,
0
)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(
IMPLEMENTATION_SLOT ==
bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)
);
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
"Cannot set a proxy implementation to a non-contract address"
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(
address _logic,
address _admin,
bytes memory _data
) public payable UpgradeabilityProxy(_logic, _data) {
assert(
ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)
);
_setAdmin(_admin);
}
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(
newAdmin != address(0),
"Cannot change the admin of a proxy to the zero address"
);
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(
msg.sender != _admin(),
"Cannot call fallback function from the proxy admin"
);
super._willFallback();
}
} | Only fall back when the sender is not the admin./ | function _willFallback() internal virtual override {
require(
msg.sender != _admin(),
"Cannot call fallback function from the proxy admin"
);
super._willFallback();
}
| 2,404,866 |
/**
* @dev Cryptolotto referral system interface.
*/
contract iCryptolottoReferral {
/**
* @dev Get partner by referral.
*/
function getPartnerByReferral(address) public view returns (address) {}
/**
* @dev Get partner percent.
*/
function getPartnerPercent(address) public view returns (uint8) {}
/**
* @dev Get sales partner percent by partner address.
*/
function getSalesPartnerPercent(address) public view returns (uint8) {}
/**
* @dev Get sales partner address by partner address.
*/
function getSalesPartner(address) public view returns (address) {}
/**
* @dev Add new referral.
*/
function addReferral(address, address) public {}
}
/**
* @dev Cryptolotto stats aggregator interface.
*/
contract iCryptolottoStatsAggregator {
/**
* @dev Write info to log about the new winner.
*/
function newWinner(address, uint, uint, uint, uint8, uint) public {}
}
/**
* @dev Ownable contract interface.
*/
contract iOwnable {
function getOwner() public view returns (address) {}
function allowed(address) public view returns (bool) {}
}
/**
* @title Cryptolotto1Day
* @dev This smart contract is a part of Cryptolotto (cryptolotto.cc) product.
*
* @dev Cryptolotto is a blockchain-based, Ethereum powered lottery which gives to users the most
* @dev transparent and honest chances of winning.
*
* @dev The main idea of Cryptolotto is straightforward: people from all over the world during the
* @dev set period of time are contributing an equal amount of ETH to one wallet. When a timer ends
* @dev this smart-contract powered wallet automatically sends all received ETHs to a one randomly
* @dev chosen wallet-participant.
*
* @dev Due to the fact that Cryptolotto is built on a blockchain technology, it eliminates any
* @dev potential for intervention by third parties and gives 100% guarantee of an honest game.
* @dev There are no backdoors and no human or computer soft can interfere the process of picking a winner.
*
* @dev If during the game only one player joins it, then the player will receive all his ETH back.
* @dev If a player sends not the exact amount of ETH - he will receive all his ETH back.
* @dev Creators of the product can change the entrance price for the game. If the price is changed
* @dev then new rules are applied when a new game starts.
*
* @dev The original idea of Cryptolotto belongs to t.me/crypto_god and t.me/crypto_creator - Founders.
* @dev Cryptolotto smart-contracts are protected by copyright, trademark, patent, trade secret,
* @dev other intellectual property, proprietary rights laws and other applicable laws.
*
* @dev All information related to the product can be found only on:
* @dev - cryptolotto.cc
* @dev - github.com/cryptolotto
* @dev - instagram.com/cryptolotto
* @dev - facebook.com/cryptolotto
*
* @dev Cryptolotto was designed and developed by erde group (https://erde.group).
**/
contract Cryptolotto1Day {
/**
* @dev Write to log info about the new game.
*
* @param _game Game number.
* @param _time Time when game stated.
*/
event Game(uint _game, uint indexed _time);
/**
* @dev Write to log info about the new game player.
*
* @param _address Player wallet address.
* @param _game Game number in which player buy ticket.
* @param _number Player number in the game.
* @param _time Time when player buy ticket.
*/
event Ticket(
address indexed _address,
uint indexed _game,
uint _number,
uint _time
);
/**
* @dev Write to log info about partner earnings.
*
* @param _partner Partner wallet address.
* @param _referral Referral wallet address.
* @param _amount Earning amount.
* @param _time The time when ether was earned.
*/
event ToPartner(
address indexed _partner,
address _referral,
uint _amount,
uint _time
);
/**
* @dev Write to log info about sales partner earnings.
*
* @param _salesPartner Sales partner wallet address.
* @param _partner Partner wallet address.
* @param _amount Earning amount.
* @param _time The time when ether was earned.
*/
event ToSalesPartner(
address indexed _salesPartner,
address _partner,
uint _amount,
uint _time
);
// Game type. Each game has own type.
uint8 public gType = 4;
// Game fee.
uint8 public fee = 10;
// Current game number.
uint public game;
// Ticket price.
uint public ticketPrice = 0.03 ether;
// New ticket price.
uint public newPrice;
// All-time game jackpot.
uint public allTimeJackpot = 0;
// All-time game players count
uint public allTimePlayers = 0;
// Paid to partners.
uint public paidToPartners = 0;
// Game status.
bool public isActive = true;
// The variable that indicates game status switching.
bool public toogleStatus = false;
// The array of all games
uint[] public games;
// Store game jackpot.
mapping(uint => uint) jackpot;
// Store game players.
mapping(uint => address[]) players;
// Ownable contract
iOwnable public ownable;
// Stats aggregator contract.
iCryptolottoStatsAggregator public stats;
// Referral system contract.
iCryptolottoReferral public referralInstance;
// Funds distributor address.
address public fundsDistributor;
/**
* @dev Check sender address and compare it to an owner.
*/
modifier onlyOwner() {
require(ownable.allowed(msg.sender));
_;
}
/**
* @dev Initialize game.
* @dev Create ownable and stats aggregator instances,
* @dev set funds distributor contract address.
*
* @param ownableContract The address of previously deployed ownable contract.
* @param distributor The address of previously deployed funds distributor contract.
* @param statsA The address of previously deployed stats aggregator contract.
* @param referralSystem The address of previously deployed referral system contract.
*/
function Cryptolotto1Day(
address ownableContract,
address distributor,
address statsA,
address referralSystem
)
public
{
ownable = iOwnable(ownableContract);
stats = iCryptolottoStatsAggregator(statsA);
referralInstance = iCryptolottoReferral(referralSystem);
fundsDistributor = distributor;
startGame();
}
/**
* @dev The method that allows buying tickets by directly sending ether to the contract.
*/
function() public payable {
buyTicket(address(0));
}
/**
* @dev Returns current game players.
*/
function getPlayedGamePlayers()
public
view
returns (uint)
{
return getPlayersInGame(game);
}
/**
* @dev Get players by game.
*
* @param playedGame Game number.
*/
function getPlayersInGame(uint playedGame)
public
view
returns (uint)
{
return players[playedGame].length;
}
/**
* @dev Returns current game jackpot.
*/
function getPlayedGameJackpot()
public
view
returns (uint)
{
return getGameJackpot(game);
}
/**
* @dev Get jackpot by game number.
*
* @param playedGame The number of the played game.
*/
function getGameJackpot(uint playedGame)
public
view
returns(uint)
{
return jackpot[playedGame];
}
/**
* @dev Change game status.
* @dev If the game is active sets flag for game status changing. Otherwise, change game status.
*/
function toogleActive() public onlyOwner() {
if (!isActive) {
isActive = true;
} else {
toogleStatus = !toogleStatus;
}
}
/**
* @dev Start the new game.`
*/
function start() public onlyOwner() {
if (players[game].length > 0) {
pickTheWinner();
}
startGame();
}
/**
* @dev Change ticket price on next game.
*
* @param price New ticket price.``
*/
function changeTicketPrice(uint price)
public
onlyOwner()
{
newPrice = price;
}
/**
* @dev Get random number.
* @dev Random number calculation depends on block timestamp,
* @dev difficulty, number and hash.
*
* @param min Minimal number.
* @param max Maximum number.
* @param time Timestamp.
* @param difficulty Block difficulty.
* @param number Block number.
* @param bHash Block hash.
*/
function randomNumber(
uint min,
uint max,
uint time,
uint difficulty,
uint number,
bytes32 bHash
)
public
pure
returns (uint)
{
min ++;
max ++;
uint random = uint(keccak256(
time *
difficulty *
number *
uint(bHash)
))%10 + 1;
uint result = uint(keccak256(random))%(min+max)-min;
if (result > max) {
result = max;
}
if (result < min) {
result = min;
}
result--;
return result;
}
/**
* @dev The payable method that accepts ether and adds the player to the game.
*/
function buyTicket(address partner) public payable {
require(isActive);
require(msg.value == ticketPrice);
jackpot[game] += msg.value;
uint playerNumber = players[game].length;
players[game].push(msg.sender);
processReferralSystem(partner, msg.sender);
emit Ticket(msg.sender, game, playerNumber, now);
}
/**
* @dev Start the new game.
* @dev Checks ticket price changes, if exists new ticket price the price will be changed.
* @dev Checks game status changes, if exists request for changing game status game status
* @dev will be changed.
*/
function startGame() internal {
require(isActive);
game = block.number;
if (newPrice != 0) {
ticketPrice = newPrice;
newPrice = 0;
}
if (toogleStatus) {
isActive = !isActive;
toogleStatus = false;
}
emit Game(game, now);
}
/**
* @dev Pick the winner.
* @dev Check game players, depends on player count provides next logic:
* @dev - if in the game is only one player, by game rules the whole jackpot
* @dev without commission returns to him.
* @dev - if more than one player smart contract randomly selects one player,
* @dev calculates commission and after that jackpot transfers to the winner,
* @dev commision to founders.
*/
function pickTheWinner() internal {
uint winner;
uint toPlayer;
if (players[game].length == 1) {
toPlayer = jackpot[game];
players[game][0].transfer(jackpot[game]);
winner = 0;
} else {
winner = randomNumber(
0,
players[game].length - 1,
block.timestamp,
block.difficulty,
block.number,
blockhash(block.number - 1)
);
uint distribute = jackpot[game] * fee / 100;
toPlayer = jackpot[game] - distribute;
players[game][winner].transfer(toPlayer);
transferToPartner(players[game][winner]);
distribute -= paidToPartners;
bool result = address(fundsDistributor).call.gas(30000).value(distribute)();
if (!result) {
revert();
}
}
paidToPartners = 0;
stats.newWinner(
players[game][winner],
game,
players[game].length,
toPlayer,
gType,
winner
);
allTimeJackpot += toPlayer;
allTimePlayers += players[game].length;
}
/**
* @dev Checks if the player is in referral system.
* @dev Sending earned ether to partners.
*
* @param partner Partner address.
* @param referral Player address.
*/
function processReferralSystem(address partner, address referral)
internal
{
address partnerRef = referralInstance.getPartnerByReferral(referral);
if (partner != address(0) || partnerRef != address(0)) {
if (partnerRef == address(0)) {
referralInstance.addReferral(partner, referral);
partnerRef = partner;
}
if (players[game].length > 1) {
transferToPartner(referral);
}
}
}
/**
* @dev Sending earned ether to partners.
*
* @param referral Player address.
*/
function transferToPartner(address referral) internal {
address partner = referralInstance.getPartnerByReferral(referral);
if (partner != address(0)) {
uint sum = getPartnerAmount(partner);
if (sum != 0) {
partner.transfer(sum);
paidToPartners += sum;
emit ToPartner(partner, referral, sum, now);
transferToSalesPartner(partner);
}
}
}
/**
* @dev Sending earned ether to sales partners.
*
* @param partner Partner address.
*/
function transferToSalesPartner(address partner) internal {
address salesPartner = referralInstance.getSalesPartner(partner);
if (salesPartner != address(0)) {
uint sum = getSalesPartnerAmount(partner);
if (sum != 0) {
salesPartner.transfer(sum);
paidToPartners += sum;
emit ToSalesPartner(salesPartner, partner, sum, now);
}
}
}
/**
* @dev Getting partner percent and calculate earned ether.
*
* @param partner Partner address.
*/
function getPartnerAmount(address partner)
internal
view
returns (uint)
{
uint8 partnerPercent = referralInstance.getPartnerPercent(partner);
if (partnerPercent == 0) {
return 0;
}
return calculateReferral(partnerPercent);
}
/**
* @dev Getting sales partner percent and calculate earned ether.
*
* @param partner sales partner address.
*/
function getSalesPartnerAmount(address partner)
internal
view
returns (uint)
{
uint8 salesPartnerPercent = referralInstance.getSalesPartnerPercent(partner);
if (salesPartnerPercent == 0) {
return 0;
}
return calculateReferral(salesPartnerPercent);
}
/**
* @dev Calculate earned ether by partner percent.
*
* @param percent Partner percent.
*/
function calculateReferral(uint8 percent)
internal
view
returns (uint)
{
uint distribute = ticketPrice * fee / 100;
return distribute * percent / 100;
}
} | Start the new game. Checks ticket price changes, if exists new ticket price the price will be changed. Checks game status changes, if exists request for changing game status game status will be changed./ | function startGame() internal {
require(isActive);
game = block.number;
if (newPrice != 0) {
ticketPrice = newPrice;
newPrice = 0;
}
if (toogleStatus) {
isActive = !isActive;
toogleStatus = false;
}
emit Game(game, now);
}
| 4,804,676 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
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'
// 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");
}
}
}
// 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 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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
} else if (signature.length == 64) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (governor) that can be granted exclusive access to
* specific functions.
*
* By default, the governor account will be the one that deploys the contract. This
* can later be changed with {transferGovernorship}.
*
*/
contract Governed is Context, Initializable {
address public governor;
address private proposedGovernor;
event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor);
/**
* @dev Initializes the contract setting the deployer as the initial governor.
*/
constructor() {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev If inheriting child is using proxy then child contract can use
* _initializeGoverned() function to initialization this contract
*/
function _initializeGoverned() internal initializer {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev Throws if called by any account other than the governor.
*/
modifier onlyGovernor {
require(governor == _msgSender(), "not-the-governor");
_;
}
/**
* @dev Transfers governorship of the contract to a new account (`proposedGovernor`).
* Can only be called by the current owner.
*/
function transferGovernorship(address _proposedGovernor) external onlyGovernor {
require(_proposedGovernor != address(0), "proposed-governor-is-zero");
proposedGovernor = _proposedGovernor;
}
/**
* @dev Allows new governor to accept governorship of the contract.
*/
function acceptGovernorship() external {
require(proposedGovernor == _msgSender(), "not-the-proposed-governor");
emit UpdatedGovernor(governor, proposedGovernor);
governor = proposedGovernor;
proposedGovernor = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier whenPaused() {
require(paused, "not-paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "not-shutdown");
_;
}
/// @dev Pause contract operations, if contract is not paused.
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
/// @dev Unpause contract operations, allow only if contract is paused and not shutdown.
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
/// @dev Shutdown contract operations, if not already shutdown.
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
/// @dev Open contract operations, if contract is in shutdown state
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_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;
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.3;
interface IPoolAccountant {
function decreaseDebt(address _strategy, uint256 _decreaseBy) external;
function migrateStrategy(address _old, address _new) external;
function reportEarning(
address _strategy,
uint256 _profit,
uint256 _loss,
uint256 _payback
)
external
returns (
uint256 _actualPayback,
uint256 _creditLine,
uint256 _interestFee
);
function reportLoss(address _strategy, uint256 _loss) external;
function availableCreditLimit(address _strategy) external view returns (uint256);
function excessDebt(address _strategy) external view returns (uint256);
function getStrategies() external view returns (address[] memory);
function getWithdrawQueue() external view returns (address[] memory);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio,
uint256 _externalDepositFee
);
function externalDepositFee() external view returns (uint256);
function totalDebt() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalDebtRatio() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolRewards {
/// Emitted after reward added
event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration);
/// Emitted whenever any user claim rewards
event RewardPaid(address indexed user, address indexed rewardToken, uint256 reward);
/// Emitted after adding new rewards token into rewardTokens array
event RewardTokenAdded(address indexed rewardToken, address[] existingRewardTokens);
function claimReward(address) external;
function notifyRewardAmount(
address _rewardToken,
uint256 _rewardAmount,
uint256 _rewardDuration
) external;
function notifyRewardAmount(
address[] memory _rewardTokens,
uint256[] memory _rewardAmounts,
uint256[] memory _rewardDurations
) external;
function updateReward(address) external;
function claimable(address _account)
external
view
returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts);
function lastTimeRewardApplicable(address _rewardToken) external view returns (uint256);
function rewardForDuration()
external
view
returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration);
function rewardPerToken()
external
view
returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function keepers() external view returns (address[] memory);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function totalValueCurrent() external returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/// @title Errors library
library Errors {
string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0
string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0
string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0
string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length
string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee
string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed
string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set
string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep
string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow
string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero
string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS
string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again
string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list
string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list
string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required
string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required
string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool
string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS
string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0
string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// solhint-disable reason-string, no-empty-blocks
///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20
abstract contract PoolERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the decimals of the token. default to 18
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev Returns total supply of the token.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
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 {}
function _setName(string memory name_) internal {
_name = name_;
}
function _setSymbol(string memory symbol_) internal {
_symbol = symbol_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./PoolERC20.sol";
///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit
// solhint-disable var-name-mixedcase
abstract contract PoolERC20Permit is PoolERC20, IERC20Permit {
bytes32 private constant _EIP712_VERSION = keccak256(bytes("1"));
bytes32 private constant _EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private _CACHED_DOMAIN_SEPARATOR;
bytes32 private _HASHED_NAME;
uint256 private _CACHED_CHAIN_ID;
/**
* @dev See {IERC20Permit-nonces}.
*/
mapping(address => uint256) public override nonces;
/**
* @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`.
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function _initializePermit(string memory name_) internal {
_HASHED_NAME = keccak256(bytes(name_));
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
uint256 _currentNonce = nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline));
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
nonces[owner] = _currentNonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() private view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./PoolERC20Permit.sol";
import "./PoolStorage.sol";
import "./Errors.sol";
import "../Governed.sol";
import "../Pausable.sol";
import "../interfaces/vesper/IPoolAccountant.sol";
import "../interfaces/vesper/IPoolRewards.sol";
/// @title Holding pool share token
// solhint-disable no-empty-blocks
abstract contract PoolShareToken is Initializable, PoolERC20Permit, Governed, Pausable, ReentrancyGuard, PoolStorageV2 {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
uint256 public constant MAX_BPS = 10_000;
event Deposit(address indexed owner, uint256 shares, uint256 amount);
event Withdraw(address indexed owner, uint256 shares, uint256 amount);
// We are using constructor to initialize implementation with basic details
constructor(
string memory _name,
string memory _symbol,
address _token
) PoolERC20(_name, _symbol) {
// 0x0 is acceptable as has no effect on functionality
token = IERC20(_token);
}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializePool(
string memory _name,
string memory _symbol,
address _token
) internal initializer {
require(_token != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
_setName(_name);
_setSymbol(_symbol);
_initializePermit(_name);
token = IERC20(_token);
// Assuming token supports 18 or less decimals
uint256 _decimals = IERC20Metadata(_token).decimals();
decimalConversionFactor = 10**(18 - _decimals);
}
/**
* @notice Deposit ERC20 tokens and receive pool shares depending on the current share price.
* @param _amount ERC20 token amount.
*/
function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused {
_updateRewards(_msgSender());
_deposit(_amount);
}
/**
* @notice Deposit ERC20 tokens and claim rewards if any
* @param _amount ERC20 token amount.
*/
function depositAndClaim(uint256 _amount) external virtual nonReentrant whenNotPaused {
_depositAndClaim(_amount);
}
/**
* @notice Deposit ERC20 tokens with permit aka gasless approval.
* @param _amount ERC20 token amount.
* @param _deadline The time at which signature will expire
* @param _v The recovery byte of the signature
* @param _r Half of the ECDSA signature pair
* @param _s Half of the ECDSA signature pair
*/
function depositWithPermit(
uint256 _amount,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external virtual nonReentrant whenNotPaused {
IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s);
_deposit(_amount);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector.
* Burn remaining shares and return collateral.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
_updateRewards(_msgSender());
_withdraw(_shares);
}
/**
* @notice Withdraw collateral and claim rewards if any
* @param _shares Pool shares. It will be in 18 decimals.
*/
function withdrawAndClaim(uint256 _shares) external virtual nonReentrant whenNotShutdown {
_withdrawAndClaim(_shares);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* @dev Burn shares and return collateral. No withdraw fee will be assessed
* when this function is called. Only some white listed address can call this function.
* @param _shares Pool shares. It will be in 18 decimals.
* This function is deprecated, normal withdraw will check for whitelisted address
*/
function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
require(_feeWhitelist.contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS);
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
_withdrawWithoutFee(_shares);
}
/**
* @notice Transfer tokens to multiple recipient
* @dev Address array and amount array are 1:1 and are in order.
* @param _recipients array of recipient addresses
* @param _amounts array of token amounts
* @return true/false
*/
function multiTransfer(address[] calldata _recipients, uint256[] calldata _amounts) external returns (bool) {
require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH);
for (uint256 i = 0; i < _recipients.length; i++) {
require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED);
}
return true;
}
/**
* @notice Get price per share
* @dev Return value will be in token defined decimals.
*/
function pricePerShare() public view returns (uint256) {
if (totalSupply() == 0 || totalValue() == 0) {
return convertFrom18(1e18);
}
return (totalValue() * 1e18) / totalSupply();
}
/**
* @notice Calculate how much shares user will get for given amount. Also return externalDepositFee if any.
* @param _amount Collateral amount
* @return _shares Amount of share that user will get
*/
function calculateMintage(uint256 _amount) public view returns (uint256 _shares) {
require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT);
uint256 _externalDepositFee = (_amount * IPoolAccountant(poolAccountant).externalDepositFee()) / MAX_BPS;
_shares = _calculateShares(_amount - _externalDepositFee);
}
/// @dev Convert from 18 decimals to token defined decimals.
function convertFrom18(uint256 _amount) public view virtual returns (uint256) {
return _amount / decimalConversionFactor;
}
/// @dev Returns the token stored in the pool. It will be in token defined decimals.
function tokensHere() public view virtual returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Returns sum of token locked in other contracts and token stored in the pool.
* Default tokensHere. It will be in token defined decimals.
*/
function totalValue() public view virtual returns (uint256);
/**
* @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue
* @param _share Pool share in 18 decimals
*/
function _beforeBurning(uint256 _share) internal virtual returns (uint256) {}
/**
* @dev Hook that is called just after burning tokens.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterBurning(uint256 _amount) internal virtual returns (uint256) {
token.safeTransfer(_msgSender(), _amount);
return _amount;
}
/**
* @dev Hook that is called just before minting new tokens. To be used i.e.
* if the deposited amount is to be transferred from user to this contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _beforeMinting(uint256 _amount) internal virtual {
token.safeTransferFrom(_msgSender(), address(this), _amount);
}
/**
* @dev Hook that is called just after minting new tokens. To be used i.e.
* if the deposited amount is to be transferred to a different contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterMinting(uint256 _amount) internal virtual {}
/// @dev Update pool rewards of sender and receiver during transfer.
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).updateReward(sender);
IPoolRewards(poolRewards).updateReward(recipient);
}
super._transfer(sender, recipient, amount);
}
/**
* @dev Calculate shares to mint/burn based on the current share price and given amount.
* @param _amount Collateral amount in collateral token defined decimals.
* @return share amount in 18 decimal
*/
function _calculateShares(uint256 _amount) internal view returns (uint256) {
uint256 _share = ((_amount * 1e18) / pricePerShare());
return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share;
}
/// @notice claim rewards of account
function _claimRewards(address _account) internal {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).claimReward(_account);
}
}
function _updateRewards(address _account) internal {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).updateReward(_account);
}
}
/// @dev Deposit incoming token and mint pool token i.e. shares.
function _deposit(uint256 _amount) internal virtual {
uint256 _shares = calculateMintage(_amount);
_beforeMinting(_amount);
_mint(_msgSender(), _shares);
_afterMinting(_amount);
emit Deposit(_msgSender(), _shares, _amount);
}
/// @dev Deposit token and claim rewards if any
function _depositAndClaim(uint256 _amount) internal {
_claimRewards(_msgSender());
_deposit(_amount);
}
/// @dev Burns shares and returns the collateral value, after fee, of those.
function _withdraw(uint256 _shares) internal virtual {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
if (withdrawFee == 0 || _feeWhitelist.contains(_msgSender())) {
_withdrawWithoutFee(_shares);
} else {
uint256 _fee = (_shares * withdrawFee) / MAX_BPS;
uint256 _sharesAfterFee = _shares - _fee;
uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee);
// Recalculate proportional share on actual amount withdrawn
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
// Using convertFrom18() to avoid dust.
// Pool share token is in 18 decimal and collateral token decimal is <=18.
// Anything less than 10**(18-collateralTokenDecimal) is dust.
if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) {
// Recalculate shares to withdraw, fee and shareAfterFee
_shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee);
_fee = _shares - _proportionalShares;
_sharesAfterFee = _proportionalShares;
}
_burn(_msgSender(), _sharesAfterFee);
_transfer(_msgSender(), feeCollector, _fee);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
/// @dev Withdraw collateral and claim rewards if any
function _withdrawAndClaim(uint256 _shares) internal {
_claimRewards(_msgSender());
_withdraw(_shares);
}
/// @dev Burns shares and returns the collateral value of those.
function _withdrawWithoutFee(uint256 _shares) internal {
uint256 _amountWithdrawn = _beforeBurning(_shares);
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) {
_shares = _proportionalShares;
}
_burn(_msgSender(), _shares);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol";
contract PoolStorageV1 {
IERC20 public token; // Collateral token
address public poolAccountant; // PoolAccountant address
address public poolRewards; // PoolRewards contract address
address private feeWhitelistObsolete; // Obsolete in favor of AddressSet of feeWhitelist
address private keepersObsolete; // Obsolete in favor of AddressSet of keepers
address private maintainersObsolete; // Obsolete in favor of AddressSet of maintainers
address public feeCollector; // Fee collector address
uint256 public withdrawFee; // Withdraw fee for this pool
uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals
bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH
}
contract PoolStorageV2 is PoolStorageV1 {
EnumerableSet.AddressSet internal _feeWhitelist; // List of addresses whitelisted for feeless withdraw
EnumerableSet.AddressSet internal _keepers; // List of keeper addresses
EnumerableSet.AddressSet internal _maintainers; // List of maintainer addresses
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./VPoolBase.sol";
//solhint-disable no-empty-blocks
contract VPool is VPoolBase {
string public constant VERSION = "4.0.0";
constructor(
string memory _name,
string memory _symbol,
address _token
) VPoolBase(_name, _symbol, _token) {}
function initialize(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant
) public initializer {
_initializeBase(_name, _symbol, _token, _poolAccountant);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./Errors.sol";
import "./PoolShareToken.sol";
import "../interfaces/vesper/IStrategy.sol";
abstract contract VPoolBase is PoolShareToken {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards);
event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee);
constructor(
string memory _name,
string memory _symbol,
address _token // solhint-disable-next-line no-empty-blocks
) PoolShareToken(_name, _symbol, _token) {}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializeBase(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant
) internal initializer {
require(_poolAccountant != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
_initializePool(_name, _symbol, _token);
_initializeGoverned();
require(_keepers.add(_msgSender()), Errors.ADD_IN_LIST_FAILED);
require(_maintainers.add(_msgSender()), Errors.ADD_IN_LIST_FAILED);
poolAccountant = _poolAccountant;
}
modifier onlyKeeper() {
require(_keepers.contains(_msgSender()), "not-a-keeper");
_;
}
modifier onlyMaintainer() {
require(_maintainers.contains(_msgSender()), "not-a-maintainer");
_;
}
////////////////////////////// Only Governor //////////////////////////////
/**
* @notice Migrate existing strategy to new strategy.
* @dev Migrating strategy aka old and new strategy should be of same type.
* @param _old Address of strategy being migrated
* @param _new Address of new strategy
*/
function migrateStrategy(address _old, address _new) external onlyGovernor {
require(
IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this),
Errors.INVALID_STRATEGY
);
IPoolAccountant(poolAccountant).migrateStrategy(_old, _new);
IStrategy(_old).migrate(_new);
}
/**
* @notice Update fee collector address for this pool
* @param _newFeeCollector new fee collector address
*/
function updateFeeCollector(address _newFeeCollector) external onlyGovernor {
require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedFeeCollector(feeCollector, _newFeeCollector);
feeCollector = _newFeeCollector;
}
/**
* @notice Update pool rewards address for this pool
* @param _newPoolRewards new pool rewards address
*/
function updatePoolRewards(address _newPoolRewards) external onlyGovernor {
require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedPoolRewards(poolRewards, _newPoolRewards);
poolRewards = _newPoolRewards;
}
/**
* @notice Update withdraw fee for this pool
* @dev Format: 1500 = 15% fee, 100 = 1%
* @param _newWithdrawFee new withdraw fee
*/
function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor {
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED);
emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee);
withdrawFee = _newWithdrawFee;
}
///////////////////////////// Only Keeper ///////////////////////////////
function pause() external onlyKeeper {
_pause();
}
function unpause() external onlyKeeper {
_unpause();
}
function shutdown() external onlyKeeper {
_shutdown();
}
function open() external onlyKeeper {
_open();
}
/// @notice Return list of whitelisted addresses
function feeWhitelist() external view returns (address[] memory) {
return _feeWhitelist.values();
}
function isFeeWhitelisted(address _address) external view returns (bool) {
return _feeWhitelist.contains(_address);
}
/**
* @notice Add given address in feeWhitelist.
* @param _addressToAdd Address to add in feeWhitelist.
*/
function addToFeeWhitelist(address _addressToAdd) external onlyKeeper {
require(_feeWhitelist.add(_addressToAdd), Errors.ADD_IN_LIST_FAILED);
}
/**
* @notice Remove given address from feeWhitelist.
* @param _addressToRemove Address to remove from feeWhitelist.
*/
function removeFromFeeWhitelist(address _addressToRemove) external onlyKeeper {
require(_feeWhitelist.remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED);
}
/// @notice Return list of keepers
function keepers() external view returns (address[] memory) {
return _keepers.values();
}
function isKeeper(address _address) external view returns (bool) {
return _keepers.contains(_address);
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyKeeper {
require(_keepers.add(_keeperAddress), Errors.ADD_IN_LIST_FAILED);
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyKeeper {
require(_keepers.remove(_keeperAddress), Errors.REMOVE_FROM_LIST_FAILED);
}
/// @notice Return list of maintainers
function maintainers() external view returns (address[] memory) {
return _maintainers.values();
}
function isMaintainer(address _address) external view returns (bool) {
return _maintainers.contains(_address);
}
/**
* @notice Add given address in maintainers list.
* @param _maintainerAddress maintainer address to add.
*/
function addMaintainer(address _maintainerAddress) external onlyKeeper {
require(_maintainers.add(_maintainerAddress), Errors.ADD_IN_LIST_FAILED);
}
/**
* @notice Remove given address from maintainers list.
* @param _maintainerAddress maintainer address to remove.
*/
function removeMaintainer(address _maintainerAddress) external onlyKeeper {
require(_maintainers.remove(_maintainerAddress), Errors.REMOVE_FROM_LIST_FAILED);
}
///////////////////////////////////////////////////////////////////////////
/**
* @dev Strategy call this in regular interval.
* @param _profit yield generated by strategy. Strategy get performance fee on this amount
* @param _loss Reduce debt ,also reduce debtRatio, increase loss in record.
* @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount.
* when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately.
*/
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) public virtual {
(uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) =
IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback);
uint256 _totalPayback = _profit + _actualPayback;
// After payback, if strategy has credit line available then send more fund to strategy
// If payback is more than available credit line then get fund from strategy
if (_totalPayback < _creditLine) {
token.safeTransfer(_msgSender(), _creditLine - _totalPayback);
} else if (_totalPayback > _creditLine) {
token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine);
}
// Mint interest fee worth shares at feeCollector address
if (_interestFee != 0) {
_mint(IStrategy(_msgSender()).feeCollector(), _calculateShares(_interestFee));
}
}
/**
* @notice Report loss outside of rebalance activity.
* @dev Some strategies pay deposit fee thus realizing loss at deposit.
* For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool.
* Strategy may want report this loss instead of waiting for next rebalance.
* @param _loss Loss that strategy want to report
*/
function reportLoss(uint256 _loss) external {
if (_loss != 0) {
IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss);
}
}
/**
* @dev Transfer given ERC20 token to feeCollector
* @param _fromToken Token address to sweep
*/
function sweepERC20(address _fromToken) external virtual onlyKeeper {
require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP);
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this)));
}
/**
* @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool
* @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy.
* credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance)
* when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool
* @param _strategy Strategy address
*/
function availableCreditLimit(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy);
}
/**
* @notice Debt above current debt limit
* @param _strategy Address of strategy
*/
function excessDebt(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).excessDebt(_strategy);
}
function getStrategies() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getStrategies();
}
function getWithdrawQueue() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getWithdrawQueue();
}
function strategy(address _strategy)
public
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio,
uint256 _externalDepositFee
)
{
return IPoolAccountant(poolAccountant).strategy(_strategy);
}
/// @notice Get total debt of pool
function totalDebt() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt();
}
/**
* @notice Get total debt of given strategy
* @param _strategy Strategy address
*/
function totalDebtOf(address _strategy) public view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtOf(_strategy);
}
/// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool
function totalDebtRatio() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtRatio();
}
/// @dev Returns total value of vesper pool, in terms of collateral token
function totalValue() public view override returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt() + tokensHere();
}
function _withdrawCollateral(uint256 _amount) internal virtual {
// Withdraw amount from queue
uint256 _debt;
uint256 _balanceAfter;
uint256 _balanceBefore;
uint256 _amountWithdrawn;
uint256 _totalAmountWithdrawn;
address[] memory _withdrawQueue = getWithdrawQueue();
uint256 _len = _withdrawQueue.length;
for (uint256 i; i < _len; i++) {
uint256 _amountNeeded = _amount - _totalAmountWithdrawn;
address _strategy = _withdrawQueue[i];
_debt = totalDebtOf(_strategy);
if (_debt == 0) {
continue;
}
if (_amountNeeded > _debt) {
// Should not withdraw more than current debt of strategy.
_amountNeeded = _debt;
}
_balanceBefore = tokensHere();
//solhint-disable no-empty-blocks
try IStrategy(_strategy).withdraw(_amountNeeded) {} catch {
continue;
}
_balanceAfter = tokensHere();
_amountWithdrawn = _balanceAfter - _balanceBefore;
// Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded
IPoolAccountant(poolAccountant).decreaseDebt(_strategy, _amountWithdrawn);
_totalAmountWithdrawn += _amountWithdrawn;
if (_totalAmountWithdrawn >= _amount) {
// withdraw done
break;
}
}
}
/**
* @dev Before burning hook.
* withdraw amount from strategies
*/
function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) {
uint256 _amount = (_share * pricePerShare()) / 1e18;
uint256 _balanceNow = tokensHere();
if (_amount > _balanceNow) {
_withdrawCollateral(_amount - _balanceNow);
_balanceNow = tokensHere();
}
actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount;
require(actualWithdrawn != 0, Errors.INVALID_COLLATERAL_AMOUNT);
}
} | Add given address in feeWhitelist. _addressToAdd Address to add in feeWhitelist./ | function addToFeeWhitelist(address _addressToAdd) external onlyKeeper {
require(_feeWhitelist.add(_addressToAdd), Errors.ADD_IN_LIST_FAILED);
}
| 416,793 |
./partial_match/1/0x8E220b9D3F09C56DC306Cab1d7644b846066cC43/sources/PToken.sol | See {IERC777-operatorBurn}. Emits {Burned} and {IERC20-Transfer} events./ | function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(_msgSender(), account, amount, data, operatorData);
}
| 3,609,900 |
./full_match/137/0xBc344BA056D5878590c7Eb81693ce954B943146E/sources/contracts/zap/staking/SolidZapStaker.sol | @inheritdoc ISolidZapStaker | function stakeETH(
address hypervisor,
bytes calldata swap1,
bytes calldata swap2,
uint minShares,
address zapRecipient
) external payable nonReentrant returns (uint) {
_wrap(weth, msg.value);
return _stakeDoubleSwap(weth, msg.value, hypervisor, swap1, swap2, minShares, zapRecipient);
}
| 3,766,341 |
./full_match/11155111/0x56192215791b87F4a3AdE556cd6BC81108D95768/sources/contracts/QapturProjectFactory.sol | Deploy a new qland smart contract revert if something gone wrong | function deployQlandSmartContract(
string calldata _name,
string calldata _uri
) internal returns (address) {
if (qlandMarketplaceAddress == address(0)) {
qlandMarketplaceAddress = stateContract
.getQlandMarketplaceAddress();
}
require(
qlandMarketplaceAddress != address(0),
"Marketplace address is not configured"
);
bytes memory bytecode = type(QapturLand).creationCode;
bytes32 salt = keccak256(abi.encodePacked(_name));
address addr;
assembly {
addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
QapturLand projectContract = QapturLand(addr);
return (addr);
}
| 3,815,882 |
./partial_match/42/0x75ECFeB9f1EAf43eAa354D0c4211D0BCB917E8f6/sources/MasterChefStageOne.sol | View function to see pending NTSs on frontend. | function pendingNTS(uint256 _pid, address _user) external view override returns (uint256 _pending, uint256 _potential) {
UserInfo storage user = userInfo[_pid][_user];
if(user.amount == 0){
return (0, 0);
}
PoolInfo storage pool = poolInfo[_pid];
uint256 userStartTerm = getPassedTerm(user.startBlock).add(1);
uint256 lastTerm = (block.number > stageOneDepositEndBlock)? STAGE_ONE_TERM_COUNT: getPassedTerm(block.number);
uint256 totalWithdrawWeight = userDividendWeight.add(devDividendWeight);
PoolDividendInfo storage poolTermInfo = pool.termInfo[userStartTerm];
if(userStartTerm > lastTerm){
_potential = poolTermInfo.termDividend.add(getRewardToken(pool.lastDividendHeight + 1, block.number))
.mul(user.termInfo[userStartTerm].modifiedWeight)
.div(poolTermInfo.termTotalWeight)
.mul(userDividendWeight)
.div(totalWithdrawWeight);
return (0, _potential);
}
while(userStartTerm <= lastTerm){
_pending = poolTermInfo.termDividend.mul(user.termInfo[userStartTerm].modifiedWeight).div(poolTermInfo.termTotalWeight).add(_pending);
userStartTerm ++;
poolTermInfo = pool.termInfo[userStartTerm];
}
uint256 lastTermEndBlock = startBlock.add(lastTerm.mul(STAGE_ONE_TERM_BLOCK)) - 1;
if(pool.lastDividendHeight < lastTermEndBlock){
_pending = _pending.add(getRewardToken(pool.lastDividendHeight + 1, lastTermEndBlock)
.mul(user.termInfo[lastTerm].modifiedWeight)
.div(poolTermInfo.termTotalWeight));
}
_pending = _pending.mul(userDividendWeight).div(totalWithdrawWeight);
if(userStartTerm <= STAGE_ONE_TERM_COUNT){
_potential = poolTermInfo.termDividend.add(getRewardToken(lastTermEndBlock + 1 > pool.lastDividendHeight? lastTermEndBlock + 1: pool.lastDividendHeight + 1, block.number))
.mul(user.termInfo[userStartTerm].modifiedWeight).div(poolTermInfo.termTotalWeight)
.mul(userDividendWeight)
.div(totalWithdrawWeight);
}
}
| 8,954,348 |
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions". This adds two-phase
* ownership control to OpenZeppelin's Ownable class. In this model, the original owner
* designates a new owner but does not actually transfer ownership. The new owner then accepts
* ownership and completes the transfer.
*/
contract Ownable {
address public owner;
address public pendingOwner;
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;
pendingOwner = address(0);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @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));
pendingOwner = _newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title CarbonDollarStorage
* @notice Contains necessary storage contracts for CarbonDollar (FeeSheet and StablecoinWhitelist).
*/
contract CarbonDollarStorage is Ownable {
using SafeMath for uint256;
/**
Mappings
*/
/* fees for withdrawing to stablecoin, in tenths of a percent) */
mapping (address => uint256) public fees;
/** @dev Units for fees are always in a tenth of a percent */
uint256 public defaultFee;
/* is the token address referring to a stablecoin/whitelisted token? */
mapping (address => bool) public whitelist;
/**
Events
*/
event DefaultFeeChanged(uint256 oldFee, uint256 newFee);
event FeeChanged(address indexed stablecoin, uint256 oldFee, uint256 newFee);
event FeeRemoved(address indexed stablecoin, uint256 oldFee);
event StablecoinAdded(address indexed stablecoin);
event StablecoinRemoved(address indexed stablecoin);
/** @notice Sets the default fee for burning CarbonDollar into a whitelisted stablecoin.
@param _fee The default fee.
*/
function setDefaultFee(uint256 _fee) public onlyOwner {
uint256 oldFee = defaultFee;
defaultFee = _fee;
if (oldFee != defaultFee)
emit DefaultFeeChanged(oldFee, _fee);
}
/** @notice Set a fee for burning CarbonDollar into a stablecoin.
@param _stablecoin Address of a whitelisted stablecoin.
@param _fee the fee.
*/
function setFee(address _stablecoin, uint256 _fee) public onlyOwner {
uint256 oldFee = fees[_stablecoin];
fees[_stablecoin] = _fee;
if (oldFee != _fee)
emit FeeChanged(_stablecoin, oldFee, _fee);
}
/** @notice Remove the fee for burning CarbonDollar into a particular kind of stablecoin.
@param _stablecoin Address of stablecoin.
*/
function removeFee(address _stablecoin) public onlyOwner {
uint256 oldFee = fees[_stablecoin];
fees[_stablecoin] = 0;
if (oldFee != 0)
emit FeeRemoved(_stablecoin, oldFee);
}
/** @notice Add a token to the whitelist.
@param _stablecoin Address of the new stablecoin.
*/
function addStablecoin(address _stablecoin) public onlyOwner {
whitelist[_stablecoin] = true;
emit StablecoinAdded(_stablecoin);
}
/** @notice Removes a token from the whitelist.
@param _stablecoin Address of the ex-stablecoin.
*/
function removeStablecoin(address _stablecoin) public onlyOwner {
whitelist[_stablecoin] = false;
emit StablecoinRemoved(_stablecoin);
}
/**
* @notice Compute the fee that will be charged on a "burn" operation.
* @param _amount The amount that will be traded.
* @param _stablecoin The stablecoin whose fee will be used.
*/
function computeStablecoinFee(uint256 _amount, address _stablecoin) public view returns (uint256) {
uint256 fee = fees[_stablecoin];
return computeFee(_amount, fee);
}
/**
* @notice Compute the fee that will be charged on a "burn" operation.
* @param _amount The amount that will be traded.
* @param _fee The fee that will be charged, in tenths of a percent.
*/
function computeFee(uint256 _amount, uint256 _fee) public pure returns (uint256) {
return _amount.mul(_fee).div(1000);
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title PermissionedTokenStorage
* @notice a PermissionedTokenStorage is constructed by setting Regulator, BalanceSheet, and AllowanceSheet locations.
* Once the storages are set, they cannot be changed.
*/
contract PermissionedTokenStorage is Ownable {
using SafeMath for uint256;
/**
Storage
*/
mapping (address => mapping (address => uint256)) public allowances;
mapping (address => uint256) public balances;
uint256 public totalSupply;
function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].add(_value);
}
function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].sub(_value);
}
function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = _value;
}
function addBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = _value;
}
function addTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.add(_value);
}
function subTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.sub(_value);
}
function setTotalSupply(uint256 _value) public onlyOwner {
totalSupply = _value;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Lockable
* @dev Base contract which allows children to lock certain methods from being called by clients.
* Locked methods are deemed unsafe by default, but must be implemented in children functionality to adhere by
* some inherited standard, for example.
*/
contract Lockable is Ownable {
// Events
event Unlocked();
event Locked();
// Fields
bool public isMethodEnabled = false;
// Modifiers
/**
* @dev Modifier that disables functions by default unless they are explicitly enabled
*/
modifier whenUnlocked() {
require(isMethodEnabled);
_;
}
// Methods
/**
* @dev called by the owner to enable method
*/
function unlock() onlyOwner public {
isMethodEnabled = true;
emit Unlocked();
}
/**
* @dev called by the owner to disable method, back to normal state
*/
function lock() onlyOwner public {
isMethodEnabled = false;
emit Locked();
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism. Identical to OpenZeppelin version
* except that it uses local Ownable contract
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/
contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
}
/**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/
contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
}
/**
* @title PermissionedToken
* @notice A permissioned token that enables transfers, withdrawals, and deposits to occur
* if and only if it is approved by an on-chain Regulator service. PermissionedToken is an
* ERC-20 smart contract representing ownership of securities and overrides the
* transfer, burn, and mint methods to check with the Regulator.
*/
contract PermissionedToken is ERC20, Pausable, Lockable {
using SafeMath for uint256;
/** Events */
event DestroyedBlacklistedTokens(address indexed account, uint256 amount);
event ApprovedBlacklistedAddressSpender(address indexed owner, address indexed spender, uint256 value);
event Mint(address indexed to, uint256 value);
event Burn(address indexed burner, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event ChangedRegulator(address indexed oldRegulator, address indexed newRegulator );
PermissionedTokenStorage public tokenStorage;
Regulator public regulator;
/**
* @dev create a new PermissionedToken with a brand new data storage
**/
constructor (address _regulator) public {
regulator = Regulator(_regulator);
tokenStorage = new PermissionedTokenStorage();
}
/** Modifiers **/
/** @notice Modifier that allows function access to be restricted based on
* whether the regulator allows the message sender to execute that function.
**/
modifier requiresPermission() {
require (regulator.hasUserPermission(msg.sender, msg.sig), "User does not have permission to execute function");
_;
}
/** @notice Modifier that checks whether or not a transferFrom operation can
* succeed with the given _from and _to address. See transferFrom()'s documentation for
* more details.
**/
modifier transferFromConditionsRequired(address _from, address _to) {
require(!regulator.isBlacklistedUser(_to), "Recipient cannot be blacklisted");
// If the origin user is blacklisted, the transaction can only succeed if
// the message sender is a user that has been approved to transfer
// blacklisted tokens out of this address.
bool is_origin_blacklisted = regulator.isBlacklistedUser(_from);
// Is the message sender a person with the ability to transfer tokens out of a blacklisted account?
bool sender_can_spend_from_blacklisted_address = regulator.isBlacklistSpender(msg.sender);
require(!is_origin_blacklisted || sender_can_spend_from_blacklisted_address, "Origin cannot be blacklisted if spender is not an approved blacklist spender");
_;
}
/** @notice Modifier that checks whether a user is blacklisted.
* @param _user The address of the user to check.
**/
modifier userBlacklisted(address _user) {
require(regulator.isBlacklistedUser(_user), "User must be blacklisted");
_;
}
/** @notice Modifier that checks whether a user is not blacklisted.
* @param _user The address of the user to check.
**/
modifier userNotBlacklisted(address _user) {
require(!regulator.isBlacklistedUser(_user), "User must not be blacklisted");
_;
}
/** Functions **/
/**
* @notice Allows user to mint if they have the appropriate permissions. User generally
* must have minting authority.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _to The address of the receiver
* @param _amount The number of tokens to mint
*/
function mint(address _to, uint256 _amount) public userNotBlacklisted(_to) requiresPermission whenNotPaused {
_mint(_to, _amount);
}
/**
* @notice Remove CUSD from supply
* @param _amount The number of tokens to burn
* @return `true` if successful and `false` if unsuccessful
*/
function burn(uint256 _amount) userNotBlacklisted(msg.sender) public whenNotPaused {
_burn(msg.sender, _amount);
}
/**
* @notice Implements ERC-20 standard approve function. Locked or disabled by default to protect against
* double spend attacks. To modify allowances, clients should call safer increase/decreaseApproval methods.
* Upon construction, all calls to approve() will revert unless this contract owner explicitly unlocks approve()
*/
function approve(address _spender, uint256 _value)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused whenUnlocked returns (bool) {
tokenStorage.setAllowance(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* @notice increaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using increaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @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 userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_increaseApproval(_spender, _addedValue, msg.sender);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @notice decreaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using decreaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @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 userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_decreaseApproval(_spender, _subtractedValue, msg.sender);
return true;
}
/**
* @notice Destroy the tokens owned by a blacklisted account. This function can generally
* only be called by a central authority.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _who Account to destroy tokens from. Must be a blacklisted account.
*/
function destroyBlacklistedTokens(address _who, uint256 _amount) public userBlacklisted(_who) whenNotPaused requiresPermission {
tokenStorage.subBalance(_who, _amount);
tokenStorage.subTotalSupply(_amount);
emit DestroyedBlacklistedTokens(_who, _amount);
}
/**
* @notice Allows a central authority to approve themselves as a spender on a blacklisted account.
* By default, the allowance is set to the balance of the blacklisted account, so that the
* authority has full control over the account balance.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _blacklistedAccount The blacklisted account.
*/
function approveBlacklistedAddressSpender(address _blacklistedAccount)
public userBlacklisted(_blacklistedAccount) whenNotPaused requiresPermission {
tokenStorage.setAllowance(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount));
emit ApprovedBlacklistedAddressSpender(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount));
}
/**
* @notice Initiates a "send" operation towards another user. See `transferFrom` for details.
* @param _to The address of the receiver. This user must not be blacklisted, or else the tranfer
* will fail.
* @param _amount The number of tokens to transfer
*
* @return `true` if successful
*/
function transfer(address _to, uint256 _amount) public userNotBlacklisted(_to) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_transfer(_to, msg.sender, _amount);
return true;
}
/**
* @notice Initiates a transfer operation between address `_from` and `_to`. Requires that the
* message sender is an approved spender on the _from account.
* @dev When implemented, it should use the transferFromConditionsRequired() modifier.
* @param _to The address of the recipient. This address must not be blacklisted.
* @param _from The address of the origin of funds. This address _could_ be blacklisted, because
* a regulator may want to transfer tokens out of a blacklisted account, for example.
* In order to do so, the regulator would have to add themselves as an approved spender
* on the account via `addBlacklistAddressSpender()`, and would then be able to transfer tokens out of it.
* @param _amount The number of tokens to transfer
* @return `true` if successful
*/
function transferFrom(address _from, address _to, uint256 _amount)
public whenNotPaused transferFromConditionsRequired(_from, _to) returns (bool) {
require(_amount <= allowance(_from, msg.sender),"not enough allowance to transfer");
_transfer(_to, _from, _amount);
tokenStorage.subAllowance(_from, msg.sender, _amount);
return true;
}
/**
*
* @dev Only the token owner can change its regulator
* @param _newRegulator the new Regulator for this token
*
*/
function setRegulator(address _newRegulator) public onlyOwner {
require(_newRegulator != address(regulator), "Must be a new regulator");
require(AddressUtils.isContract(_newRegulator), "Cannot set a regulator storage to a non-contract address");
address old = address(regulator);
regulator = Regulator(_newRegulator);
emit ChangedRegulator(old, _newRegulator);
}
/**
* @notice If a user is blacklisted, they will have the permission to
* execute this dummy function. This function effectively acts as a marker
* to indicate that a user is blacklisted. We include this function to be consistent with our
* invariant that every possible userPermission (listed in Regulator) enables access to a single
* PermissionedToken function. Thus, the 'BLACKLISTED' permission gives access to this function
* @return `true` if successful
*/
function blacklisted() public view requiresPermission returns (bool) {
return true;
}
/**
* ERC20 standard functions
*/
function allowance(address owner, address spender) public view returns (uint256) {
return tokenStorage.allowances(owner, spender);
}
function totalSupply() public view returns (uint256) {
return tokenStorage.totalSupply();
}
function balanceOf(address _addr) public view returns (uint256) {
return tokenStorage.balances(_addr);
}
/** Internal functions **/
function _decreaseApproval(address _spender, uint256 _subtractedValue, address _tokenHolder) internal {
uint256 oldValue = allowance(_tokenHolder, _spender);
if (_subtractedValue > oldValue) {
tokenStorage.setAllowance(_tokenHolder, _spender, 0);
} else {
tokenStorage.subAllowance(_tokenHolder, _spender, _subtractedValue);
}
emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender));
}
function _increaseApproval(address _spender, uint256 _addedValue, address _tokenHolder) internal {
tokenStorage.addAllowance(_tokenHolder, _spender, _addedValue);
emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender));
}
function _burn(address _tokensOf, uint256 _amount) internal {
require(_tokensOf != address(0),"burner address cannot be 0x0");
require(_amount <= balanceOf(_tokensOf),"not enough balance to burn");
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
tokenStorage.subBalance(_tokensOf, _amount);
tokenStorage.subTotalSupply(_amount);
emit Burn(_tokensOf, _amount);
emit Transfer(_tokensOf, address(0), _amount);
}
function _mint(address _to, uint256 _amount) internal {
require(_to != address(0),"to address cannot be 0x0");
tokenStorage.addTotalSupply(_amount);
tokenStorage.addBalance(_to, _amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
function _transfer(address _to, address _from, uint256 _amount) internal {
require(_to != address(0),"to address cannot be 0x0");
require(_amount <= balanceOf(_from),"not enough balance to transfer");
tokenStorage.addBalance(_to, _amount);
tokenStorage.subBalance(_from, _amount);
emit Transfer(_from, _to, _amount);
}
}
/**
* @title WhitelistedToken
* @notice A WhitelistedToken can be converted into CUSD and vice versa. Converting a WT into a CUSD
* is the only way for a user to obtain CUSD. This is a permissioned token, so users have to be
* whitelisted before they can do any mint/burn/convert operation.
*/
contract WhitelistedToken is PermissionedToken {
address public cusdAddress;
/**
Events
*/
event CUSDAddressChanged(address indexed oldCUSD, address indexed newCUSD);
event MintedToCUSD(address indexed user, uint256 amount);
event ConvertedToCUSD(address indexed user, uint256 amount);
/**
* @notice Constructor sets the regulator contract and the address of the
* CarbonUSD meta-token contract. The latter is necessary in order to make transactions
* with the CarbonDollar smart contract.
*/
constructor(address _regulator, address _cusd) public PermissionedToken(_regulator) {
// base class fields
regulator = Regulator(_regulator);
cusdAddress = _cusd;
}
/**
* @notice Mints CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD
* into the CarbonUSD contract's escrow account.
* @param _to The address of the receiver
* @param _amount The number of CarbonTokens to mint to user
*/
function mintCUSD(address _to, uint256 _amount) public requiresPermission whenNotPaused userNotBlacklisted(_to) {
return _mintCUSD(_to, _amount);
}
/**
* @notice Converts WT0 to CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD
* into the CarbonUSD contract's escrow account.
* @param _amount The number of Whitelisted tokens to convert
*/
function convertWT(uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(balanceOf(msg.sender) >= _amount, "Conversion amount should be less than balance");
_burn(msg.sender, _amount);
_mintCUSD(msg.sender, _amount);
emit ConvertedToCUSD(msg.sender, _amount);
}
/**
* @notice Change the cusd address.
* @param _cusd the cusd address.
*/
function setCUSDAddress(address _cusd) public onlyOwner {
require(_cusd != address(cusdAddress), "Must be a new cusd address");
require(AddressUtils.isContract(_cusd), "Must be an actual contract");
address oldCUSD = address(cusdAddress);
cusdAddress = _cusd;
emit CUSDAddressChanged(oldCUSD, _cusd);
}
function _mintCUSD(address _to, uint256 _amount) internal {
require(_to != cusdAddress, "Cannot mint to CarbonUSD contract"); // This is to prevent Carbon Labs from printing money out of thin air!
CarbonDollar(cusdAddress).mint(_to, _amount);
_mint(cusdAddress, _amount);
emit MintedToCUSD(_to, _amount);
}
}
/**
* @title CarbonDollar
* @notice The main functionality for the CarbonUSD metatoken. (CarbonUSD is just a proxy
* that implements this contract's functionality.) This is a permissioned token, so users have to be
* whitelisted before they can do any mint/burn/convert operation. Every CarbonDollar token is backed by one
* whitelisted stablecoin credited to the balance of this contract address.
*/
contract CarbonDollar is PermissionedToken {
// Events
event ConvertedToWT(address indexed user, uint256 amount);
event BurnedCUSD(address indexed user, uint256 feedAmount, uint256 chargedFee);
/**
Modifiers
*/
modifier requiresWhitelistedToken() {
require(isWhitelisted(msg.sender), "Sender must be a whitelisted token contract");
_;
}
CarbonDollarStorage public tokenStorage_CD;
/** CONSTRUCTOR
* @dev Passes along arguments to base class.
*/
constructor(address _regulator) public PermissionedToken(_regulator) {
// base class override
regulator = Regulator(_regulator);
tokenStorage_CD = new CarbonDollarStorage();
}
/**
* @notice Add new stablecoin to whitelist.
* @param _stablecoin Address of stablecoin contract.
*/
function listToken(address _stablecoin) public onlyOwner whenNotPaused {
tokenStorage_CD.addStablecoin(_stablecoin);
}
/**
* @notice Remove existing stablecoin from whitelist.
* @param _stablecoin Address of stablecoin contract.
*/
function unlistToken(address _stablecoin) public onlyOwner whenNotPaused {
tokenStorage_CD.removeStablecoin(_stablecoin);
}
/**
* @notice Change fees associated with going from CarbonUSD to a particular stablecoin.
* @param stablecoin Address of the stablecoin contract.
* @param _newFee The new fee rate to set, in tenths of a percent.
*/
function setFee(address stablecoin, uint256 _newFee) public onlyOwner whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
tokenStorage_CD.setFee(stablecoin, _newFee);
}
/**
* @notice Remove fees associated with going from CarbonUSD to a particular stablecoin.
* The default fee still may apply.
* @param stablecoin Address of the stablecoin contract.
*/
function removeFee(address stablecoin) public onlyOwner whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
tokenStorage_CD.removeFee(stablecoin);
}
/**
* @notice Change the default fee associated with going from CarbonUSD to a WhitelistedToken.
* This fee amount is used if the fee for a WhitelistedToken is not specified.
* @param _newFee The new fee rate to set, in tenths of a percent.
*/
function setDefaultFee(uint256 _newFee) public onlyOwner whenNotPaused {
tokenStorage_CD.setDefaultFee(_newFee);
}
/**
* @notice Mints CUSD on behalf of a user. Note the use of the "requiresWhitelistedToken"
* modifier; this means that minting authority does not belong to any personal account;
* only whitelisted token contracts can call this function. The intended functionality is that the only
* way to mint CUSD is for the user to actually burn a whitelisted token to convert into CUSD
* @param _to User to send CUSD to
* @param _amount Amount of CarbonUSD to mint.
*/
function mint(address _to, uint256 _amount) public requiresWhitelistedToken whenNotPaused {
_mint(_to, _amount);
}
/**
* @notice user can convert CarbonUSD umbrella token into a whitelisted stablecoin.
* @param stablecoin represents the type of coin the users wishes to receive for burning carbonUSD
* @param _amount Amount of CarbonUSD to convert.
* we credit the user's account at the sender address with the _amount minus the percentage fee we want to charge.
*/
function convertCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
WhitelistedToken whitelisted = WhitelistedToken(stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
// Send back WT0 to calling user, but with a fee reduction.
// Transfer this fee into the whitelisted token's CarbonDollar account (this contract's address)
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(msg.sender, _amount);
require(whitelisted.transfer(msg.sender, feedAmount));
whitelisted.burn(chargedFee);
_mint(address(this), chargedFee);
emit ConvertedToWT(msg.sender, _amount);
}
/**
* @notice burns CarbonDollar and an equal amount of whitelisted stablecoin from the CarbonDollar address
* @param stablecoin Represents the stablecoin whose fee will be charged.
* @param _amount Amount of CarbonUSD to burn.
*/
function burnCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
_burnCarbonDollar(msg.sender, stablecoin, _amount);
}
/**
* @notice release collected CUSD fees to owner
* @param _amount Amount of CUSD to release
* @return `true` if successful
*/
function releaseCarbonDollar(uint256 _amount) public onlyOwner returns (bool) {
require(_amount <= balanceOf(address(this)),"not enough balance to transfer");
tokenStorage.subBalance(address(this), _amount);
tokenStorage.addBalance(msg.sender, _amount);
emit Transfer(address(this), msg.sender, _amount);
return true;
}
/** Computes fee percentage associated with burning into a particular stablecoin.
* @param stablecoin The stablecoin whose fee will be charged. Precondition: is a whitelisted
* stablecoin.
* @return The fee that will be charged. If the stablecoin's fee is not set, the default
* fee is returned.
*/
function computeFeeRate(address stablecoin) public view returns (uint256 feeRate) {
if (getFee(stablecoin) > 0)
feeRate = getFee(stablecoin);
else
feeRate = getDefaultFee();
}
/**
* @notice Check if whitelisted token is whitelisted
* @return bool true if whitelisted, false if not
**/
function isWhitelisted(address _stablecoin) public view returns (bool) {
return tokenStorage_CD.whitelist(_stablecoin);
}
/**
* @notice Get the fee associated with going from CarbonUSD to a specific WhitelistedToken.
* @param stablecoin The stablecoin whose fee is being checked.
* @return The fee associated with the stablecoin.
*/
function getFee(address stablecoin) public view returns (uint256) {
return tokenStorage_CD.fees(stablecoin);
}
/**
* @notice Get the default fee associated with going from CarbonUSD to a specific WhitelistedToken.
* @return The default fee for stablecoin trades.
*/
function getDefaultFee() public view returns (uint256) {
return tokenStorage_CD.defaultFee();
}
function _burnCarbonDollar(address _tokensOf, address _stablecoin, uint256 _amount) internal {
require(isWhitelisted(_stablecoin), "Stablecoin must be whitelisted prior to burning");
WhitelistedToken whitelisted = WhitelistedToken(_stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
// Burn user's CUSD, but with a fee reduction.
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(_stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(_tokensOf, _amount);
whitelisted.burn(_amount);
_mint(address(this), chargedFee);
emit BurnedCUSD(_tokensOf, feedAmount, chargedFee); // Whitelisted trust account should send user feedAmount USD
}
}
/**
* @title MetaToken
* @notice Extends the CarbonDollar token by providing functionality for users to interact with
* the permissioned token contract without needing to pay gas fees. MetaToken will perform the
* exact same actions as a normal CarbonDollar, but first it will validate a signature of the
* hash of the parameters and ecrecover() a signature to prove the signer so everything is still
* cryptographically backed. Then, instead of doing actions on behalf of msg.sender,
* it will move the signer’s tokens. Finally, we can also wrap in a token reward to incentivise the relayer.
* @notice inspiration from @austingriffith and @PhABCD for leading the meta-transaction innovations
*/
contract MetaToken is CarbonDollar {
/**
* @dev create a new CarbonDollar with a brand new data storage
**/
constructor (address _regulator) CarbonDollar(_regulator) public {
}
/**
Storage
*/
mapping (address => uint256) public replayNonce;
/**
ERC20 Metadata
*/
string public constant name = "CUSD";
string public constant symbol = "CUSD";
uint8 public constant decimals = 18;
/** Functions **/
/**
* @dev Verify and broadcast an increaseApproval() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @notice increaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using increaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaIncreaseApproval(address _spender, uint256 _addedValue, bytes _signature, uint256 _nonce, uint256 _reward)
public userNotBlacklisted(_spender) whenNotPaused returns (bool) {
bytes32 metaHash = metaApproveHash(_spender, _addedValue, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( _reward <= balanceOf(signer),"not enough balance to reward relayer");
_increaseApproval(_spender, _addedValue, signer);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Verify and broadcast a transfer() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @param _to The address of the receiver. This user must not be blacklisted, or else the transfer
* will fail.
* @param _amount The number of tokens to transfer
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaTransfer(address _to, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public userNotBlacklisted(_to) whenNotPaused returns (bool) {
bytes32 metaHash = metaTransferHash(_to, _amount, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( (_amount + _reward) <= balanceOf(signer),"not enough balance to transfer and reward relayer");
_transfer(_to, signer, _amount);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Verify and broadcast a burnCarbonDollar() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @param _stablecoin Represents the stablecoin that is backing the active CUSD.
* @param _amount The number of tokens to transfer
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaBurnCarbonDollar(address _stablecoin, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public whenNotPaused returns (bool) {
bytes32 metaHash = metaBurnHash(_stablecoin, _amount, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( (_amount + _reward) <= balanceOf(signer),"not enough balance to burn and reward relayer");
_burnCarbonDollar(signer, _stablecoin, _amount);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Return hash containing all of the information about the transfer() metatransaction
* @param _to The address of the transfer receiver
* @param _amount The number of tokens to transfer
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaTransferHash(address _to, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaTransfer", _to, _amount, _nonce, _reward));
}
/**
* @notice Return hash containing all of the information about the increaseApproval() metatransaction
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaApproveHash(address _spender, uint256 _addedValue, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaIncreaseApproval", _spender, _addedValue, _nonce, _reward));
}
/**
* @notice Return hash containing all of the information about the burnCarbonDollar() metatransaction
* @param _stablecoin Represents the stablecoin that is backing the active CUSD.
* @param _amount The number of tokens to burn
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaBurnHash(address _stablecoin, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaBurnCarbonDollar", _stablecoin, _amount, _nonce, _reward));
}
/**
* @dev Recover signer of original metatransaction
* @param _hash derived bytes32 metatransaction signature, which should be the same as the parameter _signature
* @param _signature bytes metatransaction signature, the signature is generated using web3.eth.sign()
* @return address of hash signer
*/
function _getSigner(bytes32 _hash, bytes _signature) internal pure returns (address){
bytes32 r;
bytes32 s;
uint8 v;
if (_signature.length != 65) {
return address(0);
}
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return address(0);
} else {
return ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s);
}
}
} | user can convert CarbonUSD umbrella token into a whitelisted stablecoin. stablecoin represents the type of coin the users wishes to receive for burning carbonUSD _amount Amount of CarbonUSD to convert. we credit the user's account at the sender address with the _amount minus the percentage fee we want to charge./ Send back WT0 to calling user, but with a fee reduction. Transfer this fee into the whitelisted token's CarbonDollar account (this contract's address) | function convertCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
WhitelistedToken whitelisted = WhitelistedToken(stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(msg.sender, _amount);
require(whitelisted.transfer(msg.sender, feedAmount));
whitelisted.burn(chargedFee);
_mint(address(this), chargedFee);
emit ConvertedToWT(msg.sender, _amount);
}
| 1,020,298 |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
@title ERC827 interface, an extension of ERC20 token standard
Interface of a ERC827 token, following the ERC20 standard with extra
methods to transfer value and data and execute calls in transfers and
approvals.
*/
contract ERC827 is ERC20 {
function approve( address _spender, uint256 _value, bytes _data ) public returns (bool);
function transfer( address _to, uint256 _value, bytes _data ) public returns (bool);
function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool);
}
contract AccessControl {
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
interface RandomInterface {
function maxRandom() public returns (uint256 randomNumber);
function random(uint256 _upper) public returns (uint256 randomNumber);
function randomNext(uint256 _seed, uint256 _upper) public pure returns(uint256, uint256);
}
contract PlayerInterface {
function checkOwner(address _owner, uint32[11] _ids) public view returns (bool);
function queryPlayerType(uint32[11] _ids) public view returns (uint32[11] playerTypes);
function queryPlayer(uint32 _id) public view returns (uint16[8]);
function queryPlayerUnAwakeSkillIds(uint32[11] _playerIds) public view returns (uint16[11] playerUnAwakeSkillIds);
function tournamentResult(uint32[3][11][32] _playerAwakeSkills) public;
}
/// @title TournamentBase contract for BS.
contract TournamentBase {
event Enter(address user, uint256 fee, uint8 defenceCount, uint8 midfieldCount, uint8 forwardCount, uint32[11] playerIds);
event CancelEnter(address user);
event StartCompetition(uint256 id, uint256 time, address[32] users);
event CancelCompetition(uint256 id);
event Sponsor(address user, uint256 competitionId, address target, uint256 fee);
event Ball(uint256 competitionId, uint8 gameIndex, address user, uint32 playerId, uint8 time);
event Battle(uint256 competitionId, uint8 gameIndex, address userA, uint8 scoreA, address userB, uint8 scoreB);
event Champion(uint256 competitionId, address user);
event EndCompetition(uint256 competitionId, uint256 totalReward, uint256 totalWeight, uint8[32] teamWinCounts);
event Reward(uint256 competitionId, address target, uint8 winCount, address user, uint256 sponsorAmount, uint256 amount);
uint256 public minEnterFee = 100*(10**18);
//uint256 public constant sponsorInterval = 1 hours;
uint32[5] public operatingCosts = [100, 100, 120, 160, 240];
struct Team {
uint256 fees;
uint32[11] playerIds;
uint16[11] playerAtkWeights;
uint128 index;
TeamStatus status;
uint16 attack;
uint16 defense;
uint16 stamina;
}
enum TeamStatus { Normal, Enter, Competition }
enum PlayerPosType { GoalKeeper, Defence, Midfield, Forward }
enum CompetitionStatus { None, Start, End, Cancel }
struct SponsorsInfo {
mapping(address => uint256) sponsors;
uint256 totalAmount;
}
struct CompetitionInfo {
uint256 totalReward;
uint256 totalWeight;
uint8[32] teamWinCounts;
address[32] users;
//uint64 startTime;
CompetitionStatus status;
uint8 userCount;
}
mapping (address => Team) public userToTeam;
address[] teamUserInfo;
uint256 nextCompetitionId;
mapping (uint256 => CompetitionInfo) public competitionInfos;
mapping (uint256 => mapping (uint256 => SponsorsInfo)) public sponsorInfos;
PlayerInterface bsCoreContract;
RandomInterface randomContract;
ERC827 public joyTokenContract;
}
contract PlayerSkill {
enum SkillType { Undefined, WinGamesInOneTournament, ScoreInOneGame, ScoreInOneTournament,
FanOfPlayerID, ChampionWithPlayerID, HattricksInOneTuournament, Terminator,
LonelyKiller, VictoryBringer, Saver, ICanDoBetterTournament, ICanDoBetter,
LearnFromFailure, LearnFromFailureTournament}
struct SkillConfig {
SkillType skillType;
uint32 target;
uint8 addAttri;
}
function _getSkill(uint16 skillId) internal pure returns(uint16, uint16) {
return (skillId >> 2, (skillId & 0x03));
}
function triggerSkill(uint32[11][32] _playerIds, uint8[32] _teamWinCounts, uint8[4][31] _gameScores,
uint8[3][3][31] _gameBalls, uint8[5][11][32] _playerBalls, uint16[11][32] _playerUnAwakeSkillIds,
uint32[3][11][32] _playerAwakeSkills) internal pure {
SkillConfig[35] memory skillConfigs = _getSkillConfigs();
for (uint8 i = 0; i < 32; i++) {
for (uint8 j = 0; j < 11; j++) {
uint16 skillId = _playerUnAwakeSkillIds[i][j];
if (skillId > 0) {
uint16 addAttriType;
(skillId, addAttriType) = _getSkill(skillId);
SkillConfig memory skillConfig = skillConfigs[skillId];
if (skillConfig.skillType != SkillType.Undefined) {
if (_triggerSkill(skillConfig, i, j, _teamWinCounts, _gameScores, _gameBalls, _playerBalls)){
_playerAwakeSkills[i][j][0] = _playerIds[i][j];
_playerAwakeSkills[i][j][1] = addAttriType;
_playerAwakeSkills[i][j][2] = skillConfig.addAttri;
}
}
}
}
}
}
function _getSkillConfigs() internal pure returns(SkillConfig[35]) {
return [
SkillConfig(SkillType.Undefined, 0, 0),
SkillConfig(SkillType.WinGamesInOneTournament,1,1),
SkillConfig(SkillType.WinGamesInOneTournament,2,2),
SkillConfig(SkillType.WinGamesInOneTournament,3,3),
SkillConfig(SkillType.WinGamesInOneTournament,4,4),
SkillConfig(SkillType.WinGamesInOneTournament,5,5),
SkillConfig(SkillType.ScoreInOneGame,1,1),
SkillConfig(SkillType.ScoreInOneGame,2,3),
SkillConfig(SkillType.ScoreInOneGame,3,5),
SkillConfig(SkillType.ScoreInOneGame,4,7),
SkillConfig(SkillType.ScoreInOneGame,5,10),
SkillConfig(SkillType.ScoreInOneTournament,10,3),
SkillConfig(SkillType.ScoreInOneTournament,13,4),
SkillConfig(SkillType.ScoreInOneTournament,16,5),
SkillConfig(SkillType.ScoreInOneTournament,20,8),
SkillConfig(SkillType.VictoryBringer,1,4),
SkillConfig(SkillType.VictoryBringer,3,6),
SkillConfig(SkillType.VictoryBringer,5,8),
SkillConfig(SkillType.Saver,1,5),
SkillConfig(SkillType.Saver,3,7),
SkillConfig(SkillType.Saver,5,10),
SkillConfig(SkillType.HattricksInOneTuournament,1,3),
SkillConfig(SkillType.HattricksInOneTuournament,3,6),
SkillConfig(SkillType.HattricksInOneTuournament,5,10),
SkillConfig(SkillType.Terminator,1,5),
SkillConfig(SkillType.Terminator,3,8),
SkillConfig(SkillType.Terminator,5,12),
SkillConfig(SkillType.LonelyKiller,1,5),
SkillConfig(SkillType.LonelyKiller,3,7),
SkillConfig(SkillType.LonelyKiller,5,10),
SkillConfig(SkillType.ICanDoBetterTournament,15,0),
SkillConfig(SkillType.ICanDoBetter,5,0),
SkillConfig(SkillType.LearnFromFailure,5,5),
SkillConfig(SkillType.LearnFromFailureTournament,15,8),
SkillConfig(SkillType.ChampionWithPlayerID,0,5)
];
}
function _triggerSkill(SkillConfig memory _skillConfig, uint8 _teamIndex, uint8 _playerIndex,
uint8[32] _teamWinCounts, uint8[4][31] _gameScores, uint8[3][3][31] _gameBalls,
uint8[5][11][32] _playerBalls) internal pure returns(bool) {
uint256 i;
uint256 accumulateValue = 0;
if (SkillType.WinGamesInOneTournament == _skillConfig.skillType) {
return _teamWinCounts[_teamIndex] >= _skillConfig.target;
}
if (SkillType.ScoreInOneGame == _skillConfig.skillType) {
for (i = 0; i < 5; i++) {
if (_playerBalls[_teamIndex][_playerIndex][i] >= _skillConfig.target) {
return true;
}
}
return false;
}
if (SkillType.ScoreInOneTournament == _skillConfig.skillType) {
for (i = 0; i < 5; i++) {
accumulateValue += _playerBalls[_teamIndex][_playerIndex][i];
}
return accumulateValue >= _skillConfig.target;
}
/* if (SkillType.ChampionWithPlayerID == _skillConfig.skillType) {
if (_teamWinCounts[_teamIndex] >= 5) {
for (i = 0; i < 11; i++) {
if (_playerIds[i] == _skillConfig.target) {
return true;
}
}
}
return false;
} */
if (SkillType.HattricksInOneTuournament == _skillConfig.skillType) {
for (i = 0; i < 5; i++) {
if (_playerBalls[_teamIndex][_playerIndex][i] >= 3) {
accumulateValue++;
}
}
return accumulateValue >= _skillConfig.target;
}
if (SkillType.Terminator == _skillConfig.skillType) {
for (i = 0; i < 31; i++) {
if ((_gameScores[i][0] == _teamIndex && _gameScores[i][2] == _gameScores[i][3]+1)
|| (_gameScores[i][1] == _teamIndex && _gameScores[i][2]+1 == _gameScores[i][3])) {
if (_gameBalls[i][2][1] == _teamIndex && _gameBalls[i][2][2] == _playerIndex) {
accumulateValue++;
}
}
}
return accumulateValue >= _skillConfig.target;
}
if (SkillType.LonelyKiller == _skillConfig.skillType) {
for (i = 0; i < 31; i++) {
if ((_gameScores[i][0] == _teamIndex && _gameScores[i][2] == 1 && _gameScores[i][3] == 0)
|| (_gameScores[i][1] == _teamIndex && _gameScores[i][2] == 0 && _gameScores[i][3] == 1)) {
if (_gameBalls[i][2][1] == _teamIndex && _gameBalls[i][2][2] == _playerIndex) {
accumulateValue++;
}
}
}
return accumulateValue >= _skillConfig.target;
}
if (SkillType.VictoryBringer == _skillConfig.skillType) {
for (i = 0; i < 31; i++) {
if ((_gameScores[i][0] == _teamIndex && _gameScores[i][2] > _gameScores[i][3])
|| (_gameScores[i][1] == _teamIndex && _gameScores[i][2] < _gameScores[i][3])) {
if (_gameBalls[i][0][1] == _teamIndex && _gameBalls[i][0][2] == _playerIndex) {
accumulateValue++;
}
}
}
return accumulateValue >= _skillConfig.target;
}
if (SkillType.Saver == _skillConfig.skillType) {
for (i = 0; i < 31; i++) {
if (_gameBalls[i][1][1] == _teamIndex && _gameBalls[i][1][2] == _playerIndex) {
accumulateValue++;
}
}
return accumulateValue >= _skillConfig.target;
}
if (SkillType.ICanDoBetterTournament == _skillConfig.skillType) {
for (i = 0; i < 31; i++) {
if (_gameScores[i][0] == _teamIndex) {
accumulateValue += _gameScores[i][3];
}
if (_gameScores[i][1] == _teamIndex) {
accumulateValue += _gameScores[i][2];
}
}
return accumulateValue >= _skillConfig.target;
}
if (SkillType.ICanDoBetter == _skillConfig.skillType) {
for (i = 0; i < 31; i++) {
if ((_gameScores[i][0] == _teamIndex && _gameScores[i][3] >= _skillConfig.target)
|| (_gameScores[i][1] == _teamIndex && _gameScores[i][2] >= _skillConfig.target)) {
return true;
}
}
return false;
}
if (SkillType.LearnFromFailure == _skillConfig.skillType && _teamIndex == 0) {
for (i = 0; i < 31; i++) {
if ((_gameScores[i][0] == _teamIndex && _gameScores[i][3] >= _skillConfig.target)
|| (_gameScores[i][1] == _teamIndex && _gameScores[i][2] >= _skillConfig.target)) {
return true;
}
}
return false;
}
if (SkillType.LearnFromFailureTournament == _skillConfig.skillType && _teamIndex == 0) {
for (i = 0; i < 31; i++) {
if (_gameScores[i][0] == _teamIndex) {
accumulateValue += _gameScores[i][3];
}
if (_gameScores[i][1] == _teamIndex) {
accumulateValue += _gameScores[i][2];
}
}
return accumulateValue >= _skillConfig.target;
}
}
}
contract TournamentCompetition is TournamentBase, PlayerSkill {
uint256 constant rangeParam = 90;
uint256 constant halfBattleMinutes = 45;
uint256 constant minBattleMinutes = 2;
struct BattleTeam {
uint16[11] playerAtkWeights;
uint16 attack;
uint16 defense;
uint16 stamina;
}
struct BattleInfo {
uint256 competitionId;
uint256 seed;
uint256 maxRangeA;
uint256 maxRangeB;
uint8[32] teamIndexs;
BattleTeam[32] teamInfos;
uint32[11][32] allPlayerIds;
address addressA;
address addressB;
uint8 roundIndex;
uint8 gameIndex;
uint8 teamLength;
uint8 indexA;
uint8 indexB;
}
function competition(uint256 _competitionId, CompetitionInfo storage ci, uint8[32] _teamWinCounts, uint32[3][11][32] _playerAwakeSkills) internal {
uint8[4][31] memory gameScores;
uint8[3][3][31] memory gameBalls;
uint8[5][11][32] memory playerBalls;
uint16[11][32] memory playerUnAwakeSkillIds;
BattleInfo memory battleInfo;
battleInfo.competitionId = _competitionId;
battleInfo.seed = randomContract.maxRandom();
battleInfo.teamLength = uint8(ci.userCount);
for (uint8 i = 0; i < battleInfo.teamLength; i++) {
battleInfo.teamIndexs[i] = i;
}
_queryBattleInfo(ci, battleInfo, playerUnAwakeSkillIds);
while (battleInfo.teamLength > 1) {
_battle(ci, battleInfo, gameScores, gameBalls, playerBalls);
for (i = 0; i < battleInfo.teamLength; i++) {
_teamWinCounts[battleInfo.teamIndexs[i]] += 1;
}
}
address winner = ci.users[battleInfo.teamIndexs[0]];
Champion(_competitionId, winner);
triggerSkill(battleInfo.allPlayerIds, _teamWinCounts, gameScores,
gameBalls, playerBalls, playerUnAwakeSkillIds, _playerAwakeSkills);
}
function _queryBattleInfo(CompetitionInfo storage ci, BattleInfo memory _battleInfo, uint16[11][32] memory _playerUnAwakeSkillIds) internal view {
for (uint8 i = 0; i < _battleInfo.teamLength; i++) {
Team storage team = userToTeam[ci.users[i]];
_battleInfo.allPlayerIds[i] = team.playerIds;
_battleInfo.teamInfos[i].playerAtkWeights = team.playerAtkWeights;
_battleInfo.teamInfos[i].attack = team.attack;
_battleInfo.teamInfos[i].defense = team.defense;
_battleInfo.teamInfos[i].stamina = team.stamina;
_playerUnAwakeSkillIds[i] = bsCoreContract.queryPlayerUnAwakeSkillIds(_battleInfo.allPlayerIds[i]);
// uint256[3] memory teamAttrs;
// (teamAttrs, _battleInfo.teamInfos[i].playerAtkWeights) = _calTeamAttribute(ci.users[i], team.defenceCount, team.midfieldCount, team.forwardCount, _battleInfo.allPlayerIds[i]);
// _battleInfo.teamInfos[i].attack = uint16(teamAttrs[0]);
// _battleInfo.teamInfos[i].defense = uint16(teamAttrs[1]);
// _battleInfo.teamInfos[i].stamina = uint16(teamAttrs[2]);
}
}
function _battle(CompetitionInfo storage _ci, BattleInfo _battleInfo, uint8[4][31] _gameScores,
uint8[3][3][31] _gameBalls, uint8[5][11][32] _playerBalls) internal {
uint8 resultTeamLength = 0;
for (uint8 i = 0; i < _battleInfo.teamLength; i+=2) {
uint8 a = _battleInfo.teamIndexs[i];
uint8 b = _battleInfo.teamIndexs[i+1];
uint8 scoreA;
uint8 scoreB;
_battleInfo.indexA = a;
_battleInfo.indexB = b;
_battleInfo.addressA = _ci.users[a];
_battleInfo.addressB = _ci.users[b];
(scoreA, scoreB) = _battleTeam(_battleInfo, _gameScores, _gameBalls, _playerBalls);
if (scoreA > scoreB) {
_battleInfo.teamIndexs[resultTeamLength++] = a;
} else {
_battleInfo.teamIndexs[resultTeamLength++] = b;
}
Battle(_battleInfo.competitionId, _battleInfo.gameIndex, _battleInfo.addressA, scoreA, _battleInfo.addressB, scoreB);
}
_battleInfo.roundIndex++;
_battleInfo.teamLength = resultTeamLength;
}
function _battleTeam(BattleInfo _battleInfo, uint8[4][31] _gameScores, uint8[3][3][31] _gameBalls,
uint8[5][11][32] _playerBalls) internal returns (uint8 scoreA, uint8 scoreB) {
BattleTeam memory _aTeam = _battleInfo.teamInfos[_battleInfo.indexA];
BattleTeam memory _bTeam = _battleInfo.teamInfos[_battleInfo.indexB];
_battleInfo.maxRangeA = 5 + rangeParam*_bTeam.defense/_aTeam.attack;
_battleInfo.maxRangeB = 5 + rangeParam*_aTeam.defense/_bTeam.attack;
//DebugRange(_a, _b, _aTeam.attack, _aTeam.defense, _aTeam.stamina, _bTeam.attack, _bTeam.defense, _bTeam.stamina, maxRangeA, maxRangeB);
//DebugRange2(maxRangeA, maxRangeB);
_battleScore(_battleInfo, 0, _playerBalls, _gameBalls);
_battleInfo.maxRangeA = 5 + rangeParam*(uint256(_bTeam.defense)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina)))/(uint256(_aTeam.attack)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina)));
_battleInfo.maxRangeB = 5 + rangeParam*(uint256(_aTeam.defense)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina)))/(uint256(_bTeam.attack)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina)));
//DebugRange2(maxRangeA, maxRangeB);
_battleScore(_battleInfo, halfBattleMinutes, _playerBalls, _gameBalls);
uint8 i = 0;
for (i = 0; i < 11; i++) {
scoreA += _playerBalls[_battleInfo.indexA][i][_battleInfo.roundIndex];
scoreB += _playerBalls[_battleInfo.indexB][i][_battleInfo.roundIndex];
}
if (scoreA == scoreB) {
_battleInfo.maxRangeA = 5 + rangeParam * (uint256(_bTeam.defense)*uint256(_bTeam.stamina)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina))*(100+uint256(_aTeam.stamina)))/(uint256(_aTeam.attack)*uint256(_aTeam.stamina)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina))*(100+uint256(_bTeam.stamina)));
_battleInfo.maxRangeB = 5 + rangeParam * (uint256(_aTeam.defense)*uint256(_aTeam.stamina)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina))*(100+uint256(_bTeam.stamina)))/(uint256(_bTeam.attack)*uint256(_bTeam.stamina)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina))*(100+uint256(_aTeam.stamina)));
//DebugRange2(maxRangeA, maxRangeB);
(scoreA, scoreB) = _battleOvertimeScore(_battleInfo, scoreA, scoreB, _playerBalls, _gameBalls);
}
_gameScores[_battleInfo.gameIndex][0] = _battleInfo.indexA;
_gameScores[_battleInfo.gameIndex][1] = _battleInfo.indexB;
_gameScores[_battleInfo.gameIndex][2] = scoreA;
_gameScores[_battleInfo.gameIndex][3] = scoreB;
_battleInfo.gameIndex++;
}
function _battleScore(BattleInfo _battleInfo, uint256 _timeoffset, uint8[5][11][32] _playerBalls, uint8[3][3][31] _gameBalls) internal {
uint256 _battleMinutes = 0;
while (_battleMinutes < halfBattleMinutes - minBattleMinutes) {
bool isAWin;
uint256 scoreTime;
uint8 index;
(isAWin, scoreTime) = _battleOneScore(_battleInfo);
_battleMinutes += scoreTime;
if (_battleMinutes <= halfBattleMinutes) {
uint8 teamIndex;
address addressWin;
if (isAWin) {
teamIndex = _battleInfo.indexA;
addressWin = _battleInfo.addressA;
} else {
teamIndex = _battleInfo.indexB;
addressWin = _battleInfo.addressB;
}
(_battleInfo.seed, index) = _randBall(_battleInfo.seed, _battleInfo.teamInfos[teamIndex].playerAtkWeights);
uint32 playerId = _battleInfo.allPlayerIds[teamIndex][index];
Ball(_battleInfo.competitionId, _battleInfo.gameIndex+1, addressWin, playerId, uint8(_timeoffset+_battleMinutes));
_playerBalls[teamIndex][index][_battleInfo.roundIndex]++;
_onBall(_battleInfo.gameIndex, teamIndex, index, uint8(_timeoffset+_battleMinutes), _gameBalls);
}
}
}
function _battleOneScore(BattleInfo _battleInfo) internal view returns(bool, uint256) {
uint256 tA;
(_battleInfo.seed, tA) = randomContract.randomNext(_battleInfo.seed, _battleInfo.maxRangeA-minBattleMinutes+1);
tA += minBattleMinutes;
uint256 tB;
(_battleInfo.seed, tB) = randomContract.randomNext(_battleInfo.seed, _battleInfo.maxRangeB-minBattleMinutes+1);
tB += minBattleMinutes;
if (tA < tB || (tA == tB && _battleInfo.seed % 2 == 0)) {
return (true, tA);
} else {
return (false, tB);
}
}
function _randBall(uint256 _seed, uint16[11] memory _atkWeight) internal view returns(uint256, uint8) {
uint256 rand;
(_seed, rand) = randomContract.randomNext(_seed, _atkWeight[_atkWeight.length-1]);
rand += 1;
for (uint8 i = 0; i < _atkWeight.length; i++) {
if (_atkWeight[i] >= rand) {
return (_seed, i);
}
}
}
function _onBall(uint8 _gameIndex, uint8 _teamIndex, uint8 _playerIndex, uint8 _time, uint8[3][3][31] _gameBalls) internal pure {
if (_gameBalls[_gameIndex][0][0] == 0) {
_gameBalls[_gameIndex][0][0] = _time;
_gameBalls[_gameIndex][0][1] = _teamIndex;
_gameBalls[_gameIndex][0][2] = _playerIndex;
}
_gameBalls[_gameIndex][2][0] = _time;
_gameBalls[_gameIndex][2][1] = _teamIndex;
_gameBalls[_gameIndex][2][2] = _playerIndex;
}
function _onOverTimeBall(uint8 _gameIndex, uint8 _teamIndex, uint8 _playerIndex, uint8 _time, uint8[3][3][31] _gameBalls) internal pure {
_gameBalls[_gameIndex][1][0] = _time;
_gameBalls[_gameIndex][1][1] = _teamIndex;
_gameBalls[_gameIndex][1][2] = _playerIndex;
}
function _battleOvertimeScore(BattleInfo _battleInfo, uint8 _scoreA, uint8 _scoreB,
uint8[5][11][32] _playerBalls, uint8[3][3][31] _gameBalls) internal returns(uint8 scoreA, uint8 scoreB) {
bool isAWin;
uint8 index;
uint256 scoreTime;
(isAWin, scoreTime) = _battleOneScore(_battleInfo);
scoreTime = scoreTime % 30 + 90;
uint8 teamIndex;
address addressWin;
if (isAWin) {
teamIndex = _battleInfo.indexA;
scoreA = _scoreA + 1;
scoreB = _scoreB;
addressWin = _battleInfo.addressA;
} else {
teamIndex = _battleInfo.indexB;
scoreA = _scoreA;
scoreB = _scoreB + 1;
addressWin = _battleInfo.addressB;
}
(_battleInfo.seed, index) = _randBall(_battleInfo.seed, _battleInfo.teamInfos[teamIndex].playerAtkWeights);
uint32 playerId = _battleInfo.allPlayerIds[teamIndex][index];
Ball(_battleInfo.competitionId, _battleInfo.gameIndex+1, addressWin, playerId, uint8(scoreTime));
_playerBalls[teamIndex][index][_battleInfo.roundIndex]++;
_onBall(_battleInfo.gameIndex, teamIndex, index, uint8(scoreTime), _gameBalls);
_onOverTimeBall(_battleInfo.gameIndex, teamIndex, index, uint8(scoreTime), _gameBalls);
}
}
contract TournamentInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isTournament() public pure returns (bool);
function isPlayerIdle(address _owner, uint256 _playerId) public view returns (bool);
}
/// @title Tournament contract for BS.
contract TournamentCore is TournamentInterface, TournamentCompetition, AccessControl {
using SafeMath for uint256;
function TournamentCore(address _joyTokenContract, address _bsCoreContract, address _randomAddress, address _CFOAddress) public {
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
cfoAddress = _CFOAddress;
randomContract = RandomInterface(_randomAddress);
joyTokenContract = ERC827(_joyTokenContract);
bsCoreContract = PlayerInterface(_bsCoreContract);
nextCompetitionId = 1;
}
function isTournament() public pure returns (bool) {
return true;
}
function setMinEnterFee(uint256 minFee) external onlyCEO {
minEnterFee = minFee;
}
function setOperatingCost(uint32[5] costs) external onlyCEO {
operatingCosts = costs;
}
function getOperationCost(uint256 teamCount) public view returns (uint256) {
uint256 cost = 0;
if (teamCount <= 2) {
cost = operatingCosts[0];
} else if(teamCount <= 4) {
cost = operatingCosts[1];
} else if(teamCount <= 8) {
cost = operatingCosts[2];
} else if(teamCount <= 16) {
cost = operatingCosts[3];
} else {
cost = operatingCosts[4];
}
return cost.mul(10**18);
}
function isPlayerIdle(address _owner, uint256 _playerId) public view returns (bool) {
Team storage teamInfo = userToTeam[_owner];
for (uint256 i = 0; i < teamInfo.playerIds.length; i++) {
if (teamInfo.playerIds[i] == _playerId) {
return false;
}
}
return true;
}
function enter(address _sender, uint256 _fees, uint8 _defenceCount, uint8 _midfieldCount, uint8 _forwardCount,
uint32[11] _playerIds) external whenNotPaused {
require(_fees >= minEnterFee);
require(_playerIds.length == 11);
require(_defenceCount >= 1 && _defenceCount <= 5);
require(_midfieldCount >= 1 && _midfieldCount <= 5);
require(_forwardCount >= 1 && _forwardCount <= 5);
require(_defenceCount + _midfieldCount + _forwardCount == 10);
require(msg.sender == address(joyTokenContract) || msg.sender == _sender);
require(joyTokenContract.transferFrom(_sender, address(this), _fees));
uint32[11] memory ids = _playerIds;
_insertSortMemory(ids);
for (uint256 i = 0; i < 11 - 1; i++) {
require(ids[i] < ids[i + 1]);
}
require(bsCoreContract.checkOwner(_sender, _playerIds));
uint32[11] memory playerTypes = bsCoreContract.queryPlayerType(_playerIds);
_insertSortMemory(playerTypes);
for (i = 0; i < 11 - 1; i++) {
if (playerTypes[i] > 0) {
break;
}
}
for (; i < 11 - 1; i++) {
require(playerTypes[i] < playerTypes[i + 1]);
}
Team storage teamInfo = userToTeam[_sender];
require(teamInfo.status == TeamStatus.Normal);
enterInner(_sender, _fees, _defenceCount, _midfieldCount, _forwardCount, _playerIds, teamInfo);
Enter(_sender, _fees, _defenceCount, _midfieldCount, _forwardCount, _playerIds);
}
function cancelEnter(address _user) external onlyCOO {
Team storage teamInfo = userToTeam[_user];
require(teamInfo.status == TeamStatus.Enter);
uint256 fees = teamInfo.fees;
uint128 index = teamInfo.index;
require(teamUserInfo[index-1] == _user);
if (index < teamUserInfo.length) {
address user = teamUserInfo[teamUserInfo.length-1];
teamUserInfo[index-1] = user;
userToTeam[user].index = index;
}
teamUserInfo.length--;
delete userToTeam[_user];
require(joyTokenContract.transfer(_user, fees));
CancelEnter(_user);
}
function cancelAllEnter() external onlyCOO {
for (uint256 i = 0; i < teamUserInfo.length; i++) {
address user = teamUserInfo[i];
Team storage teamInfo = userToTeam[user];
require(teamInfo.status == TeamStatus.Enter);
uint256 fees = teamInfo.fees;
// uint256 index = teamInfo.index;
// require(teamUserInfo[index-1] == user);
delete userToTeam[user];
require(joyTokenContract.transfer(user, fees));
CancelEnter(user);
}
teamUserInfo.length = 0;
}
function enterInner(address _sender, uint256 _value, uint8 _defenceCount, uint8 _midfieldCount, uint8 _forwardCount,
uint32[11] _playerIds, Team storage _teamInfo) internal {
uint16[11] memory playerAtkWeights;
uint256[3] memory teamAttrs;
(teamAttrs, playerAtkWeights) = _calTeamAttribute(_defenceCount, _midfieldCount, _forwardCount, _playerIds);
uint256 teamIdx = teamUserInfo.length++;
teamUserInfo[teamIdx] = _sender;
_teamInfo.status = TeamStatus.Enter;
require((teamIdx + 1) == uint256(uint128(teamIdx + 1)));
_teamInfo.index = uint128(teamIdx + 1);
_teamInfo.attack = uint16(teamAttrs[0]);
_teamInfo.defense = uint16(teamAttrs[1]);
_teamInfo.stamina = uint16(teamAttrs[2]);
_teamInfo.playerIds = _playerIds;
_teamInfo.playerAtkWeights = playerAtkWeights;
_teamInfo.fees = _value;
}
function getTeamAttribute(uint8 _defenceCount, uint8 _midfieldCount, uint8 _forwardCount,
uint32[11] _playerIds) external view returns (uint256 attack, uint256 defense, uint256 stamina) {
uint256[3] memory teamAttrs;
uint16[11] memory playerAtkWeights;
(teamAttrs, playerAtkWeights) = _calTeamAttribute(_defenceCount, _midfieldCount, _forwardCount, _playerIds);
attack = teamAttrs[0];
defense = teamAttrs[1];
stamina = teamAttrs[2];
}
function _calTeamAttribute(uint8 _defenceCount, uint8 _midfieldCount, uint8 _forwardCount,
uint32[11] _playerIds) internal view returns (uint256[3] _attrs, uint16[11] _playerAtkWeights) {
uint256[3][11] memory playerAttrs;
_getAttribute(_playerIds, 0, PlayerPosType.GoalKeeper, 1, 0, playerAttrs);
uint8 startIndex = 1;
uint8 i;
for (i = startIndex; i < startIndex + _defenceCount; i++) {
_getAttribute(_playerIds, i, PlayerPosType.Defence, _defenceCount, i - startIndex, playerAttrs);
}
startIndex = startIndex + _defenceCount;
for (i = startIndex; i < startIndex + _midfieldCount; i++) {
_getAttribute(_playerIds, i, PlayerPosType.Midfield, _midfieldCount, i - startIndex, playerAttrs);
}
startIndex = startIndex + _midfieldCount;
for (i = startIndex; i < startIndex + _forwardCount; i++) {
_getAttribute(_playerIds, i, PlayerPosType.Forward, _forwardCount, i - startIndex, playerAttrs);
}
uint16 lastAtkWeight = 0;
for (i = 0; i < _playerIds.length; i++) {
_attrs[0] += playerAttrs[i][0];
_attrs[1] += playerAttrs[i][1];
_attrs[2] += playerAttrs[i][2];
_playerAtkWeights[i] = uint16(lastAtkWeight + playerAttrs[i][0] / 10000);
lastAtkWeight = _playerAtkWeights[i];
}
_attrs[0] /= 10000;
_attrs[1] /= 10000;
_attrs[2] /= 10000;
}
function _getAttribute(uint32[11] _playerIds, uint8 _i, PlayerPosType _type, uint8 _typeSize, uint8 _typeIndex, uint256[3][11] playerAttrs)
internal view {
uint8 xPos;
uint8 yPos;
(xPos, yPos) = _getPos(_type, _typeSize, _typeIndex);
uint16[8] memory a = bsCoreContract.queryPlayer(_playerIds[_i]);
uint256 aWeight;
uint256 dWeight;
(aWeight, dWeight) = _getWeight(yPos);
uint256 sWeight = 100 - aWeight - dWeight;
if (_type == PlayerPosType.GoalKeeper && a[5] == 1) {
dWeight += dWeight;
}
uint256 xWeight = 50;
if (xPos + 1 >= a[4] && xPos <= a[4] + 1) {
xWeight = 100;
}
playerAttrs[_i][0] = (a[1] * aWeight * xWeight);
playerAttrs[_i][1] = (a[2] * dWeight * xWeight);
playerAttrs[_i][2] = (a[3] * sWeight * xWeight);
}
function _getWeight(uint256 yPos) internal pure returns (uint256, uint256) {
if (yPos == 0) {
return (5, 90);
}
if (yPos == 1) {
return (10, 80);
}
if (yPos == 2) {
return (10, 70);
}
if (yPos == 3) {
return (10, 60);
}
if (yPos == 4) {
return (20, 30);
}
if (yPos == 5) {
return (20, 20);
}
if (yPos == 6) {
return (30, 20);
}
if (yPos == 7) {
return (60, 10);
}
if (yPos == 8) {
return (70, 10);
}
if (yPos == 9) {
return (80, 10);
}
}
function _getPos(PlayerPosType _type, uint8 _size, uint8 _index) internal pure returns (uint8, uint8) {
uint8 yPosOffset = 0;
if (_type == PlayerPosType.GoalKeeper) {
return (3, 0);
}
if (_type == PlayerPosType.Midfield) {
yPosOffset += 3;
}
if (_type == PlayerPosType.Forward) {
yPosOffset += 6;
}
if (_size == 5) {
if (_index == 0) {
return (0, 2 + yPosOffset);
}
if (_index == 1) {
return (2, 2 + yPosOffset);
}
if (_index == 2) {
return (4, 2 + yPosOffset);
}
if (_index == 3) {
return (6, 2 + yPosOffset);
} else {
return (3, 3 + yPosOffset);
}
}
if (_size == 4) {
if (_index == 0) {
return (0, 2 + yPosOffset);
}
if (_index == 1) {
return (2, 2 + yPosOffset);
}
if (_index == 2) {
return (4, 2 + yPosOffset);
} else {
return (6, 2 + yPosOffset);
}
}
if (_size == 3) {
if (_index == 0) {
return (1, 2 + yPosOffset);
}
if (_index == 1) {
return (3, 2 + yPosOffset);
} else {
return (5, 2 + yPosOffset);
}
}
if (_size == 2) {
if (_index == 0) {
return (2, 2 + yPosOffset);
} else {
return (4, 2 + yPosOffset);
}
}
if (_size == 1) {
return (3, 2 + yPosOffset);
}
}
///
function start(uint8 _minTeamCount) external onlyCOO whenNotPaused returns (uint256) {
require(teamUserInfo.length >= _minTeamCount);
uint256 competitionId = nextCompetitionId++;
CompetitionInfo storage ci = competitionInfos[competitionId];
//ci.startTime = uint64(now);
ci.status = CompetitionStatus.Start;
//randomize the last _minTeamCount(=32) teams, and take them out.
uint256 i;
uint256 startI = teamUserInfo.length - _minTeamCount;
uint256 j;
require(ci.users.length >= _minTeamCount);
ci.userCount = _minTeamCount;
uint256 seed = randomContract.maxRandom();
address[32] memory selectUserInfo;
for (i = startI; i < teamUserInfo.length; i++) {
selectUserInfo[i - startI] = teamUserInfo[i];
}
i = teamUserInfo.length;
teamUserInfo.length = teamUserInfo.length - _minTeamCount;
for (; i > startI; i--) {
//random from 0 to i
uint256 m;
(seed, m) = randomContract.randomNext(seed, i);
//take out [m], put into competitionInfo
address user;
if (m < startI) {
user = teamUserInfo[m];
} else {
user = selectUserInfo[m-startI];
}
ci.users[j] = user;
Team storage teamInfo = userToTeam[user];
teamInfo.status = TeamStatus.Competition;
teamInfo.index = uint128(competitionId);
SponsorsInfo storage si = sponsorInfos[competitionId][j];
si.sponsors[user] = (si.sponsors[user]).add(teamInfo.fees);
si.totalAmount = (si.totalAmount).add(teamInfo.fees);
//exchange [i - 1] and [m]
if (m != i - 1) {
user = selectUserInfo[i - 1 - startI];
if (m < startI) {
teamUserInfo[m] = user;
userToTeam[user].index = uint128(m + 1);
} else {
selectUserInfo[m - startI] = user;
}
}
//delete [i - 1]
//delete teamUserInfo[i - 1];
j++;
}
StartCompetition(competitionId, now, ci.users);
return competitionId;
}
function sponsor(address _sender, uint256 _competitionId, uint256 _teamIdx, uint256 _count) external whenNotPaused returns (bool) {
require(msg.sender == address(joyTokenContract) || msg.sender == _sender);
CompetitionInfo storage ci = competitionInfos[_competitionId];
require(ci.status == CompetitionStatus.Start);
//require(now < ci.startTime + sponsorInterval);
require(joyTokenContract.transferFrom(_sender, address(this), _count));
require(_teamIdx < ci.userCount);
address targetUser = ci.users[_teamIdx];
Team storage teamInfo = userToTeam[targetUser];
require(teamInfo.status == TeamStatus.Competition);
SponsorsInfo storage si = sponsorInfos[_competitionId][_teamIdx];
si.sponsors[_sender] = (si.sponsors[_sender]).add(_count);
si.totalAmount = (si.totalAmount).add(_count);
Sponsor(_sender, _competitionId, targetUser, _count);
}
function reward(uint256 _competitionId, uint256 _teamIdx) external whenNotPaused {
require(_teamIdx < 32);
SponsorsInfo storage si = sponsorInfos[_competitionId][_teamIdx];
uint256 baseValue = si.sponsors[msg.sender];
require(baseValue > 0);
CompetitionInfo storage ci = competitionInfos[_competitionId];
if (ci.status == CompetitionStatus.Cancel) {
// if (msg.sender == ci.users[_teamIdx]) {
// Team storage teamInfo = userToTeam[msg.sender];
// require(teamInfo.index == _competitionId && teamInfo.status == TeamStatus.Competition);
// delete userToTeam[msg.sender];
// }
delete si.sponsors[msg.sender];
require(joyTokenContract.transfer(msg.sender, baseValue));
} else if (ci.status == CompetitionStatus.End) {
require(ci.teamWinCounts[_teamIdx] > 0);
uint256 rewardValue = baseValue.mul(_getWinCountWeight(ci.teamWinCounts[_teamIdx]));
rewardValue = ci.totalReward.mul(rewardValue) / ci.totalWeight;
rewardValue = rewardValue.add(baseValue);
Reward(_competitionId, ci.users[_teamIdx], ci.teamWinCounts[_teamIdx], msg.sender, baseValue, rewardValue);
delete si.sponsors[msg.sender];
require(joyTokenContract.transfer(msg.sender, rewardValue));
}
}
function competition(uint256 _id) external onlyCOO whenNotPaused {
CompetitionInfo storage ci = competitionInfos[_id];
require(ci.status == CompetitionStatus.Start);
uint8[32] memory teamWinCounts;
uint32[3][11][32] memory playerAwakeSkills;
TournamentCompetition.competition(_id, ci, teamWinCounts, playerAwakeSkills);
_reward(_id, ci, teamWinCounts);
bsCoreContract.tournamentResult(playerAwakeSkills);
for (uint256 i = 0; i < ci.userCount; i++) {
delete userToTeam[ci.users[i]];
}
}
function cancelCompetition(uint256 _id) external onlyCOO {
CompetitionInfo storage ci = competitionInfos[_id];
require(ci.status == CompetitionStatus.Start);
ci.status = CompetitionStatus.Cancel;
for (uint256 i = 0; i < ci.userCount; i++) {
//Team storage teamInfo = userToTeam[ci.users[i]];
//require(teamInfo.index == _id && teamInfo.status == TeamStatus.Competition);
delete userToTeam[ci.users[i]];
}
CancelCompetition(_id);
}
function _getWinCountWeight(uint256 _winCount) internal pure returns (uint256) {
if (_winCount == 0) {
return 0;
}
if (_winCount == 1) {
return 1;
}
if (_winCount == 2) {
return 2;
}
if (_winCount == 3) {
return 3;
}
if (_winCount == 4) {
return 4;
}
if (_winCount >= 5) {
return 8;
}
}
function _reward(uint256 _competitionId, CompetitionInfo storage ci, uint8[32] teamWinCounts) internal {
uint256 totalReward = 0;
uint256 totalWeight = 0;
uint256 i;
for (i = 0; i < ci.userCount; i++) {
if (teamWinCounts[i] == 0) {
totalReward = totalReward.add(sponsorInfos[_competitionId][i].totalAmount);
} else {
uint256 weight = sponsorInfos[_competitionId][i].totalAmount;
weight = weight.mul(_getWinCountWeight(teamWinCounts[i]));
totalWeight = totalWeight.add(weight);
}
}
uint256 cost = getOperationCost(ci.userCount);
uint256 ownerCut;
if (totalReward > cost) {
ownerCut = cost.add((totalReward - cost).mul(3)/100);
totalReward = totalReward.sub(ownerCut);
} else {
ownerCut = totalReward;
totalReward = 0;
}
require(joyTokenContract.transfer(cfoAddress, ownerCut));
ci.totalReward = totalReward;
ci.totalWeight = totalWeight;
ci.teamWinCounts = teamWinCounts;
ci.status = CompetitionStatus.End;
EndCompetition(_competitionId, totalReward, totalWeight, teamWinCounts);
}
function _insertSortMemory(uint32[11] arr) internal pure {
uint256 n = arr.length;
uint256 i;
uint32 key;
uint256 j;
for (i = 1; i < n; i++) {
key = arr[i];
for (j = i; j > 0 && arr[j-1] > key; j--) {
arr[j] = arr[j-1];
}
arr[j] = key;
}
}
function getTeam(address _owner) external view returns (uint256 index, uint256 fees, uint32[11] playerIds,
uint16[11] playerAtkWeights, TeamStatus status, uint16 attack, uint16 defense, uint16 stamina) {
Team storage teamInfo = userToTeam[_owner];
index = teamInfo.index;
fees = teamInfo.fees;
playerIds = teamInfo.playerIds;
playerAtkWeights = teamInfo.playerAtkWeights;
status = teamInfo.status;
attack = teamInfo.attack;
defense = teamInfo.defense;
stamina = teamInfo.stamina;
}
function getCompetitionInfo(uint256 _id) external view returns (uint256 totalReward, uint256 totalWeight,
address[32] users, uint8[32] teamWinCounts, uint8 userCount, CompetitionStatus status) {
CompetitionInfo storage ci = competitionInfos[_id];
//startTime = ci.startTime;
totalReward = ci.totalReward;
totalWeight = ci.totalWeight;
users = ci.users;
teamWinCounts = ci.teamWinCounts;
userCount = ci.userCount;
status = ci.status;
}
} | DebugRange(_a, _b, _aTeam.attack, _aTeam.defense, _aTeam.stamina, _bTeam.attack, _bTeam.defense, _bTeam.stamina, maxRangeA, maxRangeB);DebugRange2(maxRangeA, maxRangeB);DebugRange2(maxRangeA, maxRangeB);DebugRange2(maxRangeA, maxRangeB); | function _battleTeam(BattleInfo _battleInfo, uint8[4][31] _gameScores, uint8[3][3][31] _gameBalls,
uint8[5][11][32] _playerBalls) internal returns (uint8 scoreA, uint8 scoreB) {
BattleTeam memory _aTeam = _battleInfo.teamInfos[_battleInfo.indexA];
BattleTeam memory _bTeam = _battleInfo.teamInfos[_battleInfo.indexB];
_battleInfo.maxRangeA = 5 + rangeParam*_bTeam.defense/_aTeam.attack;
_battleInfo.maxRangeB = 5 + rangeParam*_aTeam.defense/_bTeam.attack;
_battleScore(_battleInfo, 0, _playerBalls, _gameBalls);
_battleInfo.maxRangeA = 5 + rangeParam*(uint256(_bTeam.defense)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina)))/(uint256(_aTeam.attack)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina)));
_battleInfo.maxRangeB = 5 + rangeParam*(uint256(_aTeam.defense)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina)))/(uint256(_bTeam.attack)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina)));
_battleScore(_battleInfo, halfBattleMinutes, _playerBalls, _gameBalls);
uint8 i = 0;
for (i = 0; i < 11; i++) {
scoreA += _playerBalls[_battleInfo.indexA][i][_battleInfo.roundIndex];
scoreB += _playerBalls[_battleInfo.indexB][i][_battleInfo.roundIndex];
}
if (scoreA == scoreB) {
_battleInfo.maxRangeA = 5 + rangeParam * (uint256(_bTeam.defense)*uint256(_bTeam.stamina)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina))*(100+uint256(_aTeam.stamina)))/(uint256(_aTeam.attack)*uint256(_aTeam.stamina)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina))*(100+uint256(_bTeam.stamina)));
_battleInfo.maxRangeB = 5 + rangeParam * (uint256(_aTeam.defense)*uint256(_aTeam.stamina)*uint256(_aTeam.stamina)*(100+uint256(_bTeam.stamina))*(100+uint256(_bTeam.stamina)))/(uint256(_bTeam.attack)*uint256(_bTeam.stamina)*uint256(_bTeam.stamina)*(100+uint256(_aTeam.stamina))*(100+uint256(_aTeam.stamina)));
(scoreA, scoreB) = _battleOvertimeScore(_battleInfo, scoreA, scoreB, _playerBalls, _gameBalls);
}
_gameScores[_battleInfo.gameIndex][0] = _battleInfo.indexA;
_gameScores[_battleInfo.gameIndex][1] = _battleInfo.indexB;
_gameScores[_battleInfo.gameIndex][2] = scoreA;
_gameScores[_battleInfo.gameIndex][3] = scoreB;
_battleInfo.gameIndex++;
}
| 5,523,898 |
./full_match/1/0xF507733f260a42bB2c8108dE87B7B0Ce5826A9cD/sources/src/fixed-strike/FixedStrikeOptionTeller.sol | Some fancy math to convert a uint into a string, courtesy of Provable Things. Updated to work with solc 0.8.0. https:github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol | function _uint2str(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
| 3,858,776 |
contract SHA3_512 {
function hash(uint64[8]) pure public returns(uint32[16]) {}
}
contract TeikhosBounty {
SHA3_512 public sha3_512 = SHA3_512(0xbD6361cC42fD113ED9A9fdbEDF7eea27b325a222); // Mainnet: 0xbD6361cC42fD113ED9A9fdbEDF7eea27b325a222,
// Rinkeby: 0x2513CF99E051De22cEB6cf5f2EaF0dc4065c8F1f
struct Commit {
uint timestamp;
bytes signature;
}
mapping(address => Commit) public commitment;
struct Solution {
uint timestamp;
bytes publicKey; // The key that solves the bounty, empty until the correct key has been submitted with authenticate()
bytes32 msgHash;
}
Solution public isSolved;
struct Winner {
uint timestamp;
address winner;
}
Winner public winner;
enum State { Commit, Reveal, Payout }
modifier inState(State _state)
{
if(_state == State.Commit) { require(isSolved.timestamp == 0); }
if(_state == State.Reveal) { require(isSolved.timestamp != 0 && now < isSolved.timestamp + 7 days); }
if(_state == State.Payout) { require(isSolved.timestamp != 0 && now > isSolved.timestamp + 7 days); }
_;
}
// Proof-of-public-key in format 2xbytes32, to support xor operator and ecrecover r, s v format
struct PoPk {
bytes32 half1;
bytes32 half2;
}
PoPk public proof_of_public_key;
function TeikhosBounty() public { // Constructor funciton, runs when contract is deployed
proof_of_public_key.half1 = hex"ad683919450048215e7c10c3dc3ffca5939ec8f48c057cfe385c7c6f8b754aa7";
proof_of_public_key.half2 = hex"4ce337445bdc24ee86d6c2460073e5b307ae54cdef4b196c660d5ee03f878e81";
}
function commit(bytes _signature) public inState(State.Commit) {
require(commitment[msg.sender].timestamp == 0);
commitment[msg.sender].signature = _signature;
commitment[msg.sender].timestamp = now;
}
function reveal() public inState(State.Reveal) returns (bool success) {
bytes memory signature = commitment[msg.sender].signature;
require(signature.length != 0);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature,0x20))
s := mload(add(signature,0x40))
v := byte(0, mload(add(signature, 96)))
}
if (v < 27) v += 27;
if(ecrecover(isSolved.msgHash, v, r, s) == msg.sender) {
success = true; // The correct solution was submitted
if(winner.timestamp == 0 || commitment[msg.sender].timestamp < winner.timestamp) {
winner.winner = msg.sender;
winner.timestamp = commitment[msg.sender].timestamp;
}
}
delete commitment[msg.sender];
return success;
}
function reward() public inState(State.Payout) {
selfdestruct(winner.winner);
}
function authenticate(bytes _publicKey) public inState(State.Commit) {
bytes memory keyHash = getHash(_publicKey);
// Split hash of public key in 2xbytes32, to support xor operator and ecrecover r, s v format
bytes32 hash1;
bytes32 hash2;
assembly {
hash1 := mload(add(keyHash,0x20))
hash2 := mload(add(keyHash,0x40))
}
// Use xor (reverse cipher) to get signature in r, s v format
bytes32 r = proof_of_public_key.half1 ^ hash1;
bytes32 s = proof_of_public_key.half2 ^ hash2;
// Get msgHash for use with ecrecover
bytes32 msgHash = keccak256("\x19Ethereum Signed Message:\n64", _publicKey);
// Get address from public key
address signer = address(keccak256(_publicKey));
// The value v is not known, try both 27 and 28
if(ecrecover(msgHash, 27, r, s) == signer || ecrecover(msgHash, 28, r, s) == signer ) {
isSolved.timestamp = now;
isSolved.publicKey = _publicKey;
isSolved.msgHash = msgHash;
require(reveal() == true); // The correct solution has to have been commited,
// prevents funds from getting locked in the contract
}
}
// A separate method getHash() for converting bytes to uint64[8], which is done since the EVM cannot pass bytes between contracts
// The SHA3_512 logic is in a separate contract to make it easier to read, that contract could be audited on its own, and so on
function getHash(bytes _message) view internal returns (bytes messageHash) {
// Use SHA3_512 library to get a sha3_512 hash of public key
uint64[8] memory input;
// The evm is big endian, have to reverse the bytes
bytes memory reversed = new bytes(64);
for(uint i = 0; i < 64; i++) {
reversed[i] = _message[63 - i];
}
for(i = 0; i < 8; i++) {
bytes8 oneEigth;
// Load 8 byte from reversed public key at position 32 + i * 8
assembly {
oneEigth := mload(add(reversed, add(32, mul(i, 8))))
}
input[7 - i] = uint64(oneEigth);
}
uint32[16] memory output = sha3_512.hash(input);
bytes memory toBytes = new bytes(64);
for(i = 0; i < 16; i++) {
bytes4 oneSixteenth = bytes4(output[15 - i]);
// Store 4 byte in keyHash at position 32 + i * 4
assembly { mstore(add(toBytes, add(32, mul(i, 4))), oneSixteenth) }
}
messageHash = new bytes(64);
for(i = 0; i < 64; i++) {
messageHash[i] = toBytes[63 - i];
}
}
// Make it possible to send ETH to the contract with "payable" on the fallback function
function() public payable {}
} | Constructor funciton, runs when contract is deployed | function TeikhosBounty() public { | 4,815,575 |
./full_match/11155111/0x4Ac3832d773FE6B6dcC8EB6241B83212F1a55096/sources/contracts/discovery/GNS.sol | Returns account and sequence ID for a legacy subgraph (created before subgraph NFTs). _subgraphID Subgraph ID return account Account that created the subgraph (or 0 if it's not a legacy subgraph) return seqID Sequence number for the subgraph/ | function getLegacySubgraphKey(uint256 _subgraphID)
public
view
override
returns (address account, uint256 seqID)
{
LegacySubgraphKey storage legacySubgraphKey = legacySubgraphKeys[_subgraphID];
account = legacySubgraphKey.account;
seqID = legacySubgraphKey.accountSeqID;
}
| 3,811,923 |
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2021 Kentaro Hara
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
pragma solidity ^0.8.11;
import "../JohnLawCoin.sol";
//------------------------------------------------------------------------------
// [JohnLawCoin contract]
//
// JohnLawCoin is implemented as ERC20 tokens.
//
// Permission: Except public getters, only the ACB can call the methods.
// Coin holders can transfer their coins using the ERC20 token APIs.
//------------------------------------------------------------------------------
contract JohnLawCoin_v2 is ERC20PausableUpgradeable, OwnableUpgradeable {
// Constants.
// Name of the ERC20 token.
string public constant NAME = "JohnLawCoin";
// Symbol of the ERC20 token.
string public constant SYMBOL = "JLC";
// The initial coin supply.
uint public constant INITIAL_COIN_SUPPLY = 10000000;
// The tax rate.
uint public constant TAX_RATE = 1;
// Attributes.
// The account to which the tax is sent.
address public tax_account_;
address public tax_account_v2_;
mapping (address => uint) public dummy_;
// Events.
event TransferEvent(address indexed sender, address receiver,
uint amount, uint tax);
function upgrade()
public onlyOwner {
tax_account_v2_ = tax_account_;
}
// Mint coins to one account.
//
// Parameters
// ----------------
// |account|: The account to which the coins are minted.
// |amount|: The amount to be minted.
//
// Returns
// ----------------
// None.
function mint(address account, uint amount)
public onlyOwner {
mint_v2(account, amount);
}
function mint_v2(address account, uint amount)
public onlyOwner {
_mint(account, amount);
dummy_[account] = amount;
}
// Burn coins from one account.
//
// Parameters
// ----------------
// |account|: The account from which the coins are burned.
// |amount|: The amount to be burned.
//
// Returns
// ----------------
// None.
function burn(address account, uint amount)
public onlyOwner {
burn_v2(account, amount);
}
function burn_v2(address account, uint amount)
public onlyOwner {
_burn(account, amount);
dummy_[account] = amount;
}
// Move coins from one account to another account. Coin holders should use
// ERC20's transfer method instead.
//
// Parameters
// ----------------
// |sender|: The sender account.
// |receiver|: The receiver account.
// |amount|: The amount to be moved.
//
// Returns
// ----------------
// None.
function move(address sender, address receiver, uint amount)
public onlyOwner {
move_v2(sender, receiver, amount);
}
function move_v2(address sender, address receiver, uint amount)
public onlyOwner {
_transfer(sender, receiver, amount);
dummy_[receiver] = amount;
}
// Pause the contract.
function pause()
public onlyOwner {
if (!paused()) {
_pause();
}
}
// Unpause the contract.
function unpause()
public onlyOwner {
if (paused()) {
_unpause();
}
}
// Override decimals.
function decimals()
public pure override returns (uint8) {
return 18;
}
// Set the tax rate.
function resetTaxAccount()
public onlyOwner {
resetTaxAccount_v2();
}
function resetTaxAccount_v2()
public onlyOwner {
address old_tax_account = tax_account_v2_;
tax_account_v2_ = address(uint160(uint(keccak256(abi.encode(
"tax_v2", block.number)))));
move(old_tax_account, tax_account_v2_, balanceOf(old_tax_account));
tax_account_v2_ = tax_account_;
}
// Override ERC20's transfer method to impose a tax set by the ACB.
//
// Parameters
// ----------------
// |account|: The receiver account.
// |amount|: The amount to be transferred.
//
// Returns
// ----------------
// None.
function transfer(address account, uint amount)
public override returns (bool) {
return transfer_v2(account, amount);
}
function transfer_v2(address account, uint amount)
public returns (bool) {
uint tax = amount * TAX_RATE / 100;
_transfer(_msgSender(), tax_account_v2_, tax);
_transfer(_msgSender(), account, amount - tax);
emit TransferEvent(_msgSender(), account, amount - tax, tax);
return true;
}
}
//------------------------------------------------------------------------------
// [JohnLawBond contract]
//
// JohnLawBond is an implementation of the bonds to increase / decrease the
// total coin supply. The bonds are not transferable.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract JohnLawBond_v2 is OwnableUpgradeable {
using EnumerableSet for EnumerableSet.UintSet;
// Attributes.
// _bonds[account][redemption_epoch] stores the number of the bonds
// owned by the |account| that become redeemable at |redemption_epoch|.
mapping (address => mapping (uint => uint)) private _bonds;
// _redemption_epochs[account] is a set of the redemption epochs of the
// bonds owned by the |account|.
mapping (address => EnumerableSet.UintSet) private _redemption_epochs;
// _bond_count[account] is the number of the bonds owned by the |account|.
mapping (address => uint) private _bond_count;
// _bond_supply[redemption_epoch] is the total number of the bonds that
// become redeemable at |redemption_epoch|.
mapping (uint => uint) private _bond_supply;
// The total bond supply.
uint private _total_supply;
uint private _total_supply_v2;
mapping (address => mapping (uint => uint)) private _bonds_v2;
mapping (address => EnumerableSet.UintSet) private _redemption_epochs_v2;
mapping (address => uint) private _bond_count_v2;
mapping (uint => uint) private _bond_supply_v2;
// Events.
event MintEvent(address indexed account, uint redemption_epoch, uint amount);
event BurnEvent(address indexed account, uint redemption_epoch, uint amount);
function upgrade()
public onlyOwner {
_total_supply_v2 = _total_supply;
for (uint epoch = 0; epoch < 100; epoch++) {
_bond_supply_v2[epoch] = _bond_supply[epoch];
}
}
// Mint bonds to one account.
//
// Parameters
// ----------------
// |account|: The account to which the bonds are minted.
// |redemption_epoch|: The redemption epoch of the bonds.
// |amount|: The amount to be minted.
//
// Returns
// ----------------
// None.
function mint(address account, uint redemption_epoch, uint amount)
public onlyOwner {
mint_v2(account, redemption_epoch, amount);
}
function mint_v2(address account, uint redemption_epoch, uint amount)
public onlyOwner {
_bonds[account][redemption_epoch] += amount;
_bonds_v2[account][redemption_epoch] += amount;
_total_supply_v2 += amount;
_bond_count[account] += amount;
_bond_count_v2[account] += amount;
_bond_supply[redemption_epoch] += amount;
_bond_supply_v2[redemption_epoch] += amount;
if (_bonds[account][redemption_epoch] > 0) {
_redemption_epochs[account].add(redemption_epoch);
_redemption_epochs_v2[account].add(redemption_epoch);
}
emit MintEvent(account, redemption_epoch, amount);
}
// Burn bonds from one account.
//
// Parameters
// ----------------
// |account|: The account from which the bonds are burned.
// |redemption_epoch|: The redemption epoch of the bonds.
// |amount|: The amount to be burned.
//
// Returns
// ----------------
// None.
function burn(address account, uint redemption_epoch, uint amount)
public onlyOwner {
burn_v2(account, redemption_epoch, amount);
}
function burn_v2(address account, uint redemption_epoch, uint amount)
public onlyOwner {
_bonds[account][redemption_epoch] -= amount;
_bonds_v2[account][redemption_epoch] += amount;
_total_supply_v2 -= amount;
_bond_count[account] -= amount;
_bond_count_v2[account] += amount; // Use + to avoid underflow.
_bond_supply[redemption_epoch] -= amount;
_bond_supply_v2[redemption_epoch] -= amount;
if (_bonds[account][redemption_epoch] == 0) {
_redemption_epochs[account].remove(redemption_epoch);
_redemption_epochs_v2[account].remove(redemption_epoch);
}
emit BurnEvent(account, redemption_epoch, amount);
}
// Public getter: Return the number of the bonds owned by the |account|.
function numberOfBondsOwnedBy(address account)
public view returns (uint) {
return _bond_count[account];
}
// Public getter: Return the number of redemption epochs of the bonds
// owned by the |account|.
function numberOfRedemptionEpochsOwnedBy(address account)
public view returns (uint) {
return _redemption_epochs[account].length();
}
// Public getter: Return the |index|-th redemption epoch of the bonds
// owned by the |account|. |index| must be smaller than the value returned by
// numberOfRedemptionEpochsOwnedBy(account).
function getRedemptionEpochOwnedBy(address account, uint index)
public view returns (uint) {
return _redemption_epochs[account].at(index);
}
// Public getter: Return the number of the bonds owned by the |account| that
// become redeemable at |redemption_epoch|.
function balanceOf(address account, uint redemption_epoch)
public view returns (uint) {
return balanceOf_v2(account, redemption_epoch);
}
function balanceOf_v2(address account, uint redemption_epoch)
public view returns (uint) {
return _bonds[account][redemption_epoch];
}
// Public getter: Return the total bond supply.
function totalSupply()
public view returns (uint) {
return _total_supply_v2;
}
// Public getter: Return the number of the bonds that become redeemable at
// |redemption_epoch|.
function bondSupplyAt(uint redemption_epoch)
public view returns (uint) {
return _bond_supply_v2[redemption_epoch];
}
}
//------------------------------------------------------------------------------
// [Oracle contract]
//
// The oracle is a decentralized mechanism to determine one "truth" level
// from 0, 1, 2, ..., LEVEL_MAX - 1. The oracle uses the commit-reveal-reclaim
// voting scheme.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract Oracle_v2 is OwnableUpgradeable {
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public LEVEL_MAX;
uint public RECLAIM_THRESHOLD;
uint public PROPORTIONAL_REWARD_RATE;
// The valid phase transition is: COMMIT => REVEAL => RECLAIM.
enum Phase {
COMMIT, REVEAL, RECLAIM
}
// Commit is a struct to manage one commit entry in the commit-reveal-reclaim
// scheme.
struct Commit {
// The committed hash (filled in the commit phase).
bytes32 hash;
// The amount of deposited coins (filled in the commit phase).
uint deposit;
// The oracle level (filled in the reveal phase).
uint oracle_level;
// The phase of this commit entry.
Phase phase;
// The epoch ID when this commit entry is created.
uint epoch_id;
bytes32 hash_v2;
uint deposit_v2;
uint oracle_level_v2;
uint epoch_id_v2;
}
// Vote is a struct to aggregate voting statistics for each oracle level.
// The data is aggregated during the reveal phase and finalized at the end
// of the reveal phase.
struct Vote {
// The total amount of the coins deposited by the voters who voted for this
// oracle level.
uint deposit;
// The number of the voters.
uint count;
// Set to true when the voters for this oracle level are eligible to
// reclaim the coins they deposited.
bool should_reclaim;
// Set to true when the voters for this oracle level are eligible to
// receive a reward.
bool should_reward;
bool should_reclaim_v2;
bool should_reward_v2;
uint deposit_v2;
uint count_v2;
}
// Epoch is a struct to keep track of the states in the commit-reveal-reclaim
// scheme. The oracle creates three Epoch objects and uses them in a
// round-robin manner. For example, when the first Epoch object is in use for
// the commit phase, the second Epoch object is in use for the reveal phase,
// and the third Epoch object is in use for the reclaim phase.
struct Epoch {
// The commit entries.
mapping (address => Commit) commits;
// The voting statistics for all the oracle levels. This uses a mapping
// (instead of an array) to make the Vote struct upgradeable.
mapping (uint => Vote) votes;
// An account to store coins deposited by the voters.
address deposit_account;
// An account to store the reward.
address reward_account;
// The total amount of the reward.
uint reward_total;
// The current phase of this Epoch.
Phase phase;
address deposit_account_v2;
address reward_account_v2;
uint reward_total_v2;
Phase phase_v2;
}
// Attributes. See the comment in initialize().
// This uses a mapping (instead of an array) to make the Epoch struct
// upgradeable.
mapping (uint => Epoch) public epochs_;
uint public epoch_id_;
uint public epoch_id_v2_;
// Events.
event CommitEvent(address indexed sender, uint indexed epoch_id,
bytes32 hash, uint deposited);
event RevealEvent(address indexed sender, uint indexed epoch_id,
uint oracle_level, uint salt);
event ReclaimEvent(address indexed sender, uint indexed epoch_id,
uint deposited, uint rewarded);
event AdvancePhaseEvent(uint indexed epoch_id, uint tax, uint burned);
function upgrade()
public onlyOwner {
epoch_id_v2_ = epoch_id_;
for (uint epoch_index = 0; epoch_index < 3; epoch_index++) {
epochs_[epoch_index].deposit_account_v2 =
epochs_[epoch_index].deposit_account;
epochs_[epoch_index].reward_account_v2 =
epochs_[epoch_index].reward_account;
epochs_[epoch_index].reward_total_v2 =
epochs_[epoch_index].reward_total;
epochs_[epoch_index].phase_v2 =
epochs_[epoch_index].phase;
for (uint level = 0; level < LEVEL_MAX; level++) {
Vote storage vote = epochs_[epoch_index].votes[level];
vote.should_reclaim_v2 = vote.should_reclaim;
vote.should_reward_v2 = vote.should_reward;
vote.deposit_v2 = vote.deposit;
vote.count_v2 = vote.count;
}
}
}
// Do commit.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |hash|: The committed hash.
// |deposit|: The amount of the deposited coins.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// True if the commit succeeded. False otherwise.
function commit(address sender, bytes32 hash, uint deposit,
JohnLawCoin_v2 coin)
public onlyOwner returns (bool) {
return commit_v2(sender, hash, deposit, coin);
}
function commit_v2(address sender, bytes32 hash, uint deposit,
JohnLawCoin_v2 coin)
public onlyOwner returns (bool) {
Epoch storage epoch = epochs_[epoch_id_v2_ % 3];
require(epoch.phase_v2 == Phase.COMMIT, "co1");
if (coin.balanceOf(sender) < deposit) {
return false;
}
// One voter can commit only once per phase.
if (epoch.commits[sender].epoch_id == epoch_id_v2_) {
return false;
}
// Create a commit entry.
epoch.commits[sender] = Commit(
hash, deposit, LEVEL_MAX, Phase.COMMIT, epoch_id_v2_,
hash, deposit, LEVEL_MAX, epoch_id_v2_);
require(epoch.commits[sender].phase == Phase.COMMIT, "co2");
// Move the deposited coins to the deposit account.
coin.move(sender, epoch.deposit_account_v2, deposit);
emit CommitEvent(sender, epoch_id_v2_, hash, deposit);
return true;
}
// Do reveal.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |oracle_level|: The oracle level revealed by the voter.
// |salt|: The salt revealed by the voter.
//
// Returns
// ----------------
// True if the reveal succeeded. False otherwise.
function reveal(address sender, uint oracle_level, uint salt)
public onlyOwner returns (bool) {
return reveal_v2(sender, oracle_level, salt);
}
function reveal_v2(address sender, uint oracle_level, uint salt)
public onlyOwner returns (bool) {
Epoch storage epoch = epochs_[(epoch_id_v2_ - 1) % 3];
require(epoch.phase_v2 == Phase.REVEAL, "rv1");
if (LEVEL_MAX <= oracle_level) {
return false;
}
if (epoch.commits[sender].epoch_id != epoch_id_v2_ - 1) {
// The corresponding commit was not found.
return false;
}
// One voter can reveal only once per phase.
if (epoch.commits[sender].phase != Phase.COMMIT) {
return false;
}
epoch.commits[sender].phase = Phase.REVEAL;
// Check if the committed hash matches the revealed level and the salt.
bytes32 reveal_hash = encrypt(
sender, oracle_level, salt);
bytes32 hash = epoch.commits[sender].hash;
if (hash != reveal_hash) {
return false;
}
// Update the commit entry with the revealed level.
epoch.commits[sender].oracle_level = oracle_level;
// Count up the vote.
epoch.votes[oracle_level].deposit_v2 += epoch.commits[sender].deposit;
epoch.votes[oracle_level].count_v2 += 1;
emit RevealEvent(sender, epoch_id_v2_, oracle_level, salt);
return true;
}
// Do reclaim.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - uint: The amount of the reclaimed coins. This becomes a positive value
// when the voter is eligible to reclaim their deposited coins.
// - uint: The amount of the reward. This becomes a positive value when the
// voter voted for the "truth" oracle level.
function reclaim(address sender, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
return reclaim_v2(sender, coin);
}
function reclaim_v2(address sender, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
Epoch storage epoch = epochs_[(epoch_id_v2_ - 2) % 3];
require(epoch.phase_v2 == Phase.RECLAIM, "rc1");
if (epoch.commits[sender].epoch_id != epoch_id_v2_ - 2){
// The corresponding commit was not found.
return (0, 0);
}
// One voter can reclaim only once per phase.
if (epoch.commits[sender].phase != Phase.REVEAL) {
return (0, 0);
}
epoch.commits[sender].phase = Phase.RECLAIM;
uint deposit = epoch.commits[sender].deposit;
uint oracle_level = epoch.commits[sender].oracle_level;
if (oracle_level == LEVEL_MAX) {
return (0, 0);
}
require(0 <= oracle_level && oracle_level < LEVEL_MAX, "rc2");
if (!epoch.votes[oracle_level].should_reclaim_v2) {
return (0, 0);
}
require(epoch.votes[oracle_level].count_v2 > 0, "rc3");
// Reclaim the deposited coins.
coin.move(epoch.deposit_account_v2, sender, deposit);
uint reward = 0;
if (epoch.votes[oracle_level].should_reward_v2) {
// The voter who voted for the "truth" level can receive the reward.
//
// The PROPORTIONAL_REWARD_RATE of the reward is distributed to the
// voters in proportion to the coins they deposited. This incentivizes
// voters who have more coins (and thus have more power on determining
// the "truth" level) to join the oracle.
//
// The rest of the reward is distributed to the voters evenly. This
// incentivizes more voters (including new voters) to join the oracle.
if (epoch.votes[oracle_level].deposit_v2 > 0) {
reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total_v2 *
deposit) /
(uint(100) * epoch.votes[oracle_level].deposit_v2);
}
reward += ((uint(100) - PROPORTIONAL_REWARD_RATE) *
epoch.reward_total_v2) /
(uint(100) * epoch.votes[oracle_level].count_v2);
coin.move(epoch.reward_account_v2, sender, reward);
}
emit ReclaimEvent(sender, epoch_id_v2_, deposit, reward);
return (deposit, reward);
}
// Advance to the next phase. COMMIT => REVEAL, REVEAL => RECLAIM,
// RECLAIM => COMMIT.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// None.
function advance(JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
return advance_v2(coin);
}
function advance_v2(JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
// Advance the phase.
epoch_id_v2_ += 1;
epoch_id_ += 1;
// Step 1: Move the commit phase to the reveal phase.
Epoch storage epoch = epochs_[(epoch_id_v2_ - 1) % 3];
require(epoch.phase_v2 == Phase.COMMIT, "ad1");
epoch.phase_v2 = Phase.REVEAL;
// Step 2: Move the reveal phase to the reclaim phase.
epoch = epochs_[(epoch_id_v2_ - 2) % 3];
require(epoch.phase_v2 == Phase.REVEAL, "ad2");
epoch.phase_v2 = Phase.RECLAIM;
// The "truth" level is set to the mode of the weighted majority votes.
uint mode_level = getModeLevel();
if (0 <= mode_level && mode_level < LEVEL_MAX) {
uint deposit_revealed = 0;
uint deposit_to_reclaim = 0;
for (uint level = 0; level < LEVEL_MAX; level++) {
require(epoch.votes[level].should_reclaim_v2 == false, "ad3");
require(epoch.votes[level].should_reward_v2 == false, "ad4");
deposit_revealed += epoch.votes[level].deposit_v2;
if ((mode_level < RECLAIM_THRESHOLD ||
mode_level - RECLAIM_THRESHOLD <= level) &&
level <= mode_level + RECLAIM_THRESHOLD) {
// Voters who voted for the oracle levels in [mode_level -
// reclaim_threshold, mode_level + reclaim_threshold] are eligible
// to reclaim their deposited coins. Other voters lose their deposited
// coins.
epoch.votes[level].should_reclaim_v2 = true;
deposit_to_reclaim += epoch.votes[level].deposit_v2;
}
}
// Voters who voted for the "truth" level are eligible to receive the
// reward.
epoch.votes[mode_level].should_reward_v2 = true;
// Note: |deposit_revealed| is equal to
// |balanceOf(epoch.deposit_account_v2)|
// only when all the voters who voted in the commit phase revealed
// their votes correctly in the reveal phase.
require(deposit_revealed <= coin.balanceOf(epoch.deposit_account_v2),
"ad5");
require(deposit_to_reclaim <= coin.balanceOf(epoch.deposit_account_v2),
"ad6");
// The lost coins are moved to the reward account.
coin.move(
epoch.deposit_account_v2,
epoch.reward_account_v2,
coin.balanceOf(epoch.deposit_account_v2) - deposit_to_reclaim);
}
// Move the collected tax to the reward account.
address tax_account = coin.tax_account_v2_();
uint tax = coin.balanceOf(tax_account);
coin.move(tax_account, epoch.reward_account_v2, tax);
// Set the total amount of the reward.
epoch.reward_total_v2 = coin.balanceOf(epoch.reward_account_v2);
// Step 3: Move the reclaim phase to the commit phase.
uint epoch_index = epoch_id_v2_ % 3;
epoch = epochs_[epoch_index];
require(epoch.phase_v2 == Phase.RECLAIM, "ad7");
uint burned = coin.balanceOf(epoch.deposit_account_v2) +
coin.balanceOf(epoch.reward_account_v2);
// Burn the remaining deposited coins.
coin.burn(epoch.deposit_account_v2, coin.balanceOf(
epoch.deposit_account_v2));
// Burn the remaining reward.
coin.burn(epoch.reward_account_v2, coin.balanceOf(epoch.reward_account_v2));
// Initialize the Epoch object for the next commit phase.
//
// |epoch.commits_| cannot be cleared due to the restriction of Solidity.
// |epoch_id_| ensures the stale commit entries are not misused.
for (uint level = 0; level < LEVEL_MAX; level++) {
epoch.votes[level] = Vote(0, 0, false, false, false, false, 0, 0);
}
// Regenerate the account addresses just in case.
require(coin.balanceOf(epoch.deposit_account_v2) == 0, "ad8");
require(coin.balanceOf(epoch.reward_account_v2) == 0, "ad9");
epoch.deposit_account_v2 =
address(uint160(uint(keccak256(abi.encode(
"deposit_v2", epoch_index, block.number)))));
epoch.reward_account_v2 =
address(uint160(uint(keccak256(abi.encode(
"reward_v2", epoch_index, block.number)))));
epoch.reward_total_v2 = 0;
epoch.phase_v2 = Phase.COMMIT;
emit AdvancePhaseEvent(epoch_id_v2_, tax, burned);
return burned;
}
// Return the oracle level that got the largest amount of deposited coins.
// In other words, return the mode of the votes weighted by the deposited
// coins.
//
// Parameters
// ----------------
// None.
//
// Returns
// ----------------
// If there are multiple modes, return the mode that has the largest votes.
// If there are multiple modes that have the largest votes, return the
// smallest mode. If there are no votes, return LEVEL_MAX.
function getModeLevel()
public onlyOwner view returns (uint) {
return getModeLevel_v2();
}
function getModeLevel_v2()
public onlyOwner view returns (uint) {
Epoch storage epoch = epochs_[(epoch_id_v2_ - 2) % 3];
require(epoch.phase_v2 == Phase.RECLAIM, "gm1");
uint mode_level = LEVEL_MAX;
uint max_deposit = 0;
uint max_count = 0;
for (uint level = 0; level < LEVEL_MAX; level++) {
if (epoch.votes[level].count_v2 > 0 &&
(mode_level == LEVEL_MAX ||
max_deposit < epoch.votes[level].deposit_v2 ||
(max_deposit == epoch.votes[level].deposit_v2 &&
max_count < epoch.votes[level].count_v2))){
max_deposit = epoch.votes[level].deposit_v2;
max_count = epoch.votes[level].count_v2;
mode_level = level;
}
}
return mode_level;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
return revokeOwnership_v2(coin);
}
function revokeOwnership_v2(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
// Public getter: Return the Vote object at |epoch_index| and |level|.
function getVote(uint epoch_index, uint level)
public view returns (uint, uint, bool, bool) {
require(0 <= epoch_index && epoch_index <= 2, "gv1");
require(0 <= level && level < LEVEL_MAX, "gv2");
Vote memory vote = epochs_[epoch_index].votes[level];
return (vote.deposit_v2, vote.count_v2, vote.should_reclaim_v2,
vote.should_reward_v2);
}
// Public getter: Return the Commit object at |epoch_index| and |account|.
function getCommit(uint epoch_index, address account)
public view returns (bytes32, uint, uint, Phase, uint) {
require(0 <= epoch_index && epoch_index <= 2, "gc1");
Commit memory entry = epochs_[epoch_index].commits[account];
return (entry.hash, entry.deposit, entry.oracle_level,
entry.phase, entry.epoch_id);
}
// Public getter: Return the Epoch object at |epoch_index|.
function getEpoch(uint epoch_index)
public view returns (address, address, uint, Phase) {
require(0 <= epoch_index && epoch_index <= 2, "ge1");
return (epochs_[epoch_index].deposit_account_v2,
epochs_[epoch_index].reward_account_v2,
epochs_[epoch_index].reward_total_v2,
epochs_[epoch_index].phase_v2);
}
// Calculate a hash to be committed. Voters are expected to use this function
// to create a hash used in the commit phase.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |level|: The oracle level to vote.
// |salt|: The voter's salt.
//
// Returns
// ----------------
// The calculated hash value.
function encrypt(address sender, uint level, uint salt)
public pure returns (bytes32) {
return hash_v2(sender, level, salt);
}
function hash_v2(address sender, uint level, uint salt)
public pure returns (bytes32) {
return keccak256(abi.encode(sender, level, salt));
}
}
//------------------------------------------------------------------------------
// [Logging contract]
//
// The Logging contract records various metrics for analysis purpose.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract Logging_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// A struct to record metrics about voting.
struct VoteLog {
uint commit_succeeded;
uint commit_failed;
uint reveal_succeeded;
uint reveal_failed;
uint reclaim_succeeded;
uint reward_succeeded;
uint deposited;
uint reclaimed;
uint rewarded;
uint new_value1;
uint new_value2;
uint new_value3;
uint new_value4;
}
// A struct to record metrics about Epoch.
struct EpochLog {
uint minted_coins;
uint burned_coins;
int coin_supply_delta;
uint total_coin_supply;
uint oracle_level;
uint current_epoch_start;
uint tax;
uint new_value1;
uint new_value2;
}
// A struct to record metrics about BondOperation.
struct BondOperationLog {
int bond_budget;
uint total_bond_supply;
uint valid_bond_supply;
uint purchased_bonds;
uint redeemed_bonds;
uint expired_bonds;
uint new_value1;
uint new_value2;
}
// A struct to record metrics about OpenMarketOperation.
struct OpenMarketOperationLog {
int coin_budget;
int exchanged_coins;
int exchanged_eth;
uint eth_balance;
uint latest_price;
uint new_value1;
uint new_value2;
}
struct AnotherLog {
uint new_value1;
uint new_value2;
uint new_value3;
uint new_value4;
}
// Attributes.
// Logs about voting.
mapping (uint => VoteLog) public vote_logs_;
// Logs about Epoch.
mapping (uint => EpochLog) public epoch_logs_;
// Logs about BondOperation.
mapping (uint => BondOperationLog) public bond_operation_logs_;
// Logs about OpenMarketOperation.
mapping (uint => OpenMarketOperationLog) public open_market_operation_logs_;
mapping (uint => AnotherLog) public another_logs_;
function upgrade()
public onlyOwner {
}
// Public getter: Return the VoteLog of |epoch_id|.
function getVoteLog(uint epoch_id)
public view returns (
uint, uint, uint, uint, uint, uint, uint, uint, uint) {
return getVoteLog_v2(epoch_id);
}
function getVoteLog_v2(uint epoch_id)
public view returns (
uint, uint, uint, uint, uint, uint, uint, uint, uint) {
VoteLog memory log = vote_logs_[epoch_id];
return (log.commit_succeeded, log.commit_failed, log.reveal_succeeded,
log.reveal_failed, log.reclaim_succeeded, log.reward_succeeded,
log.deposited, log.reclaimed, log.rewarded);
}
// Public getter: Return the EpochLog of |epoch_id|.
function getEpochLog(uint epoch_id)
public view returns (uint, uint, int, uint, uint, uint, uint) {
return getEpochLog_v2(epoch_id);
}
function getEpochLog_v2(uint epoch_id)
public view returns (uint, uint, int, uint, uint, uint, uint) {
EpochLog memory log = epoch_logs_[epoch_id];
return (log.minted_coins, log.burned_coins, log.coin_supply_delta,
log.total_coin_supply, log.oracle_level, log.current_epoch_start,
log.tax);
}
// Public getter: Return the BondOperationLog of |epoch_id|.
function getBondOperationLog(uint epoch_id)
public view returns (int, uint, uint, uint, uint, uint) {
return getBondOperationLog_v2(epoch_id);
}
function getBondOperationLog_v2(uint epoch_id)
public view returns (int, uint, uint, uint, uint, uint) {
BondOperationLog memory log = bond_operation_logs_[epoch_id];
return (log.bond_budget, log.total_bond_supply, log.valid_bond_supply,
log.purchased_bonds, log.redeemed_bonds, log.expired_bonds);
}
// Public getter: Return the OpenMarketOperationLog of |epoch_id|.
function getOpenMarketOperationLog(uint epoch_id)
public view returns (int, int, int, uint, uint) {
return getOpenMarketOperationLog_v2(epoch_id);
}
function getOpenMarketOperationLog_v2(uint epoch_id)
public view returns (int, int, int, uint, uint) {
OpenMarketOperationLog memory log = open_market_operation_logs_[epoch_id];
return (log.coin_budget, log.exchanged_coins, log.exchanged_eth,
log.eth_balance, log.latest_price);
}
// Called when the epoch is updated.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |minted|: The amount of the minted coins.
// |burned|: The amount of the burned coins.
// |delta|: The delta of the total coin supply.
// |total_coin_supply|: The total coin supply.
// |oracle_level|: ACB.oracle_level_.
// |current_epoch_start|: ACB.current_epoch_start_.
// |tax|: The amount of the tax collected in the previous epoch.
//
// Returns
// ----------------
// None.
function updateEpoch(uint epoch_id, uint minted, uint burned, int delta,
uint total_coin_supply, uint oracle_level,
uint current_epoch_start, uint tax)
public onlyOwner {
updateEpoch_v2(epoch_id, minted, burned, delta, total_coin_supply,
oracle_level, current_epoch_start, tax);
}
function updateEpoch_v2(uint epoch_id, uint minted, uint burned, int delta,
uint total_coin_supply, uint oracle_level,
uint current_epoch_start, uint tax)
public onlyOwner {
epoch_logs_[epoch_id].minted_coins = minted;
epoch_logs_[epoch_id].burned_coins = burned;
epoch_logs_[epoch_id].coin_supply_delta = delta;
epoch_logs_[epoch_id].total_coin_supply = total_coin_supply;
epoch_logs_[epoch_id].oracle_level = oracle_level;
epoch_logs_[epoch_id].current_epoch_start = current_epoch_start;
epoch_logs_[epoch_id].tax = tax;
epoch_logs_[epoch_id].new_value1 += minted;
epoch_logs_[epoch_id].new_value2 += burned;
another_logs_[epoch_id].new_value1 += minted;
another_logs_[epoch_id].new_value2 += burned;
}
// Called when BondOperation's bond budget is updated at the beginning of
// the epoch.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |bond_budget|: The bond budget.
// |total_bond_supply|: The total bond supply.
// |valid_bond_supply|: The valid bond supply.
//
// Returns
// ----------------
// None.
function updateBondBudget(uint epoch_id, int bond_budget,
uint total_bond_supply, uint valid_bond_supply)
public onlyOwner {
updateBondBudget_v2(epoch_id, bond_budget,
total_bond_supply, valid_bond_supply);
}
function updateBondBudget_v2(uint epoch_id, int bond_budget,
uint total_bond_supply, uint valid_bond_supply)
public onlyOwner {
bond_operation_logs_[epoch_id].bond_budget = bond_budget;
bond_operation_logs_[epoch_id].total_bond_supply = total_bond_supply;
bond_operation_logs_[epoch_id].valid_bond_supply = valid_bond_supply;
bond_operation_logs_[epoch_id].purchased_bonds = 0;
bond_operation_logs_[epoch_id].redeemed_bonds = 0;
bond_operation_logs_[epoch_id].expired_bonds = 0;
bond_operation_logs_[epoch_id].new_value1 = epoch_id;
bond_operation_logs_[epoch_id].new_value2 = epoch_id;
another_logs_[epoch_id].new_value1 += epoch_id;
another_logs_[epoch_id].new_value2 += epoch_id;
}
// Called when OpenMarketOperation's coin budget is updated at the beginning
// of the epoch.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |coin_budget|: The coin budget.
// |eth_balance|: The ETH balance in the EthPool.
// |latest_price|: The latest ETH / JLC price.
//
// Returns
// ----------------
// None.
function updateCoinBudget(uint epoch_id, int coin_budget,
uint eth_balance, uint latest_price)
public onlyOwner {
updateCoinBudget_v2(epoch_id, coin_budget, eth_balance, latest_price);
}
function updateCoinBudget_v2(uint epoch_id, int coin_budget,
uint eth_balance, uint latest_price)
public onlyOwner {
open_market_operation_logs_[epoch_id].coin_budget = coin_budget;
open_market_operation_logs_[epoch_id].exchanged_coins = 0;
open_market_operation_logs_[epoch_id].exchanged_eth = 0;
open_market_operation_logs_[epoch_id].eth_balance = eth_balance;
open_market_operation_logs_[epoch_id].latest_price = latest_price;
open_market_operation_logs_[epoch_id].new_value1 = epoch_id;
open_market_operation_logs_[epoch_id].new_value2 = epoch_id;
another_logs_[epoch_id].new_value1 += epoch_id;
another_logs_[epoch_id].new_value2 += epoch_id;
}
// Called when ACB.vote is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |commit_result|: Whether the commit succeeded or not.
// |reveal_result|: Whether the reveal succeeded or not.
// |deposited|: The amount of the deposited coins.
// |reclaimed|: The amount of the reclaimed coins.
// |rewarded|: The amount of the reward.
//
// Returns
// ----------------
// None.
function vote(uint epoch_id, bool commit_result, bool reveal_result,
uint deposit, uint reclaimed, uint rewarded)
public onlyOwner {
vote_v2(epoch_id, commit_result, reveal_result, deposit,
reclaimed, rewarded);
}
function vote_v2(uint epoch_id, bool commit_result, bool reveal_result,
uint deposit, uint reclaimed, uint rewarded)
public onlyOwner {
if (commit_result) {
vote_logs_[epoch_id].commit_succeeded += 1;
} else {
vote_logs_[epoch_id].commit_failed += 1;
}
if (reveal_result) {
vote_logs_[epoch_id].reveal_succeeded += 1;
} else {
vote_logs_[epoch_id].reveal_failed += 1;
}
if (reclaimed > 0) {
vote_logs_[epoch_id].reclaim_succeeded += 1;
}
if (rewarded > 0) {
vote_logs_[epoch_id].reward_succeeded += 1;
}
vote_logs_[epoch_id].deposited += deposit;
vote_logs_[epoch_id].reclaimed += reclaimed;
vote_logs_[epoch_id].rewarded += rewarded;
vote_logs_[epoch_id].new_value1 += deposit;
vote_logs_[epoch_id].new_value2 += reclaimed;
another_logs_[epoch_id].new_value1 += deposit;
another_logs_[epoch_id].new_value2 += reclaimed;
}
// Called when ACB.purchaseBonds is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |purchased_bonds|: The number of purchased bonds.
//
// Returns
// ----------------
// None.
function purchaseBonds(uint epoch_id, uint purchased_bonds)
public onlyOwner {
purchaseBonds_v2(epoch_id, purchased_bonds);
}
function purchaseBonds_v2(uint epoch_id, uint purchased_bonds)
public onlyOwner {
bond_operation_logs_[epoch_id].purchased_bonds += purchased_bonds;
bond_operation_logs_[epoch_id].new_value1 += purchased_bonds;
}
// Called when ACB.redeemBonds is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |redeemed_bonds|: The number of redeemded bonds.
// |expired_bonds|: The number of expired bonds.
//
// Returns
// ----------------
// None.
function redeemBonds(uint epoch_id, uint redeemed_bonds, uint expired_bonds)
public onlyOwner {
redeemBonds_v2(epoch_id, redeemed_bonds, expired_bonds);
}
function redeemBonds_v2(uint epoch_id, uint redeemed_bonds,
uint expired_bonds)
public onlyOwner {
bond_operation_logs_[epoch_id].redeemed_bonds += redeemed_bonds;
bond_operation_logs_[epoch_id].expired_bonds += expired_bonds;
bond_operation_logs_[epoch_id].new_value1 += redeemed_bonds;
bond_operation_logs_[epoch_id].new_value2 += expired_bonds;
}
// Called when ACB.purchaseCoins is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |eth_amount|: The amount of ETH exchanged.
// |coin_amount|: The amount of coins exchanged.
//
// Returns
// ----------------
// None.
function purchaseCoins(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
purchaseCoins_v2(epoch_id, eth_amount, coin_amount);
}
function purchaseCoins_v2(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
open_market_operation_logs_[epoch_id].exchanged_eth +=
eth_amount.toInt256();
open_market_operation_logs_[epoch_id].exchanged_coins +=
coin_amount.toInt256();
open_market_operation_logs_[epoch_id].new_value1 += eth_amount;
open_market_operation_logs_[epoch_id].new_value2 += coin_amount;
}
// Called when ACB.sellCoins is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |eth_amount|: The amount of ETH exchanged.
// |coin_amount|: The amount of coins exchanged.
//
// Returns
// ----------------
// None.
function sellCoins(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
sellCoins_v2(epoch_id, eth_amount, coin_amount);
}
function sellCoins_v2(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
open_market_operation_logs_[epoch_id].exchanged_eth -=
eth_amount.toInt256();
open_market_operation_logs_[epoch_id].exchanged_coins -=
coin_amount.toInt256();
open_market_operation_logs_[epoch_id].new_value1 += eth_amount;
open_market_operation_logs_[epoch_id].new_value2 += coin_amount;
}
}
//------------------------------------------------------------------------------
// [BondOperation contract]
//
// The BondOperation contract increases / decreases the total coin supply by
// redeeming / issuing bonds. The bond budget is updated by the ACB every epoch.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract BondOperation_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public BOND_PRICE;
uint public BOND_REDEMPTION_PRICE;
uint public BOND_REDEMPTION_PERIOD;
uint public BOND_REDEEMABLE_PERIOD;
// Attributes. See the comment in initialize().
JohnLawBond public bond_;
int public bond_budget_;
JohnLawBond_v2 public bond_v2_;
int public bond_budget_v2_;
// Events.
event IncreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint issued_bonds, uint redemption_epoch);
event DecreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event UpdateBondBudgetEvent(uint indexed epoch_id, int delta,
int bond_budget, uint mint);
function upgrade(JohnLawBond_v2 bond)
public onlyOwner {
bond_v2_ = bond;
bond_budget_v2_ = bond_budget_;
bond_v2_.upgrade();
}
// Deprecate the contract.
function deprecate()
public onlyOwner {
bond_v2_.transferOwnership(msg.sender);
}
// Increase the total bond supply by issuing bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to be issued.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// The redemption epoch of the issued bonds if it succeeds. 0 otherwise.
function increaseBondSupply(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
return increaseBondSupply_v2(sender, count, epoch_id, coin);
}
function increaseBondSupply_v2(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
require(count > 0, "BondOperation: You must purchase at least one bond.");
require(bond_budget_v2_ >= count.toInt256(),
"BondOperation: The bond budget is not enough.");
uint amount = BOND_PRICE * count;
require(coin.balanceOf(sender) >= amount,
"BondOperation: Your coin balance is not enough.");
// Set the redemption epoch of the bonds.
uint redemption_epoch = epoch_id + BOND_REDEMPTION_PERIOD;
// Issue new bonds.
bond_v2_.mint(sender, redemption_epoch, count);
bond_budget_v2_ -= count.toInt256();
require(bond_budget_v2_ >= 0, "pb1");
require(bond_v2_.balanceOf(sender, redemption_epoch) > 0, "pb2");
// Burn the corresponding coins.
coin.burn(sender, amount);
bond_budget_ = bond_budget_v2_;
emit IncreaseBondSupplyEvent(sender, epoch_id, count, redemption_epoch);
return redemption_epoch;
}
// Decrease the total bond supply by redeeming bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - The number of redeemed bonds.
// - The number of expired bonds.
function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
return decreaseBondSupply_v2(sender, redemption_epochs, epoch_id, coin);
}
function decreaseBondSupply_v2(address sender,
uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
uint redeemed_bonds = 0;
uint expired_bonds = 0;
for (uint i = 0; i < redemption_epochs.length; i++) {
uint redemption_epoch = redemption_epochs[i];
uint count = bond_v2_.balanceOf(sender, redemption_epoch);
if (epoch_id < redemption_epoch) {
// If the bonds have not yet hit their redemption epoch, the
// BondOperation accepts the redemption as long as |bond_budget_| is
// negative.
if (bond_budget_v2_ >= 0) {
continue;
}
if (count > (-bond_budget_v2_).toUint256()) {
count = (-bond_budget_v2_).toUint256();
}
bond_budget_v2_ += count.toInt256();
}
if (epoch_id < redemption_epoch + BOND_REDEEMABLE_PERIOD) {
// If the bonds are not expired, mint the corresponding coins to the
// sender account.
uint amount = count * BOND_REDEMPTION_PRICE;
coin.mint(sender, amount);
redeemed_bonds += count;
} else {
expired_bonds += count;
}
// Burn the redeemed / expired bonds.
bond_v2_.burn(sender, redemption_epoch, count);
}
bond_budget_ = bond_budget_v2_;
emit DecreaseBondSupplyEvent(sender, epoch_id,
redeemed_bonds, expired_bonds);
return (redeemed_bonds, expired_bonds);
}
// Update the bond budget to increase or decrease the total coin supply.
//
// Parameters
// ----------------
// |delta|: The target increase or decrease of the total coin supply.
// |epoch_id|: The current epoch ID.
//
// Returns
// ----------------
// The amount of coins that cannot be increased by adjusting the bond budget
// and thus need to be newly minted.
function updateBondBudget(int delta, uint epoch_id)
public onlyOwner returns (uint) {
return updateBondBudget_v2(delta, epoch_id);
}
function updateBondBudget_v2(int delta, uint epoch_id)
public onlyOwner returns (uint) {
uint mint = 0;
uint bond_supply = validBondSupply(epoch_id);
if (delta == 0) {
// No change in the total coin supply.
bond_budget_v2_ = 0;
} else if (delta > 0) {
// Increase the total coin supply.
uint count = delta.toUint256() / BOND_REDEMPTION_PRICE;
if (count <= bond_supply) {
// If there are sufficient bonds to redeem, increase the total coin
// supply by redeeming the bonds.
bond_budget_v2_ = -count.toInt256();
} else {
// Otherwise, redeem all the issued bonds.
bond_budget_v2_ = -bond_supply.toInt256();
// The remaining coins need to be newly minted.
mint = (count - bond_supply) * BOND_REDEMPTION_PRICE;
}
require(bond_budget_v2_ <= 0, "cs1");
} else {
// Issue new bonds to decrease the total coin supply.
bond_budget_v2_ = -delta / BOND_PRICE.toInt256();
require(bond_budget_v2_ >= 0, "cs2");
}
bond_budget_ = bond_budget_v2_;
require(bond_supply.toInt256() + bond_budget_v2_ >= 0, "cs3");
emit UpdateBondBudgetEvent(epoch_id, delta, bond_budget_v2_, mint);
return mint;
}
// Public getter: Return the valid bond supply; i.e., the total supply of
// not-yet-expired bonds.
function validBondSupply(uint epoch_id)
public view returns (uint) {
return validBondSupply_v2(epoch_id);
}
function validBondSupply_v2(uint epoch_id)
public view returns (uint) {
uint count = 0;
for (uint redemption_epoch =
(epoch_id > BOND_REDEEMABLE_PERIOD ?
epoch_id - BOND_REDEEMABLE_PERIOD + 1 : 0);
// The previous versions of the smart contract might have used a larger
// BOND_REDEMPTION_PERIOD. Add 20 to look up all the redemption
// epochs that might have set in the previous versions.
redemption_epoch <= epoch_id + BOND_REDEMPTION_PERIOD + 20;
redemption_epoch++) {
count += bond_v2_.bondSupplyAt(redemption_epoch);
}
return count;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
return revokeOwnership_v2(coin);
}
function revokeOwnership_v2(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
}
//------------------------------------------------------------------------------
// [OpenMarketOperation contract]
//
// The OpenMarketOperation contract increases / decreases the total coin supply
// by purchasing / selling ETH from the open market. The price between JLC and
// ETH is determined by a Dutch auction.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract OpenMarketOperation_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public PRICE_CHANGE_INTERVAL;
uint public PRICE_CHANGE_PERCENTAGE;
uint public PRICE_CHANGE_MAX;
uint public PRICE_MULTIPLIER;
// Attributes. See the comment in initialize().
uint public latest_price_;
bool public latest_price_updated_;
uint public start_price_;
int public coin_budget_;
uint public latest_price_v2_;
bool public latest_price_updated_v2_;
uint public start_price_v2_;
int public coin_budget_v2_;
// Events.
event IncreaseCoinSupplyEvent(uint requested_eth_amount, uint elapsed_time,
uint eth_amount, uint coin_amount);
event DecreaseCoinSupplyEvent(uint requested_coin_amount, uint elapsed_time,
uint eth_balance, uint eth_amount,
uint coin_amount);
event UpdateCoinBudgetEvent(int coin_budget);
function upgrade()
public onlyOwner {
latest_price_v2_ = latest_price_;
latest_price_updated_v2_ = latest_price_updated_;
start_price_v2_ = start_price_;
coin_budget_v2_ = coin_budget_;
}
// Increase the total coin supply by purchasing ETH from the sender account.
// This method returns the amount of JLC and ETH to be exchanged. The actual
// change to the total coin supply and the ETH pool is made by the ACB.
//
// Parameters
// ----------------
// |requested_eth_amount|: The amount of ETH the sender is willing to pay.
// |elapsed_time|: The elapsed seconds from the current epoch start.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH to be exchanged. This can be smaller than
// |requested_eth_amount| when the open market operation does not have
// enough coin budget.
// - The amount of JLC to be exchanged.
function increaseCoinSupply(uint requested_eth_amount, uint elapsed_time)
public onlyOwner returns (uint, uint) {
return increaseCoinSupply_v2(requested_eth_amount, elapsed_time);
}
function increaseCoinSupply_v2(uint requested_eth_amount, uint elapsed_time)
public onlyOwner returns (uint, uint) {
require(coin_budget_v2_ > 0,
"OpenMarketOperation: The coin budget must be positive.");
// Calculate the amount of JLC and ETH to be exchanged.
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_eth_amount / price;
if (coin_amount > coin_budget_v2_.toUint256()) {
coin_amount = coin_budget_v2_.toUint256();
}
uint eth_amount = coin_amount * price;
if (coin_amount > 0) {
latest_price_v2_ = price;
latest_price_updated_v2_ = true;
}
coin_budget_v2_ -= coin_amount.toInt256();
require(coin_budget_v2_ >= 0, "ic1");
require(eth_amount <= requested_eth_amount, "ic2");
emit IncreaseCoinSupplyEvent(requested_eth_amount, elapsed_time,
eth_amount, coin_amount);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
return (eth_amount, coin_amount);
}
// Decrease the total coin supply by selling ETH to the sender account.
// This method returns the amount of JLC and ETH to be exchanged. The actual
// change to the total coin supply and the ETH pool is made by the ACB.
//
// Parameters
// ----------------
// |requested_coin_amount|: The amount of JLC the sender is willing to pay.
// |elapsed_time|: The elapsed seconds from the current epoch start.
// |eth_balance|: The ETH balance in the EthPool.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH to be exchanged.
// - The amount of JLC to be exchanged. This can be smaller than
// |requested_coin_amount| when the open market operation does not have
// enough ETH in the pool.
function decreaseCoinSupply(uint requested_coin_amount, uint elapsed_time,
uint eth_balance)
public onlyOwner returns (uint, uint) {
return decreaseCoinSupply_v2(requested_coin_amount, elapsed_time,
eth_balance);
}
function decreaseCoinSupply_v2(uint requested_coin_amount, uint elapsed_time,
uint eth_balance)
public onlyOwner returns (uint, uint) {
require(coin_budget_v2_ < 0,
"OpenMarketOperation: The coin budget must be negative.");
// Calculate the amount of JLC and ETH to be exchanged.
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_coin_amount;
if (coin_amount >= (-coin_budget_v2_).toUint256()) {
coin_amount = (-coin_budget_v2_).toUint256();
}
uint eth_amount = coin_amount * price;
if (eth_amount >= eth_balance) {
eth_amount = eth_balance;
}
coin_amount = eth_amount / price;
if (coin_amount > 0) {
latest_price_v2_ = price;
latest_price_updated_v2_ = true;
}
coin_budget_v2_ += coin_amount.toInt256();
require(coin_budget_v2_ <= 0, "dc1");
require(coin_amount <= requested_coin_amount, "dc2");
emit DecreaseCoinSupplyEvent(requested_coin_amount, elapsed_time,
eth_balance, eth_amount, coin_amount);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
return (eth_amount, coin_amount);
}
// Return the current price in the Dutch auction.
//
// Parameters
// ----------------
// |elapsed_time|: The elapsed seconds from the current epoch start.
//
// Returns
// ----------------
// The current price.
function getCurrentPrice(uint elapsed_time)
public view returns (uint) {
return getCurrentPrice_v2(elapsed_time);
}
function getCurrentPrice_v2(uint elapsed_time)
public view returns (uint) {
if (coin_budget_v2_ > 0) {
uint price = start_price_v2_;
for (uint i = 0;
i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX;
i++) {
price = price * (100 - PRICE_CHANGE_PERCENTAGE) / 100;
}
if (price == 0) {
price = 1;
}
return price;
} else if (coin_budget_v2_ < 0) {
uint price = start_price_v2_;
for (uint i = 0;
i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX;
i++) {
price = price * (100 + PRICE_CHANGE_PERCENTAGE) / 100;
}
return price;
}
return 0;
}
// Update the coin budget. The coin budget indicates how many coins should
// be added to / removed from the total coin supply; i.e., the amount of JLC
// to be sold / purchased by the open market operation. The ACB calls the
// method at the beginning of each epoch.
//
// Parameters
// ----------------
// |coin_budget|: The coin budget.
//
// Returns
// ----------------
// None.
function updateCoinBudget(int coin_budget)
public onlyOwner {
updateCoinBudget_v2(coin_budget);
}
function updateCoinBudget_v2(int coin_budget)
public onlyOwner {
if (latest_price_updated_v2_ == false) {
if (coin_budget_v2_ > 0) {
// If no exchange was observed in the previous epoch, the price setting
// was too high. Lower the price.
latest_price_v2_ = latest_price_v2_ / PRICE_MULTIPLIER + 1;
} else if (coin_budget_v2_ < 0) {
// If no exchange was observed in the previous epoch, the price setting
// was too low. Raise the price.
latest_price_v2_ = latest_price_v2_ * PRICE_MULTIPLIER;
}
}
coin_budget_v2_ = coin_budget;
latest_price_updated_v2_ = false;
require(latest_price_v2_ > 0, "uc1");
if (coin_budget_v2_ > 0) {
start_price_v2_ = latest_price_v2_ * PRICE_MULTIPLIER;
} else if (coin_budget_v2_ == 0) {
start_price_v2_ = 0;
} else {
start_price_v2_ = latest_price_v2_ / PRICE_MULTIPLIER + 1;
}
emit UpdateCoinBudgetEvent(coin_budget_v2_);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
}
}
//------------------------------------------------------------------------------
// [EthPool contract]
//
// The EthPool contract stores ETH for the open market operation.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract EthPool_v2 is OwnableUpgradeable {
function upgrade()
public onlyOwner {
}
// Increase ETH.
function increaseEth()
public onlyOwner payable {
increaseEth_v2();
}
function increaseEth_v2()
public onlyOwner payable {
}
// Decrease |eth_amount| ETH and send it to the |receiver|.
function decreaseEth(address receiver, uint eth_amount)
public onlyOwner {
decreaseEth_v2(receiver, eth_amount);
}
function decreaseEth_v2(address receiver, uint eth_amount)
public onlyOwner {
require(address(this).balance >= eth_amount, "de1");
(bool success,) =
payable(receiver).call{value: eth_amount}("");
require(success, "de2");
}
}
//------------------------------------------------------------------------------
// [ACB contract]
//
// The ACB stabilizes the USD / JLC exchange rate to 1.0 with algorithmically
// defined monetary policies:
//
// 1. The ACB obtains the exchange rate from the oracle.
// 2. If the exchange rate is 1.0, the ACB does nothing.
// 3. If the exchange rate is higher than 1.0, the ACB increases the total coin
// supply by redeeming issued bonds (regardless of their redemption dates).
// If that is not enough to supply sufficient coins, the ACB performs an open
// market operation to sell JLC and purchase ETH to increase the total coin
// supply.
// 4. If the exchange rate is lower than 1.0, the ACB decreases the total coin
// supply by issuing new bonds. If the exchange rate drops down to 0.6, the
// ACB performs an open market operation to sell ETH and purchase JLC to
// decrease the total coin supply.
//
// Permission: All the methods are public. No one (including the genesis
// account) is privileged to influence the monetary policies of the ACB. The ACB
// is fully decentralized and there is truly no gatekeeper. The only exceptions
// are a few methods the genesis account may use to upgrade the smart contracts
// to fix bugs during a development phase.
//------------------------------------------------------------------------------
contract ACB_v2 is OwnableUpgradeable, PausableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
bytes32 public constant NULL_HASH = 0;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint[] public LEVEL_TO_EXCHANGE_RATE;
uint public EXCHANGE_RATE_DIVISOR;
uint public EPOCH_DURATION;
uint public DEPOSIT_RATE;
uint public DAMPING_FACTOR;
// Used only in testing. This cannot be put in a derived contract due to
// a restriction of @openzeppelin/truffle-upgrades.
uint public _timestamp_for_testing;
// Attributes. See the comment in initialize().
JohnLawCoin public coin_;
Oracle public oracle_;
BondOperation public bond_operation_;
OpenMarketOperation public open_market_operation_;
EthPool public eth_pool_;
Logging public logging_;
uint public oracle_level_;
uint public current_epoch_start_;
JohnLawCoin_v2 public coin_v2_;
Oracle_v2 public oracle_v2_;
BondOperation_v2 public bond_operation_v2_;
OpenMarketOperation_v2 public open_market_operation_v2_;
EthPool_v2 public eth_pool_v2_;
Logging_v2 public logging_v2_;
uint public oracle_level_v2_;
uint public current_epoch_start_v2_;
// Events.
event PayableEvent(address indexed sender, uint value);
event UpdateEpochEvent(uint epoch_id, uint current_epoch_start, uint tax,
uint burned, int delta, uint mint);
event VoteEvent(address indexed sender, uint indexed epoch_id,
bytes32 hash, uint oracle_level, uint salt,
bool commit_result, bool reveal_result,
uint deposited, uint reclaimed, uint rewarded,
bool epoch_updated);
event PurchaseBondsEvent(address indexed sender, uint indexed epoch_id,
uint purchased_bonds, uint redemption_epoch);
event RedeemBondsEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event PurchaseCoinsEvent(address indexed sender, uint requested_eth_amount,
uint eth_amount, uint coin_amount);
event SellCoinsEvent(address indexed sender, uint requested_coin_amount,
uint eth_amount, uint coin_amount);
function upgrade(JohnLawCoin_v2 coin, JohnLawBond_v2 bond,
Oracle_v2 oracle, BondOperation_v2 bond_operation,
OpenMarketOperation_v2 open_market_operation,
EthPool_v2 eth_pool,
Logging_v2 logging)
public onlyOwner {
coin_v2_ = coin;
oracle_v2_ = oracle;
bond_operation_v2_ = bond_operation;
open_market_operation_v2_ = open_market_operation;
eth_pool_v2_ = eth_pool;
oracle_level_v2_ = oracle_level_;
current_epoch_start_v2_ = current_epoch_start_;
logging_v2_ = logging;
coin_v2_.upgrade();
bond_operation_v2_.upgrade(bond);
open_market_operation_v2_.upgrade();
eth_pool_v2_.upgrade();
oracle_v2_.upgrade();
logging_v2_.upgrade();
}
// Deprecate the ACB. Only the genesis account can call this method.
function deprecate()
public onlyOwner {
coin_v2_.transferOwnership(msg.sender);
oracle_v2_.transferOwnership(msg.sender);
bond_operation_v2_.transferOwnership(msg.sender);
open_market_operation_v2_.transferOwnership(msg.sender);
eth_pool_v2_.transferOwnership(msg.sender);
logging_v2_.transferOwnership(msg.sender);
}
// Pause the ACB in emergency cases. Only the genesis account can call this
// method.
function pause()
public onlyOwner {
if (!paused()) {
_pause();
}
coin_v2_.pause();
}
// Unpause the ACB. Only the genesis account can call this method.
function unpause()
public onlyOwner {
if (paused()) {
_unpause();
}
coin_v2_.unpause();
}
// Payable fallback to receive and store ETH. Give us tips :)
fallback() external payable {
require(msg.data.length == 0, "fb1");
emit PayableEvent(msg.sender, msg.value);
}
receive() external payable {
emit PayableEvent(msg.sender, msg.value);
}
// Withdraw the tips. Only the genesis account can call this method.
function withdrawTips()
public whenNotPaused onlyOwner {
(bool success,) =
payable(msg.sender).call{value: address(this).balance}("");
require(success, "wt1");
}
// A struct to pack local variables. This is needed to avoid a stack-too-deep
// error in Solidity.
struct VoteResult {
uint epoch_id;
bool epoch_updated;
bool reveal_result;
bool commit_result;
uint deposited;
uint reclaimed;
uint rewarded;
}
// Vote for the exchange rate. The voter can commit a vote to the current
// epoch N, reveal their vote in the epoch N-1, and reclaim the deposited
// coins and get a reward for their vote in the epoch N-2 at the same time.
//
// Parameters
// ----------------
// |hash|: The hash to be committed in the current epoch N. Specify
// ACB.NULL_HASH if you do not want to commit and only want to reveal and
// reclaim previous votes.
// |oracle_level|: The oracle level you voted for in the epoch N-1.
// |salt|: The salt you used in the epoch N-1.
//
// Returns
// ----------------
// A tuple of six values:
// - boolean: Whether the commit succeeded or not.
// - boolean: Whether the reveal succeeded or not.
// - uint: The amount of the deposited coins.
// - uint: The amount of the reclaimed coins.
// - uint: The amount of the reward.
// - boolean: Whether this vote updated the epoch.
function vote(bytes32 hash, uint oracle_level,
uint salt)
public whenNotPaused returns (bool, bool, uint, uint, uint, bool) {
return vote_v2(hash, oracle_level, salt);
}
function vote_v2(bytes32 hash, uint oracle_level,
uint salt)
public whenNotPaused returns (bool, bool, uint, uint, uint, bool) {
VoteResult memory result;
result.epoch_id = oracle_v2_.epoch_id_();
result.epoch_updated = false;
if (getTimestamp() >= current_epoch_start_v2_ + EPOCH_DURATION) {
// Start a new epoch.
result.epoch_updated = true;
result.epoch_id += 1;
current_epoch_start_v2_ = getTimestamp();
current_epoch_start_ = current_epoch_start_v2_;
// Advance to the next epoch. Provide the |tax| coins to the oracle
// as a reward.
uint tax = coin_v2_.balanceOf(coin_v2_.tax_account_v2_());
coin_v2_.transferOwnership(address(oracle_v2_));
uint burned = oracle_v2_.advance(coin_v2_);
oracle_v2_.revokeOwnership(coin_v2_);
// Reset the tax account address just in case.
coin_v2_.resetTaxAccount();
require(coin_v2_.balanceOf(coin_v2_.tax_account_v2_()) == 0, "vo1");
int delta = 0;
oracle_level_ = oracle_v2_.getModeLevel();
if (oracle_level_ != oracle_v2_.LEVEL_MAX()) {
require(0 <= oracle_level_ && oracle_level_ < oracle_v2_.LEVEL_MAX(),
"vo2");
// Translate the oracle level to the exchange rate.
uint exchange_rate = LEVEL_TO_EXCHANGE_RATE[oracle_level_];
// Calculate the amount of coins to be minted or burned based on the
// Quantity Theory of Money. If the exchange rate is 1.1 (i.e., 1 coin
// = 1.1 USD), the total coin supply is increased by 10%. If the
// exchange rate is 0.8 (i.e., 1 coin = 0.8 USD), the total coin supply
// is decreased by 20%.
delta = coin_v2_.totalSupply().toInt256() *
(int(exchange_rate) - int(EXCHANGE_RATE_DIVISOR)) /
int(EXCHANGE_RATE_DIVISOR);
// To avoid increasing or decreasing too many coins in one epoch,
// multiply the damping factor.
delta = delta * int(DAMPING_FACTOR) / 100;
}
// Update the bond budget.
uint mint =
bond_operation_v2_.updateBondBudget(delta, result.epoch_id);
// Update the coin budget.
if (oracle_level_ == 0 && delta < 0) {
require(mint == 0, "vo3");
open_market_operation_v2_.updateCoinBudget(delta);
} else {
open_market_operation_v2_.updateCoinBudget(mint.toInt256());
}
logging_v2_.updateEpoch(
result.epoch_id, mint, burned, delta, coin_v2_.totalSupply(),
oracle_level_, current_epoch_start_v2_, tax);
logging_v2_.updateBondBudget(
result.epoch_id, bond_operation_v2_.bond_budget_v2_(),
bond_operation_v2_.bond_v2_().totalSupply(),
bond_operation_v2_.validBondSupply(result.epoch_id));
logging_v2_.updateCoinBudget(
result.epoch_id, open_market_operation_v2_.coin_budget_v2_(),
address(eth_pool_).balance,
open_market_operation_v2_.latest_price_());
emit UpdateEpochEvent(result.epoch_id, current_epoch_start_v2_,
tax, burned, delta, mint);
}
coin_v2_.transferOwnership(address(oracle_v2_));
// Commit.
//
// The voter needs to deposit the DEPOSIT_RATE percentage of their coin
// balance.
result.deposited = coin_v2_.balanceOf(msg.sender) * DEPOSIT_RATE / 100;
if (hash == 0) {
result.deposited = 0;
}
result.commit_result = oracle_v2_.commit(
msg.sender, hash, result.deposited, coin_v2_);
if (!result.commit_result) {
result.deposited = 0;
}
// Reveal.
result.reveal_result = oracle_v2_.reveal(msg.sender, oracle_level, salt);
// Reclaim.
(result.reclaimed, result.rewarded) =
oracle_v2_.reclaim(msg.sender, coin_v2_);
oracle_v2_.revokeOwnership(coin_v2_);
logging_v2_.vote(result.epoch_id, result.commit_result,
result.reveal_result, result.deposited,
result.reclaimed, result.rewarded);
emit VoteEvent(
msg.sender, result.epoch_id, hash, oracle_level, salt,
result.commit_result, result.reveal_result, result.deposited,
result.reclaimed, result.rewarded, result.epoch_updated);
return (result.commit_result, result.reveal_result, result.deposited,
result.reclaimed, result.rewarded, result.epoch_updated);
}
// Purchase bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to purchase.
//
// Returns
// ----------------
// The redemption epoch of the purchased bonds.
function purchaseBonds(uint count)
public whenNotPaused returns (uint) {
return purchaseBonds_v2(count);
}
function purchaseBonds_v2(uint count)
public whenNotPaused returns (uint) {
uint epoch_id = oracle_v2_.epoch_id_();
coin_v2_.transferOwnership(address(bond_operation_v2_));
uint redemption_epoch =
bond_operation_v2_.increaseBondSupply(address(msg.sender), count,
epoch_id, coin_v2_);
bond_operation_v2_.revokeOwnership(coin_v2_);
logging_v2_.purchaseBonds(epoch_id, count);
emit PurchaseBondsEvent(address(msg.sender), epoch_id,
count, redemption_epoch);
return redemption_epoch;
}
// Redeem bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
//
// Returns
// ----------------
// The number of successfully redeemed bonds.
function redeemBonds(uint[] memory redemption_epochs)
public whenNotPaused returns (uint) {
return redeemBonds_v2(redemption_epochs);
}
function redeemBonds_v2(uint[] memory redemption_epochs)
public whenNotPaused returns (uint) {
uint epoch_id = oracle_v2_.epoch_id_();
coin_v2_.transferOwnership(address(bond_operation_v2_));
(uint redeemed_bonds, uint expired_bonds) =
bond_operation_v2_.decreaseBondSupply(
address(msg.sender), redemption_epochs, epoch_id, coin_v2_);
bond_operation_v2_.revokeOwnership(coin_v2_);
logging_v2_.redeemBonds(epoch_id, redeemed_bonds, expired_bonds);
emit RedeemBondsEvent(address(msg.sender), epoch_id,
redeemed_bonds, expired_bonds);
return redeemed_bonds;
}
// Pay ETH and purchase JLC from the open market operation.
//
// Parameters
// ----------------
// The sender needs to pay |requested_eth_amount| ETH.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH the sender paid. This value can be smaller than
// |requested_eth_amount| when the open market operation does not have enough
// coin budget. The remaining ETH is returned to the sender's wallet.
// - The amount of JLC the sender purchased.
function purchaseCoins()
public whenNotPaused payable returns (uint, uint) {
uint requested_eth_amount = msg.value;
uint elapsed_time = getTimestamp() - current_epoch_start_v2_;
// Calculate the amount of ETH and JLC to be exchanged.
(uint eth_amount, uint coin_amount) =
open_market_operation_v2_.increaseCoinSupply(
requested_eth_amount, elapsed_time);
coin_v2_.mint(msg.sender, coin_amount);
require(address(this).balance >= requested_eth_amount, "pc1");
bool success;
(success,) =
payable(address(eth_pool_v2_)).call{value: eth_amount}(
abi.encodeWithSignature("increaseEth()"));
require(success, "pc2");
logging_.purchaseCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
// Pay back the remaining ETH to the sender. This may trigger any arbitrary
// operations in an external smart contract. This must be called at the very
// end of purchaseCoins().
(success,) =
payable(msg.sender).call{value: requested_eth_amount - eth_amount}("");
require(success, "pc3");
emit PurchaseCoinsEvent(msg.sender, requested_eth_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Pay JLC and purchase ETH from the open market operation.
//
// Parameters
// ----------------
// |requested_coin_amount|: The amount of JLC the sender is willing to pay.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH the sender purchased.
// - The amount of JLC the sender paid. This value can be smaller than
// |requested_coin_amount| when the open market operation does not have
// enough ETH in the pool.
function sellCoins(uint requested_coin_amount)
public whenNotPaused returns (uint, uint) {
return sellCoins_v2(requested_coin_amount);
}
function sellCoins_v2(uint requested_coin_amount)
public whenNotPaused returns (uint, uint) {
// The sender does not have enough coins.
require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount,
"OpenMarketOperation: Your coin balance is not enough.");
// Calculate the amount of ETH and JLC to be exchanged.
uint elapsed_time = getTimestamp() - current_epoch_start_v2_;
(uint eth_amount, uint coin_amount) =
open_market_operation_v2_.decreaseCoinSupply(
requested_coin_amount, elapsed_time, address(eth_pool_v2_).balance);
coin_v2_.burn(msg.sender, coin_amount);
logging_.sellCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
// Send ETH to the sender. This may trigger any arbitrary operations in an
// external smart contract. This must be called at the very end of
// sellCoins().
eth_pool_v2_.decreaseEth(msg.sender, eth_amount);
emit SellCoinsEvent(msg.sender, requested_coin_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Calculate a hash to be committed to the oracle. Voters are expected to
// call this function to create the hash.
//
// Parameters
// ----------------
// |level|: The oracle level to vote.
// |salt|: The voter's salt.
//
// Returns
// ----------------
// The calculated hash value.
function encrypt(uint level, uint salt)
public view returns (bytes32) {
return encrypt_v2(level, salt);
}
function encrypt_v2(uint level, uint salt)
public view returns (bytes32) {
address sender = msg.sender;
return oracle_v2_.encrypt(sender, level, salt);
}
// Public getter: Return the current timestamp in seconds.
function getTimestamp()
public virtual view returns (uint) {
// block.timestamp is better than block.number because the granularity of
// the epoch update is EPOCH_DURATION (1 week).
return block.timestamp;
}
}
| The sender does not have enough coins. Calculate the amount of ETH and JLC to be exchanged. Send ETH to the sender. This may trigger any arbitrary operations in an external smart contract. This must be called at the very end of sellCoins(). | function sellCoins_v2(uint requested_coin_amount)
public whenNotPaused returns (uint, uint) {
require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount,
"OpenMarketOperation: Your coin balance is not enough.");
uint elapsed_time = getTimestamp() - current_epoch_start_v2_;
(uint eth_amount, uint coin_amount) =
open_market_operation_v2_.decreaseCoinSupply(
requested_coin_amount, elapsed_time, address(eth_pool_v2_).balance);
coin_v2_.burn(msg.sender, coin_amount);
logging_.sellCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
eth_pool_v2_.decreaseEth(msg.sender, eth_amount);
emit SellCoinsEvent(msg.sender, requested_coin_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
| 13,078,090 |
pragma solidity ^0.4.20;
/**
* @author FadyAro
*
* 22.07.2018
*
*
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused, 'Contract Paused!');
_;
}
modifier whenPaused() {
require(paused, 'Contract Active!');
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract EtherDrop is Pausable {
uint constant PRICE_WEI = 2e16;
/*
* blacklist flag
*/
uint constant FLAG_BLACKLIST = 1;
/*
* subscription queue size: should be power of 10
*/
uint constant QMAX = 1000;
/*
* randomness order construction conform to QMAX
* e.g. random [0 to 999] is of order 3 => rand = 100*x + 10*y + z
*/
uint constant DMAX = 3;
/*
* this event is when we have a new subscription
* note that it may be fired sequentially just before => NewWinner
*/
event NewDropIn(address addr, uint round, uint place, uint value);
/*
* this event is when we have a new winner
* it is as well a new round start => (round + 1)
*/
event NewWinner(address addr, uint round, uint place, uint value, uint price);
struct history {
/*
* user black listed comment
*/
uint blacklist;
/*
* user rounds subscriptions number
*/
uint size;
/*
* array of subscribed rounds indexes
*/
uint[] rounds;
/*
* array of rounds subscription's inqueue indexes
*/
uint[] places;
/*
* array of rounds's ether value subscription >= PRICE
*/
uint[] values;
/*
* array of 0's initially, update to REWARD PRICE in win situations
*/
uint[] prices;
}
/*
* active subscription queue
*/
address[] private _queue;
/*
* winners history
*/
address[] private _winners;
/*
* winner comment 32 left
*/
bytes32[] private _wincomma;
/*
* winner comment 32 right
*/
bytes32[] private _wincommb;
/*
* winners positions
*/
uint[] private _positions;
/*
* on which block we got a winner
*/
uint[] private _blocks;
/*
* active round index
*/
uint public _round;
/*
* active round queue pointer
*/
uint public _counter;
/*
* allowed collectibles
*/
uint private _collectibles = 0;
/*
* users history mapping
*/
mapping(address => history) private _history;
/**
* get current round details
*/
function currentRound() public view returns (uint round, uint counter, uint round_users, uint price) {
return (_round, _counter, QMAX, PRICE_WEI);
}
/**
* get round stats by index
*/
function roundStats(uint index) public view returns (uint round, address winner, uint position, uint block_no) {
return (index, _winners[index], _positions[index], _blocks[index]);
}
/**
*
* @dev get the total number of user subscriptions
*
* @param user the specific user
*
* @return user rounds size
*/
function userRounds(address user) public view returns (uint) {
return _history[user].size;
}
/**
*
* @dev get user subscription round number details
*
* @param user the specific user
*
* @param index the round number
*
* @return round no, user placing, user drop, user reward
*/
function userRound(address user, uint index) public view returns (uint round, uint place, uint value, uint price) {
history memory h = _history[user];
return (h.rounds[index], h.places[index], h.values[index], h.prices[index]);
}
/**
* round user subscription
*/
function() public payable whenNotPaused {
/*
* check subscription price
*/
require(msg.value >= PRICE_WEI, 'Insufficient Ether');
/*
* start round ahead: on QUEUE_MAX + 1
* draw result
*/
if (_counter == QMAX) {
uint r = DMAX;
uint winpos = 0;
_blocks.push(block.number);
bytes32 _a = blockhash(block.number - 1);
for (uint i = 31; i >= 1; i--) {
if (uint8(_a[i]) >= 48 && uint8(_a[i]) <= 57) {
winpos = 10 * winpos + (uint8(_a[i]) - 48);
if (--r == 0) break;
}
}
_positions.push(winpos);
/*
* post out winner rewards
*/
uint _reward = (QMAX * PRICE_WEI * 90) / 100;
address _winner = _queue[winpos];
_winners.push(_winner);
_winner.transfer(_reward);
/*
* update round history
*/
history storage h = _history[_winner];
h.prices[h.size - 1] = _reward;
/*
* default winner blank comments
*/
_wincomma.push(0x0);
_wincommb.push(0x0);
/*
* log the win event: winpos is the proof, history trackable
*/
emit NewWinner(_winner, _round, winpos, h.values[h.size - 1], _reward);
/*
* update collectibles
*/
_collectibles += address(this).balance - _reward;
/*
* reset counter
*/
_counter = 0;
/*
* increment round
*/
_round++;
}
h = _history[msg.sender];
/*
* user is not allowed to subscribe twice
*/
require(h.size == 0 || h.rounds[h.size - 1] != _round, 'Already In Round');
/*
* create user subscription: N.B. places[_round] is the result proof
*/
h.size++;
h.rounds.push(_round);
h.places.push(_counter);
h.values.push(msg.value);
h.prices.push(0);
/*
* initial round is a push, others are 'on set' index
*/
if (_round == 0) {
_queue.push(msg.sender);
} else {
_queue[_counter] = msg.sender;
}
/*
* log subscription
*/
emit NewDropIn(msg.sender, _round, _counter, msg.value);
/*
* increment counter
*/
_counter++;
}
/**
*
* @dev let the user comment 64 letters for a winning round
*
* @param round the winning round
*
* @param a the first 32 letters comment
*
* @param b the second 32 letters comment
*
* @return user comment
*/
function comment(uint round, bytes32 a, bytes32 b) whenNotPaused public {
address winner = _winners[round];
require(winner == msg.sender, 'not a winner');
require(_history[winner].blacklist != FLAG_BLACKLIST, 'blacklisted');
_wincomma[round] = a;
_wincommb[round] = b;
}
/**
*
* @dev blacklist a user for its comments behavior
*
* @param user address
*
*/
function blackList(address user) public onlyOwner {
history storage h = _history[user];
if (h.size > 0) {
h.blacklist = FLAG_BLACKLIST;
}
}
/**
*
* @dev get the user win round comment
*
* @param round the winning round number
*
* @return user comment
*/
function userComment(uint round) whenNotPaused public view returns (address winner, bytes32 comma, bytes32 commb) {
if (_history[_winners[round]].blacklist != FLAG_BLACKLIST) {
return (_winners[round], _wincomma[round], _wincommb[round]);
} else {
return (0x0, 0x0, 0x0);
}
}
/*
* etherdrop team R&D support collectibles
*/
function collect() public onlyOwner {
owner.transfer(_collectibles);
}
} | get the total number of user subscriptions user the specific user return user rounds size/ | function userRounds(address user) public view returns (uint) {
return _history[user].size;
}
| 6,355,278 |
./partial_match/1/0xFb27de6Ed15E20d84D9a6eC92e784E40587de768/sources/contracts/modules/PropsERC721UConfigPools.sol | see {IERC721Metadata}/ | function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"no token"
);
return string(abi.encodePacked(baseURI_, _tokenId.toString(), ".json"));
}
| 2,751,199 |
./partial_match/1/0x79241Fd23F74a5587D22E24795776159f5455569/sources/Proposal22.sol | allows governance to assign delegate to self/ | function _acceptGov()
override
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
| 4,022,556 |
./full_match/43114/0x21a5e0Fc127C246030Fe12fd8bad711a06601A9b/sources/contracts/libraries/IncentiveId.sol | Calculate the key for a staking incentive key The components used to compute the incentive identifier return incentiveId The identifier for the incentive | function compute(IUniswapV3Staker.IncentiveKey memory key) internal pure returns (bytes32 incentiveId) {
return keccak256(abi.encode(key));
}
| 4,602,603 |
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Poseidon hash function
/// See: https://eprint.iacr.org/2019/458.pdf
/// Code auto-generated by generate_poseidon_EVM_code.py
/// @author Brecht Devos - <[email protected]>
library Poseidon
{
//
// hash_t5f6p52
//
struct HashInputs5
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
}
function hash_t5f6p52_internal(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint q
)
internal
pure
returns (uint)
{
assembly {
function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q)
nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q)
nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q)
nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q)
nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q)
nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q)
nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q)
nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q)
nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q)
nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q)
nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q)
nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q)
nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q)
nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q)
nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q)
nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q)
nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q)
nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q)
nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q)
nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q)
nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q)
nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q)
nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q)
nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q)
nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q)
}
function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := addmod(_t0, c, _q)
nt1 := addmod(_t1, c, _q)
nt2 := addmod(_t2, c, _q)
nt3 := addmod(_t3, c, _q)
nt4 := addmod(_t4, c, _q)
}
function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, _t0, _q)
nt0 := mulmod(nt0, nt0, _q)
nt0 := mulmod(_t0, nt0, _q)
nt1 := mulmod(_t1, _t1, _q)
nt1 := mulmod(nt1, nt1, _q)
nt1 := mulmod(_t1, nt1, _q)
nt2 := mulmod(_t2, _t2, _q)
nt2 := mulmod(nt2, nt2, _q)
nt2 := mulmod(_t2, nt2, _q)
nt3 := mulmod(_t3, _t3, _q)
nt3 := mulmod(nt3, nt3, _q)
nt3 := mulmod(_t3, nt3, _q)
nt4 := mulmod(_t4, _t4, _q)
nt4 := mulmod(nt4, nt4, _q)
nt4 := mulmod(_t4, nt4, _q)
}
function sbox_partial(_t, _q) -> nt {
nt := mulmod(_t, _t, _q)
nt := mulmod(nt, nt, _q)
nt := mulmod(_t, nt, _q)
}
// round 0
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 1
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 2
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 3
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 4
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 5
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 6
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 7
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 8
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 9
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 10
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 11
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 12
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 13
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 14
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 15
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 16
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 17
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 18
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 19
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 20
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 21
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 22
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 23
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 24
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 25
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 26
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 27
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 28
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 29
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 30
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 31
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 32
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 33
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 34
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 35
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 36
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 37
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 38
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 39
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 40
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 41
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 42
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 43
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 44
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 45
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 46
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 47
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 48
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 49
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 50
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 51
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 52
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 53
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 54
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 55
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 56
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 57
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
}
return t0;
}
function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q);
}
//
// hash_t7f6p52
//
struct HashInputs7
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
uint t5;
uint t6;
}
function mix(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q);
o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q);
o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q);
o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q);
o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q);
o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q);
o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q);
o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q);
o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q);
o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q);
o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q);
o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q);
o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q);
o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q);
o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q);
o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q);
o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q);
o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q);
o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q);
o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q);
o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q);
o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q);
o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q);
o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q);
o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q);
o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q);
o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q);
o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q);
o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q);
o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q);
o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q);
o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q);
o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q);
o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q);
o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q);
o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q);
o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q);
o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q);
o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q);
o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q);
o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q);
o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q);
o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q);
o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q);
o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q);
o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q);
o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q);
o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q);
o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function ark(HashInputs7 memory i, uint q, uint c) internal pure
{
HashInputs7 memory o;
o.t0 = addmod(i.t0, c, q);
o.t1 = addmod(i.t1, c, q);
o.t2 = addmod(i.t2, c, q);
o.t3 = addmod(i.t3, c, q);
o.t4 = addmod(i.t4, c, q);
o.t5 = addmod(i.t5, c, q);
o.t6 = addmod(i.t6, c, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_full(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
o.t1 = mulmod(i.t1, i.t1, q);
o.t1 = mulmod(o.t1, o.t1, q);
o.t1 = mulmod(i.t1, o.t1, q);
o.t2 = mulmod(i.t2, i.t2, q);
o.t2 = mulmod(o.t2, o.t2, q);
o.t2 = mulmod(i.t2, o.t2, q);
o.t3 = mulmod(i.t3, i.t3, q);
o.t3 = mulmod(o.t3, o.t3, q);
o.t3 = mulmod(i.t3, o.t3, q);
o.t4 = mulmod(i.t4, i.t4, q);
o.t4 = mulmod(o.t4, o.t4, q);
o.t4 = mulmod(i.t4, o.t4, q);
o.t5 = mulmod(i.t5, i.t5, q);
o.t5 = mulmod(o.t5, o.t5, q);
o.t5 = mulmod(i.t5, o.t5, q);
o.t6 = mulmod(i.t6, i.t6, q);
o.t6 = mulmod(o.t6, o.t6, q);
o.t6 = mulmod(i.t6, o.t6, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_partial(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
i.t0 = o.t0;
}
function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
require(i.t5 < q, "INVALID_INPUT");
require(i.t6 < q, "INVALID_INPUT");
// round 0
ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522);
sbox_full(i, q);
mix(i, q);
// round 1
ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128);
sbox_full(i, q);
mix(i, q);
// round 2
ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509);
sbox_full(i, q);
mix(i, q);
// round 3
ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615);
sbox_partial(i, q);
mix(i, q);
// round 4
ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514);
sbox_partial(i, q);
mix(i, q);
// round 5
ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619);
sbox_partial(i, q);
mix(i, q);
// round 6
ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153);
sbox_partial(i, q);
mix(i, q);
// round 7
ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608);
sbox_partial(i, q);
mix(i, q);
// round 8
ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567);
sbox_partial(i, q);
mix(i, q);
// round 9
ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471);
sbox_partial(i, q);
mix(i, q);
// round 10
ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765);
sbox_partial(i, q);
mix(i, q);
// round 11
ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772);
sbox_partial(i, q);
mix(i, q);
// round 12
ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850);
sbox_partial(i, q);
mix(i, q);
// round 13
ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375);
sbox_partial(i, q);
mix(i, q);
// round 14
ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136);
sbox_partial(i, q);
mix(i, q);
// round 15
ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374);
sbox_partial(i, q);
mix(i, q);
// round 16
ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107);
sbox_partial(i, q);
mix(i, q);
// round 17
ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214);
sbox_partial(i, q);
mix(i, q);
// round 18
ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455);
sbox_partial(i, q);
mix(i, q);
// round 19
ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212);
sbox_partial(i, q);
mix(i, q);
// round 20
ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626);
sbox_partial(i, q);
mix(i, q);
// round 21
ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417);
sbox_partial(i, q);
mix(i, q);
// round 22
ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006);
sbox_partial(i, q);
mix(i, q);
// round 23
ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766);
sbox_partial(i, q);
mix(i, q);
// round 24
ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832);
sbox_partial(i, q);
mix(i, q);
// round 25
ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231);
sbox_partial(i, q);
mix(i, q);
// round 26
ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114);
sbox_partial(i, q);
mix(i, q);
// round 27
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719);
sbox_partial(i, q);
mix(i, q);
// round 28
ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018);
sbox_partial(i, q);
mix(i, q);
// round 29
ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562);
sbox_partial(i, q);
mix(i, q);
// round 30
ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826);
sbox_partial(i, q);
mix(i, q);
// round 31
ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245);
sbox_partial(i, q);
mix(i, q);
// round 32
ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748);
sbox_partial(i, q);
mix(i, q);
// round 33
ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508);
sbox_partial(i, q);
mix(i, q);
// round 34
ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523);
sbox_partial(i, q);
mix(i, q);
// round 35
ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410);
sbox_partial(i, q);
mix(i, q);
// round 36
ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935);
sbox_partial(i, q);
mix(i, q);
// round 37
ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643);
sbox_partial(i, q);
mix(i, q);
// round 38
ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512);
sbox_partial(i, q);
mix(i, q);
// round 39
ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393);
sbox_partial(i, q);
mix(i, q);
// round 40
ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525);
sbox_partial(i, q);
mix(i, q);
// round 41
ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006);
sbox_partial(i, q);
mix(i, q);
// round 42
ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058);
sbox_partial(i, q);
mix(i, q);
// round 43
ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739);
sbox_partial(i, q);
mix(i, q);
// round 44
ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548);
sbox_partial(i, q);
mix(i, q);
// round 45
ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311);
sbox_partial(i, q);
mix(i, q);
// round 46
ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208);
sbox_partial(i, q);
mix(i, q);
// round 47
ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706);
sbox_partial(i, q);
mix(i, q);
// round 48
ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232);
sbox_partial(i, q);
mix(i, q);
// round 49
ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524);
sbox_partial(i, q);
mix(i, q);
// round 50
ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266);
sbox_partial(i, q);
mix(i, q);
// round 51
ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210);
sbox_partial(i, q);
mix(i, q);
// round 52
ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743);
sbox_partial(i, q);
mix(i, q);
// round 53
ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373);
sbox_partial(i, q);
mix(i, q);
// round 54
ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849);
sbox_partial(i, q);
mix(i, q);
// round 55
ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076);
sbox_full(i, q);
mix(i, q);
// round 56
ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047);
sbox_full(i, q);
mix(i, q);
// round 57
ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544);
sbox_full(i, q);
mix(i, q);
return i.t0;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
using MathUint for uint;
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function add64(
uint64 a,
uint64 b
)
internal
pure
returns (uint64 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 safe transfer
/// @dev see https://github.com/sec-bit/badERC20Fix
/// @author Brecht Devos - <[email protected]>
library ERC20SafeTransfer
{
function safeTransferAndVerify(
address token,
address to,
uint value
)
internal
{
safeTransferWithGasLimitAndVerify(
token,
to,
value,
gasleft()
);
}
function safeTransfer(
address token,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferWithGasLimit(
token,
to,
value,
gasleft()
);
}
function safeTransferWithGasLimitAndVerify(
address token,
address to,
uint value,
uint gasLimit
)
internal
{
require(
safeTransferWithGasLimit(token, to, value, gasLimit),
"TRANSFER_FAILURE"
);
}
function safeTransferWithGasLimit(
address token,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transfer is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb
bytes memory callData = abi.encodeWithSelector(
bytes4(0xa9059cbb),
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function safeTransferFromAndVerify(
address token,
address from,
address to,
uint value
)
internal
{
safeTransferFromWithGasLimitAndVerify(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFromWithGasLimitAndVerify(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
{
bool result = safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasLimit
);
require(result, "TRANSFER_FAILURE");
}
function safeTransferFromWithGasLimit(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd
bytes memory callData = abi.encodeWithSelector(
bytes4(0x23b872dd),
from,
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function checkReturnValue(
bool success
)
internal
pure
returns (bool)
{
// A transfer/transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
if (success) {
assembly {
switch returndatasize()
// Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded
case 0 {
success := 1
}
// Standard ERC20: a single boolean value is returned which needs to be true
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
// None of the above: not successful
default {
success := 0
}
}
}
return success;
}
}
// Copyright 2017 Loopring Technology Limited.
pragma experimental ABIEncoderV2;
/// @title ExchangeTokens.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeTokens
{
using MathUint for uint;
using ERC20SafeTransfer for address;
using ExchangeMode for ExchangeData.State;
event TokenRegistered(
address token,
uint16 tokenId
);
function getTokenAddress(
ExchangeData.State storage S,
uint16 tokenID
)
public
view
returns (address)
{
require(tokenID < S.tokens.length, "INVALID_TOKEN_ID");
return S.tokens[tokenID].token;
}
function registerToken(
ExchangeData.State storage S,
address tokenAddress
)
public
returns (uint16 tokenID)
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST");
require(S.tokens.length < ExchangeData.MAX_NUM_TOKENS(), "TOKEN_REGISTRY_FULL");
if (S.depositContract != IDepositContract(0)) {
require(
S.depositContract.isTokenSupported(tokenAddress),
"UNSUPPORTED_TOKEN"
);
}
ExchangeData.Token memory token = ExchangeData.Token(
tokenAddress
);
tokenID = uint16(S.tokens.length);
S.tokens.push(token);
S.tokenToTokenId[tokenAddress] = tokenID + 1;
emit TokenRegistered(tokenAddress, tokenID);
}
function getTokenID(
ExchangeData.State storage S,
address tokenAddress
)
internal // inline call
view
returns (uint16 tokenID)
{
tokenID = S.tokenToTokenId[tokenAddress];
require(tokenID != 0, "TOKEN_NOT_FOUND");
tokenID = tokenID - 1;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeBalances.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeBalances
{
using MathUint for uint;
function verifyAccountBalance(
uint merkleRoot,
ExchangeData.MerkleProof calldata merkleProof
)
public
pure
{
require(
isAccountBalanceCorrect(merkleRoot, merkleProof),
"INVALID_MERKLE_TREE_DATA"
);
}
function isAccountBalanceCorrect(
uint merkleRoot,
ExchangeData.MerkleProof memory merkleProof
)
public
pure
returns (bool)
{
// Verify data
uint calculatedRoot = getBalancesRoot(
merkleProof.balanceLeaf.tokenID,
merkleProof.balanceLeaf.balance,
merkleProof.balanceLeaf.weightAMM,
merkleProof.balanceLeaf.storageRoot,
merkleProof.balanceMerkleProof
);
calculatedRoot = getAccountInternalsRoot(
merkleProof.accountLeaf.accountID,
merkleProof.accountLeaf.owner,
merkleProof.accountLeaf.pubKeyX,
merkleProof.accountLeaf.pubKeyY,
merkleProof.accountLeaf.nonce,
merkleProof.accountLeaf.feeBipsAMM,
calculatedRoot,
merkleProof.accountMerkleProof
);
return (calculatedRoot == merkleRoot);
}
function getBalancesRoot(
uint16 tokenID,
uint balance,
uint weightAMM,
uint storageRoot,
uint[24] memory balanceMerkleProof
)
private
pure
returns (uint)
{
uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0);
uint _id = tokenID;
for (uint depth = 0; depth < 8; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
balanceItem = hashImpl(
balanceItem,
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceItem,
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceItem,
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2],
balanceItem
);
}
_id = _id >> 2;
}
return balanceItem;
}
function getAccountInternalsRoot(
uint32 accountID,
address owner,
uint pubKeyX,
uint pubKeyY,
uint nonce,
uint feeBipsAMM,
uint balancesRoot,
uint[48] memory accountMerkleProof
)
private
pure
returns (uint)
{
uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot);
uint _id = accountID;
for (uint depth = 0; depth < 16; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
accountItem = hashImpl(
accountItem,
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
accountItem = hashImpl(
accountMerkleProof[base],
accountItem,
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountItem,
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2],
accountItem
);
}
_id = _id >> 2;
}
return accountItem;
}
function hashAccountLeaf(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint t5
)
public
pure
returns (uint)
{
Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0);
return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD());
}
function hashImpl(
uint t0,
uint t1,
uint t2,
uint t3
)
private
pure
returns (uint)
{
Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0);
return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD());
}
}
//Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
library BytesUtil {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, 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(tempBytes, 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 tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// 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 tempBytes 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.
))
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
require(_bytes.length >= (_start + 20));
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
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;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success, ) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// Copyright 2017 Loopring Technology Limited.
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
/**
* @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 uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(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 uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(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);
}
}
/// @title Utility Functions for floats
/// @author Brecht Devos - <[email protected]>
library FloatUtil
{
using MathUint for uint;
using SafeCast for uint;
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits for the exponent
/// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent)
/// @return value The decoded integer value.
function decodeFloat(
uint f,
uint numBits
)
internal
pure
returns (uint96 value)
{
uint numBitsMantissa = numBits.sub(5);
uint exponent = f >> numBitsMantissa;
// log2(10**77) = 255.79 < 256
require(exponent <= 77, "EXPONENT_TOO_LARGE");
uint mantissa = f & ((1 << numBitsMantissa) - 1);
value = mantissa.mul(10 ** exponent).toUint96();
}
}
// Copyright 2017 Loopring Technology Limited.
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainHash,
bytes32 dataHash
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_HEADER,
domainHash,
dataHash
)
);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint96
{
function add(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function sub(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
}
// Copyright 2017 Loopring Technology Limited.
interface IAmmSharedConfig
{
function maxForcedExitAge() external view returns (uint);
function maxForcedExitCount() external view returns (uint);
function forcedExitFee() external view returns (uint);
}
// Copyright 2017 Loopring Technology Limited.
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @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.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
abstract contract ERC20
{
function totalSupply()
public
virtual
view
returns (uint);
function balanceOf(
address who
)
public
virtual
view
returns (uint);
function allowance(
address owner,
address spender
)
public
virtual
view
returns (uint);
function transfer(
address to,
uint value
)
public
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint value
)
public
virtual
returns (bool);
function approve(
address spender,
uint value
)
public
virtual
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
interface IAgent{}
interface IAgentRegistry
{
/// @dev Returns whether an agent address is an agent of an account owner
/// @param owner The account owner.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address owner,
address agent
)
external
view
returns (bool);
/// @dev Returns whether an agent address is an agent of all account owners
/// @param owners The account owners.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address[] calldata owners,
address agent
)
external
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockVerifier
/// @author Brecht Devos - <[email protected]>
abstract contract IBlockVerifier is Claimable
{
// -- Events --
event CircuitRegistered(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
event CircuitDisabled(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
// -- Public functions --
/// @dev Sets the verifying key for the specified circuit.
/// Every block permutation needs its own circuit and thus its own set of
/// verification keys. Only a limited number of block sizes per block
/// type are supported.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param vk The verification key
function registerCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[18] calldata vk
)
external
virtual;
/// @dev Disables the use of the specified circuit.
/// This will stop NEW blocks from using the given circuit, blocks that were already committed
/// can still be verified.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
function disableCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual;
/// @dev Verifies blocks with the given public data and proofs.
/// Verifying a block makes sure all requests handled in the block
/// are correctly handled by the operator.
/// @param blockType The type of block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param publicInputs The hash of all the public data of the blocks
/// @param proofs The ZK proofs proving that the blocks are correct
/// @return True if the block is valid, false otherwise
function verifyProofs(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[] calldata publicInputs,
uint[] calldata proofs
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit with the specified parameters is registered.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is registered, false otherwise
function isCircuitRegistered(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit can still be used to commit new blocks.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is enabled, false otherwise
function isCircuitEnabled(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title IDepositContract.
/// @dev Contract storing and transferring funds for an exchange.
///
/// ERC1155 tokens can be supported by registering pseudo token addresses calculated
/// as `address(keccak256(real_token_address, token_params))`. Then the custom
/// deposit contract can look up the real token address and paramsters with the
/// pseudo token address before doing the transfers.
/// @author Brecht Devos - <[email protected]>
interface IDepositContract
{
/// @dev Returns if a token is suppoprted by this contract.
function isTokenSupported(address token)
external
view
returns (bool);
/// @dev Transfers tokens from a user to the exchange. This function will
/// be called when a user deposits funds to the exchange.
/// In a simple implementation the funds are simply stored inside the
/// deposit contract directly. More advanced implementations may store the funds
/// in some DeFi application to earn interest, so this function could directly
/// call the necessary functions to store the funds there.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens to transfer.
/// @param extraData Opaque data that can be used by the contract to handle the deposit
/// @return amountReceived The amount to deposit to the user's account in the Merkle tree
function deposit(
address from,
address token,
uint96 amount,
bytes calldata extraData
)
external
payable
returns (uint96 amountReceived);
/// @dev Transfers tokens from the exchange to a user. This function will
/// be called when a withdrawal is done for a user on the exchange.
/// In the simplest implementation the funds are simply stored inside the
/// deposit contract directly so this simply transfers the requested tokens back
/// to the user. More advanced implementations may store the funds
/// in some DeFi application to earn interest so the function would
/// need to get those tokens back from the DeFi application first before they
/// can be transferred to the user.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address from which 'amount' tokens are transferred.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens transferred.
/// @param extraData Opaque data that can be used by the contract to handle the withdrawal
function withdraw(
address from,
address to,
address token,
uint amount,
bytes calldata extraData
)
external
payable;
/// @dev Transfers tokens (ETH not supported) for a user using the allowance set
/// for the exchange. This way the approval can be used for all functionality (and
/// extended functionality) of the exchange.
/// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw`
/// should be used for that as they will contain specialised logic for those operations.
/// This function can be called by the exchange to transfer onchain funds of users
/// necessary for Agent functionality.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function transfer(
address from,
address to,
address token,
uint amount
)
external
payable;
/// @dev Checks if the given address is used for depositing ETH or not.
/// Is used while depositing to send the correct ETH amount to the deposit contract.
///
/// Note that 0x0 is always registered for deposting ETH when the exchange is created!
/// This function allows additional addresses to be used for depositing ETH, the deposit
/// contract can implement different behaviour based on the address value.
///
/// @param addr The address to check
/// @return True if the address is used for depositing ETH, else false.
function isETH(address addr)
external
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title ILoopringV3
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract ILoopringV3 is Claimable
{
// == Events ==
event ExchangeStakeDeposited(address exchangeAddr, uint amount);
event ExchangeStakeWithdrawn(address exchangeAddr, uint amount);
event ExchangeStakeBurned(address exchangeAddr, uint amount);
event SettingsUpdated(uint time);
// == Public Variables ==
mapping (address => uint) internal exchangeStake;
address public lrcAddress;
uint public totalStake;
address public blockVerifierAddress;
uint public forcedWithdrawalFee;
uint public tokenRegistrationFeeLRCBase;
uint public tokenRegistrationFeeLRCDelta;
uint8 public protocolTakerFeeBips;
uint8 public protocolMakerFeeBips;
address payable public protocolFeeVault;
// == Public Functions ==
/// @dev Updates the global exchange settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateSettings(
address payable _protocolFeeVault, // address(0) not allowed
address _blockVerifierAddress, // address(0) not allowed
uint _forcedWithdrawalFee
)
external
virtual;
/// @dev Updates the global protocol fee settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateProtocolFeeSettings(
uint8 _protocolTakerFeeBips,
uint8 _protocolMakerFeeBips
)
external
virtual;
/// @dev Gets the amount of staked LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @return stakedLRC The amount of LRC
function getExchangeStake(
address exchangeAddr
)
public
virtual
view
returns (uint stakedLRC);
/// @dev Burns a certain amount of staked LRC for a specific exchange.
/// This function is meant to be called only from exchange contracts.
/// @return burnedLRC The amount of LRC burned. If the amount is greater than
/// the staked amount, all staked LRC will be burned.
function burnExchangeStake(
uint amount
)
external
virtual
returns (uint burnedLRC);
/// @dev Stakes more LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @param amountLRC The amount of LRC to stake
/// @return stakedLRC The total amount of LRC staked for the exchange
function depositExchangeStake(
address exchangeAddr,
uint amountLRC
)
external
virtual
returns (uint stakedLRC);
/// @dev Withdraws a certain amount of staked LRC for an exchange to the given address.
/// This function is meant to be called only from within exchange contracts.
/// @param recipient The address to receive LRC
/// @param requestedAmount The amount of LRC to withdraw
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient,
uint requestedAmount
)
external
virtual
returns (uint amountLRC);
/// @dev Gets the protocol fee values for an exchange.
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
function getProtocolFeeValues(
)
public
virtual
view
returns (
uint8 takerFeeBips,
uint8 makerFeeBips
);
}
/// @title ExchangeData
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeData
{
// -- Enums --
enum TransactionType
{
NOOP,
DEPOSIT,
WITHDRAWAL,
TRANSFER,
SPOT_TRADE,
ACCOUNT_UPDATE,
AMM_UPDATE
}
// -- Structs --
struct Token
{
address token;
}
struct ProtocolFeeData
{
uint32 syncedAt; // only valid before 2105 (85 years to go)
uint8 takerFeeBips;
uint8 makerFeeBips;
uint8 previousTakerFeeBips;
uint8 previousMakerFeeBips;
}
// General auxiliary data for each conditional transaction
struct AuxiliaryData
{
uint txIndex;
bytes data;
}
// This is the (virtual) block the owner needs to submit onchain to maintain the
// per-exchange (virtual) blockchain.
struct Block
{
uint8 blockType;
uint16 blockSize;
uint8 blockVersion;
bytes data;
uint256[8] proof;
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
// Block specific data that is only used to help process the block on-chain.
// It is not used as input for the circuits and it is not necessary for data-availability.
AuxiliaryData[] auxiliaryData;
// Arbitrary data, mainly for off-chain data-availability, i.e.,
// the multihash of the IPFS file that contains the block data.
bytes offchainData;
}
struct BlockInfo
{
// The time the block was submitted on-chain.
uint32 timestamp;
// The public data hash of the block (the 28 most significant bytes).
bytes28 blockDataHash;
}
// Represents an onchain deposit request.
struct Deposit
{
uint96 amount;
uint64 timestamp;
}
// A forced withdrawal request.
// If the actual owner of the account initiated the request (we don't know who the owner is
// at the time the request is being made) the full balance will be withdrawn.
struct ForcedWithdrawal
{
address owner;
uint64 timestamp;
}
struct Constants
{
uint SNARK_SCALAR_FIELD;
uint MAX_OPEN_FORCED_REQUESTS;
uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE;
uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS;
uint MAX_NUM_ACCOUNTS;
uint MAX_NUM_TOKENS;
uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED;
uint MIN_TIME_IN_SHUTDOWN;
uint TX_DATA_AVAILABILITY_SIZE;
uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND;
}
function SNARK_SCALAR_FIELD() internal pure returns (uint) {
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
return 21888242871839275222246405745257275088548364400416034343698204186575808495617;
}
function MAX_OPEN_FORCED_REQUESTS() internal pure returns (uint16) { return 4096; }
function MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE() internal pure returns (uint32) { return 15 days; }
function TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS() internal pure returns (uint32) { return 7 days; }
function MAX_NUM_ACCOUNTS() internal pure returns (uint) { return 2 ** 32; }
function MAX_NUM_TOKENS() internal pure returns (uint) { return 2 ** 16; }
function MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED() internal pure returns (uint32) { return 7 days; }
function MIN_TIME_IN_SHUTDOWN() internal pure returns (uint32) { return 30 days; }
// The amount of bytes each rollup transaction uses in the block data for data-availability.
// This is the maximum amount of bytes of all different transaction types.
function TX_DATA_AVAILABILITY_SIZE() internal pure returns (uint32) { return 68; }
function MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND() internal pure returns (uint32) { return 15 days; }
function ACCOUNTID_PROTOCOLFEE() internal pure returns (uint32) { return 0; }
function TX_DATA_AVAILABILITY_SIZE_PART_1() internal pure returns (uint32) { return 29; }
function TX_DATA_AVAILABILITY_SIZE_PART_2() internal pure returns (uint32) { return 39; }
struct AccountLeaf
{
uint32 accountID;
address owner;
uint pubKeyX;
uint pubKeyY;
uint32 nonce;
uint feeBipsAMM;
}
struct BalanceLeaf
{
uint16 tokenID;
uint96 balance;
uint96 weightAMM;
uint storageRoot;
}
struct MerkleProof
{
ExchangeData.AccountLeaf accountLeaf;
ExchangeData.BalanceLeaf balanceLeaf;
uint[48] accountMerkleProof;
uint[24] balanceMerkleProof;
}
struct BlockContext
{
bytes32 DOMAIN_SEPARATOR;
uint32 timestamp;
}
// Represents the entire exchange state except the owner of the exchange.
struct State
{
uint32 maxAgeDepositUntilWithdrawable;
bytes32 DOMAIN_SEPARATOR;
ILoopringV3 loopring;
IBlockVerifier blockVerifier;
IAgentRegistry agentRegistry;
IDepositContract depositContract;
// The merkle root of the offchain data stored in a Merkle tree. The Merkle tree
// stores balances for users using an account model.
bytes32 merkleRoot;
// List of all blocks
mapping(uint => BlockInfo) blocks;
uint numBlocks;
// List of all tokens
Token[] tokens;
// A map from a token to its tokenID + 1
mapping (address => uint16) tokenToTokenId;
// A map from an accountID to a tokenID to if the balance is withdrawn
mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode;
// A map from an account to a token to the amount withdrawable for that account.
// This is only used when the automatic distribution of the withdrawal failed.
mapping (address => mapping (uint16 => uint)) amountWithdrawable;
// A map from an account to a token to the forced withdrawal (always full balance)
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
// A map from an address to a token to a deposit
mapping (address => mapping (uint16 => Deposit)) pendingDeposits;
// A map from an account owner to an approved transaction hash to if the transaction is approved or not
mapping (address => mapping (bytes32 => bool)) approvedTx;
// A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address
mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient;
// Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner
uint32 numPendingForcedTransactions;
// Cached data for the protocol fee
ProtocolFeeData protocolFeeData;
// Time when the exchange was shutdown
uint shutdownModeStartTime;
// Time when the exchange has entered withdrawal mode
uint withdrawalModeStartTime;
// Last time the protocol fee was withdrawn for a specific token
mapping (address => uint) protocolFeeLastWithdrawnTime;
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeSignatures.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeSignatures
{
using SignatureUtil for bytes32;
function requireAuthorizedTx(
ExchangeData.State storage S,
address signer,
bytes memory signature,
bytes32 txHash
)
internal // inline call
{
require(signer != address(0), "INVALID_SIGNER");
// Verify the signature if one is provided, otherwise fall back to an approved tx
if (signature.length > 0) {
require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE");
} else {
require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED");
delete S.approvedTx[signer][txHash];
}
}
}
/// @title AmmUpdateTransaction
/// @author Brecht Devos - <[email protected]>
library AmmUpdateTransaction
{
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public AMMUPDATE_TYPEHASH = keccak256(
"AmmUpdate(address owner,uint32 accountID,uint16 tokenID,uint8 feeBips,uint96 tokenWeight,uint32 validUntil,uint32 nonce)"
);
struct AmmUpdate
{
address owner;
uint32 accountID;
uint16 tokenID;
uint8 feeBips;
uint96 tokenWeight;
uint32 validUntil;
uint32 nonce;
uint96 balance;
}
// Auxiliary data for each AMM update
struct AmmUpdateAuxiliaryData
{
bytes signature;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read in the AMM update
AmmUpdate memory update = readTx(data, offset);
AmmUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AmmUpdateAuxiliaryData));
// Check validUntil
require(ctx.timestamp < auxData.validUntil, "AMM_UPDATE_EXPIRED");
update.validUntil = auxData.validUntil;
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, update);
// Check the on-chain authorization
S.requireAuthorizedTx(update.owner, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset
)
internal
pure
returns (AmmUpdate memory update)
{
uint _offset = offset;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
update.owner = data.toAddress(_offset);
_offset += 20;
update.accountID = data.toUint32(_offset);
_offset += 4;
update.tokenID = data.toUint16(_offset);
_offset += 2;
update.feeBips = data.toUint8(_offset);
_offset += 1;
update.tokenWeight = data.toUint96(_offset);
_offset += 12;
update.nonce = data.toUint32(_offset);
_offset += 4;
update.balance = data.toUint96(_offset);
_offset += 12;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
AmmUpdate memory update
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
AMMUPDATE_TYPEHASH,
update.owner,
update.accountID,
update.tokenID,
update.feeBips,
update.tokenWeight,
update.validUntil,
update.nonce
)
)
);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title BlockReader
/// @author Brecht Devos - <[email protected]>
/// @dev Utility library to read block data.
library BlockReader {
using BlockReader for ExchangeData.Block;
using BytesUtil for bytes;
uint public constant OFFSET_TO_TRANSACTIONS = 20 + 32 + 32 + 4 + 1 + 1 + 4 + 4;
struct BlockHeader
{
address exchange;
bytes32 merkleRootBefore;
bytes32 merkleRootAfter;
uint32 timestamp;
uint8 protocolTakerFeeBips;
uint8 protocolMakerFeeBips;
uint32 numConditionalTransactions;
uint32 operatorAccountID;
}
function readHeader(
ExchangeData.Block memory _block
)
internal
pure
returns (BlockHeader memory header)
{
uint offset = 0;
header.exchange = _block.data.toAddress(offset);
offset += 20;
header.merkleRootBefore = _block.data.toBytes32(offset);
offset += 32;
header.merkleRootAfter = _block.data.toBytes32(offset);
offset += 32;
header.timestamp = _block.data.toUint32(offset);
offset += 4;
header.protocolTakerFeeBips = _block.data.toUint8(offset);
offset += 1;
header.protocolMakerFeeBips = _block.data.toUint8(offset);
offset += 1;
header.numConditionalTransactions = _block.data.toUint32(offset);
offset += 4;
header.operatorAccountID = _block.data.toUint32(offset);
offset += 4;
assert(offset == OFFSET_TO_TRANSACTIONS);
}
function readTransactionData(
ExchangeData.Block memory _block,
uint txIdx
)
internal
pure
returns (bytes memory)
{
require(txIdx < _block.blockSize, "INVALID_TX_IDX");
bytes memory data = _block.data;
bytes memory txData = new bytes(ExchangeData.TX_DATA_AVAILABILITY_SIZE());
// Part 1
uint txDataOffset = OFFSET_TO_TRANSACTIONS +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1();
assembly {
mstore(add(txData, 32), mload(add(data, add(txDataOffset, 32))))
}
// Part 2
txDataOffset = OFFSET_TO_TRANSACTIONS +
_block.blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1() +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2();
assembly {
mstore(add(txData, 61 /*32 + 29*/), mload(add(data, add(txDataOffset, 32))))
mstore(add(txData, 68 ), mload(add(data, add(txDataOffset, 39))))
}
return txData;
}
}
// Copyright 2017 Loopring Technology Limited.
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
}
// Copyright 2017 Loopring Technology Limited.
/// @title AmmData
library AmmData
{
function POOL_TOKEN_BASE() internal pure returns (uint) { return 100 * (10 ** 8); }
function POOL_TOKEN_MINTED_SUPPLY() internal pure returns (uint) { return uint96(-1); }
enum PoolTxType
{
NOOP,
JOIN,
EXIT
}
struct PoolConfig
{
address sharedConfig;
address exchange;
string poolName;
uint32 accountID;
address[] tokens;
uint96[] weights;
uint8 feeBips;
string tokenSymbol;
}
struct PoolJoin
{
address owner;
uint96[] joinAmounts;
uint32[] joinStorageIDs;
uint96 mintMinAmount;
uint32 validUntil;
}
struct PoolExit
{
address owner;
uint96 burnAmount;
uint32 burnStorageID; // for pool token withdrawal from user to the pool
uint96[] exitMinAmounts; // the amount to receive BEFORE paying the fee.
uint96 fee;
uint32 validUntil;
}
struct PoolTx
{
PoolTxType txType;
bytes data;
bytes signature;
}
struct Token
{
address addr;
uint96 weight;
uint16 tokenID;
}
struct Context
{
// functional parameters
uint txIdx;
// Exchange state variables
IExchangeV3 exchange;
bytes32 exchangeDomainSeparator;
// AMM pool state variables
bytes32 domainSeparator;
uint32 accountID;
uint16 poolTokenID;
uint totalSupply;
Token[] tokens;
uint96[] tokenBalancesL2;
TransactionBuffer transactionBuffer;
}
struct TransactionBuffer
{
uint size;
address[] owners;
bytes32[] txHashes;
}
struct State {
// Pool token state variables
string poolName;
string symbol;
uint _totalSupply;
mapping(address => uint) balanceOf;
mapping(address => mapping(address => uint)) allowance;
mapping(address => uint) nonces;
// AMM pool state variables
IAmmSharedConfig sharedConfig;
Token[] tokens;
// The order of the following variables important to minimize loads
bytes32 exchangeDomainSeparator;
bytes32 domainSeparator;
IExchangeV3 exchange;
uint32 accountID;
uint16 poolTokenID;
uint8 feeBips;
address exchangeOwner;
uint64 shutdownTimestamp;
uint16 forcedExitCount;
// A map from a user to the forced exit.
mapping (address => PoolExit) forcedExit;
mapping (bytes32 => bool) approvedTx;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockReceiver
/// @author Brecht Devos - <[email protected]>
abstract contract IBlockReceiver
{
function beforeBlockSubmission(
ExchangeData.Block memory _block,
bytes memory data,
uint txIdx,
uint numTxs
)
external
virtual;
}
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
/// @title DepositTransaction
/// @author Brecht Devos - <[email protected]>
library DepositTransaction
{
using BytesUtil for bytes;
using MathUint96 for uint96;
struct Deposit
{
address to;
uint32 toAccountID;
uint16 tokenID;
uint96 amount;
}
/*event DepositProcessed(
address to,
uint32 toAccountId,
uint16 token,
uint amount
);*/
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory /*ctx*/,
bytes memory data,
uint offset,
bytes memory /*auxiliaryData*/
)
internal
{
// Read in the deposit
Deposit memory deposit = readTx(data, offset);
// Process the deposit
ExchangeData.Deposit memory pendingDeposit = S.pendingDeposits[deposit.to][deposit.tokenID];
// Make sure the deposit was actually done
require(pendingDeposit.timestamp > 0, "DEPOSIT_DOESNT_EXIST");
// Processing partial amounts of the deposited amount is allowed.
// This is done to ensure the user can do multiple deposits after each other
// without invalidating work done by the exchange owner for previous deposit amounts.
// Also note the original deposit.amount can be zero!
if (deposit.amount > 0) {
require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT");
pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount);
}
// If the deposit was fully consumed, reset it so the storage is freed up
// and the owner receives a gas refund.
if (pendingDeposit.amount == 0) {
delete S.pendingDeposits[deposit.to][deposit.tokenID];
} else {
S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit;
}
//emit DepositProcessed(deposit.to, deposit.toAccountID, deposit.tokenID, deposit.amount);
}
function readTx(
bytes memory data,
uint offset
)
internal
pure
returns (Deposit memory deposit)
{
uint _offset = offset;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
deposit.to = data.toAddress(_offset);
_offset += 20;
deposit.toAccountID = data.toUint32(_offset);
_offset += 4;
deposit.tokenID = data.toUint16(_offset);
_offset += 2;
deposit.amount = data.toUint96(_offset);
_offset += 12;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title TransferTransaction
/// @author Brecht Devos - <[email protected]>
library TransferTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public TRANSFER_TYPEHASH = keccak256(
"Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)"
);
struct Transfer
{
uint32 fromAccountID;
uint32 toAccountID;
address from;
address to;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint32 validUntil;
uint32 storageID;
}
// Auxiliary data for each transfer
struct TransferAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
/*event ConditionalTransferProcessed(
address from,
address to,
uint16 token,
uint amount
);*/
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the transfer
Transfer memory transfer = readTx(data, offset);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
// Fill in withdrawal data missing from DA
transfer.validUntil = auxData.validUntil;
transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED");
require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer);
// Check the on-chain authorization
S.requireAuthorizedTx(transfer.from, auxData.signature, txHash);
//emit ConditionalTransferProcessed(from, to, tokenID, amount);
}
function readTx(
bytes memory data,
uint offset
)
internal
pure
returns (Transfer memory transfer)
{
uint _offset = offset;
// Check that this is a conditional transfer
require(data.toUint8(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
transfer.fromAccountID = data.toUint32(_offset);
_offset += 4;
transfer.toAccountID = data.toUint32(_offset);
_offset += 4;
transfer.tokenID = data.toUint16(_offset);
_offset += 2;
transfer.amount = uint(data.toUint24(_offset)).decodeFloat(24);
_offset += 3;
transfer.feeTokenID = data.toUint16(_offset);
_offset += 2;
transfer.fee = uint(data.toUint16(_offset)).decodeFloat(16);
_offset += 2;
transfer.storageID = data.toUint32(_offset);
_offset += 4;
transfer.to = data.toAddress(_offset);
_offset += 20;
transfer.from = data.toAddress(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Transfer memory transfer
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
TRANSFER_TYPEHASH,
transfer.from,
transfer.to,
transfer.tokenID,
transfer.amount,
transfer.feeTokenID,
transfer.maxFee,
transfer.validUntil,
transfer.storageID
)
)
);
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeMode.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeMode
{
using MathUint for uint;
function isInWithdrawalMode(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool result)
{
result = S.withdrawalModeStartTime > 0;
}
function isShutdown(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool)
{
return S.shutdownModeStartTime > 0;
}
function getNumAvailableForcedSlots(
ExchangeData.State storage S
)
internal
view
returns (uint)
{
return ExchangeData.MAX_OPEN_FORCED_REQUESTS() - S.numPendingForcedTransactions;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeWithdrawals.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeWithdrawals
{
enum WithdrawalCategory
{
DISTRIBUTION,
FROM_MERKLE_TREE,
FROM_DEPOSIT_REQUEST,
FROM_APPROVED_WITHDRAWAL
}
using AddressUtil for address;
using AddressUtil for address payable;
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeBalances for ExchangeData.State;
using ExchangeMode for ExchangeData.State;
using ExchangeTokens for ExchangeData.State;
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
function forceWithdraw(
ExchangeData.State storage S,
address owner,
address token,
uint32 accountID
)
public
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN");
require(accountID < ExchangeData.MAX_NUM_ACCOUNTS(), "INVALID_ACCOUNTID");
uint16 tokenID = S.getTokenID(token);
uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee();
// Check ETH value sent, can be larger than the expected withdraw fee
require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE");
// Send surplus of ETH back to the sender
uint feeSurplus = msg.value.sub(withdrawalFeeETH);
if (feeSurplus > 0) {
msg.sender.sendETHAndVerify(feeSurplus, gasleft());
}
require(
S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0,
"WITHDRAWAL_ALREADY_PENDING"
);
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({
owner: owner,
timestamp: uint64(block.timestamp)
});
S.numPendingForcedTransactions++;
emit ForcedWithdrawalRequested(
owner,
token,
accountID
);
}
// We still alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree(
ExchangeData.State storage S,
ExchangeData.MerkleProof calldata merkleProof
)
public
{
require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE");
address owner = merkleProof.accountLeaf.owner;
uint32 accountID = merkleProof.accountLeaf.accountID;
uint16 tokenID = merkleProof.balanceLeaf.tokenID;
uint96 balance = merkleProof.balanceLeaf.balance;
require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY");
ExchangeBalances.verifyAccountBalance(
uint(S.merkleRoot),
merkleProof
);
// Make sure the balance can only be withdrawn once
S.withdrawnInWithdrawMode[accountID][tokenID] = true;
// Transfer the tokens
transferTokens(
S,
uint8(WithdrawalCategory.FROM_MERKLE_TREE),
owner,
owner,
tokenID,
balance,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromDepositRequest(
ExchangeData.State storage S,
address owner,
address token
)
public
{
uint16 tokenID = S.getTokenID(token);
ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID];
require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET");
// Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode
require(
block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable ||
S.isInWithdrawalMode(),
"DEPOSIT_NOT_WITHDRAWABLE_YET"
);
uint amount = deposit.amount;
// Reset the deposit request
delete S.pendingDeposits[owner][tokenID];
// Transfer the tokens
transferTokens(
S,
uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromApprovedWithdrawals(
ExchangeData.State storage S,
address[] memory owners,
address[] memory tokens
)
public
{
require(owners.length == tokens.length, "INVALID_INPUT_DATA");
for (uint i = 0; i < owners.length; i++) {
address owner = owners[i];
uint16 tokenID = S.getTokenID(tokens[i]);
uint amount = S.amountWithdrawable[owner][tokenID];
// Make sure this amount can't be withdrawn again
delete S.amountWithdrawable[owner][tokenID];
// Transfer the tokens
transferTokens(
S,
uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
}
function distributeWithdrawal(
ExchangeData.State storage S,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit
)
public
{
// Try to transfer the tokens
bool success = transferTokens(
S,
uint8(WithdrawalCategory.DISTRIBUTION),
from,
to,
tokenID,
amount,
extraData,
gasLimit,
true
);
if (!success) {
// Allow the amount to be withdrawn using `withdrawFromApprovedWithdrawal`.
S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount);
}
}
// == Internal and Private Functions ==
// If allowFailure is true the transfer can fail because of a transfer error or
// because the transfer uses more than `gasLimit` gas. The function
// will return true when successful, false otherwise.
// If allowFailure is false the transfer is guaranteed to succeed using
// as much gas as needed, otherwise it throws. The function always returns true.
function transferTokens(
ExchangeData.State storage S,
uint8 category,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit,
bool allowFailure
)
private
returns (bool success)
{
if (to == address(0)) {
to = S.loopring.protocolFeeVault();
}
address token = S.getTokenAddress(tokenID);
// Transfer the tokens from the deposit contract to the owner
if (gasLimit > 0) {
try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) {
success = true;
} catch {
success = false;
}
} else {
success = false;
}
require(allowFailure || success, "TRANSFER_FAILURE");
if (success) {
emit WithdrawalCompleted(category, from, to, token, amount);
if (from == address(0)) {
S.protocolFeeLastWithdrawnTime[token] = block.timestamp;
}
} else {
emit WithdrawalFailed(category, from, to, token, amount);
}
}
}
/// @title WithdrawTransaction
/// @author Brecht Devos - <[email protected]>
/// @dev The following 4 types of withdrawals are supported:
/// - withdrawType = 0: offchain withdrawals with EdDSA signatures
/// - withdrawType = 1: offchain withdrawals with ECDSA signatures or onchain appprovals
/// - withdrawType = 2: onchain valid forced withdrawals (owner and accountID match), or
/// offchain operator-initiated withdrawals for protocol fees or for
/// users in shutdown mode
/// - withdrawType = 3: onchain invalid forced withdrawals (owner and accountID mismatch)
library WithdrawTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint;
using MathUint for uint;
using ExchangeMode for ExchangeData.State;
using ExchangeSignatures for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
bytes32 constant public WITHDRAWAL_TYPEHASH = keccak256(
"Withdrawal(address owner,uint32 accountID,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,address to,bytes extraData,uint256 minGas,uint32 validUntil,uint32 storageID)"
);
struct Withdrawal
{
uint withdrawalType;
address from;
uint32 fromAccountID;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
address to;
bytes extraData;
uint minGas;
uint32 validUntil;
uint32 storageID;
bytes20 onchainDataHash;
}
// Auxiliary data for each withdrawal
struct WithdrawalAuxiliaryData
{
bool storeRecipient;
uint gasLimit;
bytes signature;
uint minGas;
address to;
bytes extraData;
uint96 maxFee;
uint32 validUntil;
}
/*event ForcedWithdrawalProcessed(
uint32 accountID,
uint16 tokenID,
uint amount
);*/
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
Withdrawal memory withdrawal = readTx(data, offset);
WithdrawalAuxiliaryData memory auxData = abi.decode(auxiliaryData, (WithdrawalAuxiliaryData));
// Validate the withdrawal data not directly part of the DA
bytes20 onchainDataHash = hashOnchainData(
auxData.minGas,
auxData.to,
auxData.extraData
);
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
require(withdrawal.onchainDataHash == onchainDataHash, "INVALID_WITHDRAWAL_DATA");
// Fill in withdrawal data missing from DA
withdrawal.to = auxData.to;
withdrawal.minGas = auxData.minGas;
withdrawal.extraData = auxData.extraData;
withdrawal.maxFee = auxData.maxFee == 0 ? withdrawal.fee : auxData.maxFee;
withdrawal.validUntil = auxData.validUntil;
if (withdrawal.withdrawalType == 0) {
// Signature checked offchain, nothing to do
} else if (withdrawal.withdrawalType == 1) {
// Validate
require(ctx.timestamp < withdrawal.validUntil, "WITHDRAWAL_EXPIRED");
require(withdrawal.fee <= withdrawal.maxFee, "WITHDRAWAL_FEE_TOO_HIGH");
// Check appproval onchain
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, withdrawal);
// Check onchain authorization
S.requireAuthorizedTx(withdrawal.from, auxData.signature, txHash);
} else if (withdrawal.withdrawalType == 2 || withdrawal.withdrawalType == 3) {
// Forced withdrawals cannot make use of certain features because the
// necessary data is not authorized by the account owner.
// For protocol fee withdrawals, `owner` and `to` are both address(0).
require(withdrawal.from == withdrawal.to, "INVALID_WITHDRAWAL_ADDRESS");
// Forced withdrawal fees are charged when the request is submitted.
require(withdrawal.fee == 0, "FEE_NOT_ZERO");
require(withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
ExchangeData.ForcedWithdrawal memory forcedWithdrawal =
S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
if (forcedWithdrawal.timestamp != 0) {
if (withdrawal.withdrawalType == 2) {
require(withdrawal.from == forcedWithdrawal.owner, "INCONSISENT_OWNER");
} else { //withdrawal.withdrawalType == 3
require(withdrawal.from != forcedWithdrawal.owner, "INCONSISENT_OWNER");
require(withdrawal.amount == 0, "UNAUTHORIZED_WITHDRAWAL");
}
// delete the withdrawal request and free a slot
delete S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
S.numPendingForcedTransactions--;
/*emit ForcedWithdrawalProcessed(
withdrawal.fromAccountID,
withdrawal.tokenID,
withdrawal.amount
);*/
} else {
// Allow the owner to submit full withdrawals without authorization
// - when in shutdown mode
// - to withdraw protocol fees
require(
withdrawal.fromAccountID == ExchangeData.ACCOUNTID_PROTOCOLFEE() ||
S.isShutdown(),
"FULL_WITHDRAWAL_UNAUTHORIZED"
);
}
} else {
revert("INVALID_WITHDRAWAL_TYPE");
}
// Check if there is a withdrawal recipient
address recipient = S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
if (recipient != address(0)) {
// Auxiliary data is not supported
require (withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
// Set the new recipient address
withdrawal.to = recipient;
// Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped)
withdrawal.minGas = 0;
// Do NOT delete the recipient to prevent replay attack
// delete S.withdrawalRecipient[withdrawal.owner][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
} else if (auxData.storeRecipient) {
// Store the destination address to mark the withdrawal as done
require(withdrawal.to != address(0), "INVALID_DESTINATION_ADDRESS");
S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID] = withdrawal.to;
}
// Validate gas provided
require(auxData.gasLimit >= withdrawal.minGas, "OUT_OF_GAS_FOR_WITHDRAWAL");
// Try to transfer the tokens with the provided gas limit
S.distributeWithdrawal(
withdrawal.from,
withdrawal.to,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.extraData,
auxData.gasLimit
);
}
function readTx(
bytes memory data,
uint offset
)
internal
pure
returns (Withdrawal memory withdrawal)
{
uint _offset = offset;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
withdrawal.withdrawalType = data.toUint8(_offset);
_offset += 1;
withdrawal.from = data.toAddress(_offset);
_offset += 20;
withdrawal.fromAccountID = data.toUint32(_offset);
_offset += 4;
withdrawal.tokenID = data.toUint16(_offset);
_offset += 2;
withdrawal.amount = data.toUint96(_offset);
_offset += 12;
withdrawal.feeTokenID = data.toUint16(_offset);
_offset += 2;
withdrawal.fee = uint(data.toUint16(_offset)).decodeFloat(16);
_offset += 2;
withdrawal.storageID = data.toUint32(_offset);
_offset += 4;
withdrawal.onchainDataHash = data.toBytes20(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Withdrawal memory withdrawal
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
WITHDRAWAL_TYPEHASH,
withdrawal.from,
withdrawal.fromAccountID,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.feeTokenID,
withdrawal.maxFee,
withdrawal.to,
keccak256(withdrawal.extraData),
withdrawal.minGas,
withdrawal.validUntil,
withdrawal.storageID
)
)
);
}
function hashOnchainData(
uint minGas,
address to,
bytes memory extraData
)
internal
pure
returns (bytes20)
{
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
return bytes20(keccak256(
abi.encodePacked(
minGas,
to,
extraData
)
));
}
}
/// @title TransactionReader
/// @author Brecht Devos - <[email protected]>
/// @dev Utility library to read transactions.
library TransactionReader {
using BlockReader for ExchangeData.Block;
using TransactionReader for ExchangeData.Block;
using BytesUtil for bytes;
function readDeposit(
ExchangeData.Block memory _block,
uint txIdx
)
internal
pure
returns (DepositTransaction.Deposit memory)
{
bytes memory data = _block.readTx(txIdx, ExchangeData.TransactionType.DEPOSIT);
return DepositTransaction.readTx(data, 1);
}
function readWithdrawal(
ExchangeData.Block memory _block,
uint txIdx
)
internal
pure
returns (WithdrawTransaction.Withdrawal memory)
{
bytes memory data = _block.readTx(txIdx, ExchangeData.TransactionType.WITHDRAWAL);
return WithdrawTransaction.readTx(data, 1);
}
function readAmmUpdate(
ExchangeData.Block memory _block,
uint txIdx
)
internal
pure
returns (AmmUpdateTransaction.AmmUpdate memory)
{
bytes memory data = _block.readTx(txIdx, ExchangeData.TransactionType.AMM_UPDATE);
return AmmUpdateTransaction.readTx(data, 1);
}
function readTransfer(
ExchangeData.Block memory _block,
uint txIdx
)
internal
pure
returns (TransferTransaction.Transfer memory)
{
bytes memory data = _block.readTx(txIdx, ExchangeData.TransactionType.TRANSFER);
return TransferTransaction.readTx(data, 1);
}
function readTx(
ExchangeData.Block memory _block,
uint txIdx,
ExchangeData.TransactionType txType
)
internal
pure
returns (bytes memory data)
{
data = _block.readTransactionData(txIdx);
require(txType == ExchangeData.TransactionType(data.toUint8(0)), "UNEXPTECTED_TX_TYPE");
}
function createMinimalBlock(
ExchangeData.Block memory _block,
uint txIdx,
uint16 numTransactions
)
internal
pure
returns (ExchangeData.Block memory)
{
ExchangeData.Block memory minimalBlock = ExchangeData.Block({
blockType: _block.blockType,
blockSize: numTransactions,
blockVersion: _block.blockVersion,
data: new bytes(0),
proof: _block.proof,
storeBlockInfoOnchain: _block.storeBlockInfoOnchain,
auxiliaryData: new ExchangeData.AuxiliaryData[](0),
offchainData: new bytes(0)
});
bytes memory header = _block.data.slice(0, BlockReader.OFFSET_TO_TRANSACTIONS);
// Extract the data of the transactions we want
// Part 1
uint txDataOffset = BlockReader.OFFSET_TO_TRANSACTIONS +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1();
bytes memory dataPart1 = _block.data.slice(txDataOffset, numTransactions * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1());
// Part 2
txDataOffset = BlockReader.OFFSET_TO_TRANSACTIONS +
_block.blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1() +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2();
bytes memory dataPart2 = _block.data.slice(txDataOffset, numTransactions * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2());
// Set the data on the block in the standard format
minimalBlock.data = header.concat(dataPart1).concat(dataPart2);
return minimalBlock;
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
/// @title ZeroDecompressor
/// @author Brecht Devos - <[email protected]>
/// @dev Easy decompressor that compresses runs of zeros.
/// The format is very simple. Each entry consists of
/// (uint16 numDataBytes, uint16 numZeroBytes) which will
/// copy `numDataBytes` data bytes from `data` and will
/// add an additional `numZeroBytes` after it.
library ZeroDecompressor
{
function decompress(
bytes calldata /*data*/,
uint parameterIdx
)
internal
pure
returns (bytes memory)
{
bytes memory uncompressed;
uint offsetPos = 4 + 32 * parameterIdx;
assembly {
uncompressed := mload(0x40)
let ptr := add(uncompressed, 32)
let offset := add(4, calldataload(offsetPos))
let pos := add(offset, 4)
let dataLength := add(calldataload(offset), pos)
let tupple := 0
let numDataBytes := 0
let numZeroBytes := 0
for {} lt(pos, dataLength) {} {
tupple := and(calldataload(pos), 0xFFFFFFFF)
numDataBytes := shr(16, tupple)
numZeroBytes := and(tupple, 0xFFFF)
calldatacopy(ptr, add(32, pos), numDataBytes)
pos := add(pos, add(4, numDataBytes))
ptr := add(ptr, add(numDataBytes, numZeroBytes))
}
// Store data length
mstore(uncompressed, sub(sub(ptr, uncompressed), 32))
// Update free memory pointer
mstore(0x40, add(ptr, 0x20))
}
return uncompressed;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title IExchangeV3
/// @dev Note that Claimable and RentrancyGuard are inherited here to
/// ensure all data members are declared on IExchangeV3 to make it
/// easy to support upgradability through proxies.
///
/// Subclasses of this contract must NOT define constructor to
/// initialize data.
///
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract IExchangeV3 is Claimable
{
// -- Events --
event ExchangeCloned(
address exchangeAddress,
address owner,
bytes32 genesisMerkleRoot
);
event TokenRegistered(
address token,
uint16 tokenId
);
event Shutdown(
uint timestamp
);
event WithdrawalModeActivated(
uint timestamp
);
event BlockSubmitted(
uint indexed blockIdx,
bytes32 merkleRoot,
bytes32 publicDataHash
);
event DepositRequested(
address from,
address to,
address token,
uint16 tokenId,
uint96 amount
);
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
event ProtocolFeesUpdated(
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
event TransactionApproved(
address owner,
bytes32 transactionHash
);
// events from libraries
/*event DepositProcessed(
address to,
uint32 toAccountId,
uint16 token,
uint amount
);*/
/*event ForcedWithdrawalProcessed(
uint32 fromAccountID,
uint16 tokenID,
uint amount
);*/
/*event ConditionalTransferProcessed(
address from,
address to,
uint16 token,
uint amount
);*/
/*event AccountUpdated(
uint32 owner,
uint publicKey
);*/
// -- Initialization --
/// @dev Initializes this exchange. This method can only be called once.
/// @param loopring The LoopringV3 contract address.
/// @param owner The owner of this exchange.
/// @param genesisMerkleRoot The initial Merkle tree state.
function initialize(
address loopring,
address owner,
bytes32 genesisMerkleRoot
)
virtual
external;
/// @dev Initialized the agent registry contract used by the exchange.
/// Can only be called by the exchange owner once.
/// @param agentRegistry The agent registry contract to be used
function setAgentRegistry(address agentRegistry)
external
virtual;
/// @dev Gets the agent registry contract used by the exchange.
/// @return the agent registry contract
function getAgentRegistry()
external
virtual
view
returns (IAgentRegistry);
/// Can only be called by the exchange owner once.
/// @param depositContract The deposit contract to be used
function setDepositContract(address depositContract)
external
virtual;
/// @dev Gets the deposit contract used by the exchange.
/// @return the deposit contract
function getDepositContract()
external
virtual
view
returns (IDepositContract);
// @dev Exchange owner withdraws fees from the exchange.
// @param token Fee token address
// @param feeRecipient Fee recipient address
function withdrawExchangeFees(
address token,
address feeRecipient
)
external
virtual;
// -- Constants --
/// @dev Returns a list of constants used by the exchange.
/// @return constants The list of constants.
function getConstants()
external
virtual
pure
returns(ExchangeData.Constants memory);
// -- Mode --
/// @dev Returns hether the exchange is in withdrawal mode.
/// @return Returns true if the exchange is in withdrawal mode, else false.
function isInWithdrawalMode()
external
virtual
view
returns (bool);
/// @dev Returns whether the exchange is shutdown.
/// @return Returns true if the exchange is shutdown, else false.
function isShutdown()
external
virtual
view
returns (bool);
// -- Tokens --
/// @dev Registers an ERC20 token for a token id. Note that different exchanges may have
/// different ids for the same ERC20 token.
///
/// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH),
/// and 3 is reserved for Loopring Token (LRC).
///
/// This function is only callable by the exchange owner.
///
/// @param tokenAddress The token's address
/// @return tokenID The token's ID in this exchanges.
function registerToken(
address tokenAddress
)
external
virtual
returns (uint16 tokenID);
/// @dev Returns the id of a registered token.
/// @param tokenAddress The token's address
/// @return tokenID The token's ID in this exchanges.
function getTokenID(
address tokenAddress
)
external
virtual
view
returns (uint16 tokenID);
/// @dev Returns the address of a registered token.
/// @param tokenID The token's ID in this exchanges.
/// @return tokenAddress The token's address
function getTokenAddress(
uint16 tokenID
)
external
virtual
view
returns (address tokenAddress);
// -- Stakes --
/// @dev Gets the amount of LRC the owner has staked onchain for this exchange.
/// The stake will be burned if the exchange does not fulfill its duty by
/// processing user requests in time. Please note that order matching may potentially
/// performed by another party and is not part of the exchange's duty.
///
/// @return The amount of LRC staked
function getExchangeStake()
external
virtual
view
returns (uint);
/// @dev Withdraws the amount staked for this exchange.
/// This can only be done if the exchange has been correctly shutdown:
/// - The exchange owner has shutdown the exchange
/// - All deposit requests are processed
/// - All funds are returned to the users (merkle root is reset to initial state)
///
/// Can only be called by the exchange owner.
///
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient
)
external
virtual
returns (uint amountLRC);
/// @dev Can by called by anyone to burn the stake of the exchange when certain
/// conditions are fulfilled.
///
/// Currently this will only burn the stake of the exchange if
/// the exchange is in withdrawal mode.
function burnExchangeStake()
external
virtual;
// -- Blocks --
/// @dev Gets the current Merkle root of this exchange's virtual blockchain.
/// @return The current Merkle root.
function getMerkleRoot()
external
virtual
view
returns (bytes32);
/// @dev Gets the height of this exchange's virtual blockchain. The block height for a
/// new exchange is 1.
/// @return The virtual blockchain height which is the index of the last block.
function getBlockHeight()
external
virtual
view
returns (uint);
/// @dev Gets some minimal info of a previously submitted block that's kept onchain.
/// A DEX can use this function to implement a payment receipt verification
/// contract with a challange-response scheme.
/// @param blockIdx The block index.
function getBlockInfo(uint blockIdx)
external
virtual
view
returns (ExchangeData.BlockInfo memory);
/// @dev Sumbits new blocks to the rollup blockchain.
///
/// This function can only be called by the exchange operator.
///
/// @param blocks The blocks being submitted
/// - blockType: The type of the new block
/// - blockSize: The number of onchain or offchain requests/settlements
/// that have been processed in this block
/// - blockVersion: The circuit version to use for verifying the block
/// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain
/// - data: The data for this block
/// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e.,
/// the multihash of the IPFS file that contains the block data.
function submitBlocks(ExchangeData.Block[] calldata blocks)
external
virtual;
/// @dev Gets the number of available forced request slots.
/// @return The number of available slots.
function getNumAvailableForcedSlots()
external
virtual
view
returns (uint);
// -- Deposits --
/// @dev Deposits Ether or ERC20 tokens to the specified account.
///
/// This function is only callable by an agent of 'from'.
///
/// A fee to the owner is paid in ETH to process the deposit.
/// The operator is not forced to do the deposit and the user can send
/// any fee amount.
///
/// @param from The address that deposits the funds to the exchange
/// @param to The account owner's address receiving the funds
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @param amount The amount of tokens to deposit
/// @param auxiliaryData Optional extra data used by the deposit contract
function deposit(
address from,
address to,
address tokenAddress,
uint96 amount,
bytes calldata auxiliaryData
)
external
virtual
payable;
/// @dev Gets the amount of tokens that may be added to the owner's account.
/// @param owner The destination address for the amount deposited.
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @return The amount of tokens pending.
function getPendingDepositAmount(
address owner,
address tokenAddress
)
external
virtual
view
returns (uint96);
// -- Withdrawals --
/// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens.
/// This request always withdraws the full balance.
///
/// This function is only callable by an agent of the account.
///
/// The total fee in ETH that the user needs to pay is 'withdrawalFee'.
/// If the user sends too much ETH the surplus is sent back immediately.
///
/// Note that after such an operation, it will take the owner some
/// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request
/// and create the deposit to the offchain account.
///
/// @param owner The expected owner of the account
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @param accountID The address the account in the Merkle tree.
function forceWithdraw(
address owner,
address tokenAddress,
uint32 accountID
)
external
virtual
payable;
/// @dev Checks if a forced withdrawal is pending for an account balance.
/// @param accountID The accountID of the account to check.
/// @param token The token address
/// @return True if a request is pending, false otherwise
function isForcedWithdrawalPending(
uint32 accountID,
address token
)
external
virtual
view
returns (bool);
/// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the
/// protocol fees account. The complete balance is always withdrawn.
///
/// Anyone can request a withdrawal of the protocol fees.
///
/// Note that after such an operation, it will take the owner some
/// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request
/// and create the deposit to the offchain account.
///
/// @param tokenAddress The address of the token, use `0x0` for Ether.
function withdrawProtocolFees(
address tokenAddress
)
external
virtual
payable;
/// @dev Gets the time the protocol fee for a token was last withdrawn.
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @return The time the protocol fee was last withdrawn.
function getProtocolFeeLastWithdrawnTime(
address tokenAddress
)
external
virtual
view
returns (uint);
/// @dev Allows anyone to withdraw funds for a specified user using the balances stored
/// in the Merkle tree. The funds will be sent to the owner of the acount.
///
/// Can only be used in withdrawal mode (i.e. when the owner has stopped
/// committing blocks and is not able to commit any more blocks).
///
/// This will NOT modify the onchain merkle root! The merkle root stored
/// onchain will remain the same after the withdrawal. We store if the user
/// has withdrawn the balance in State.withdrawnInWithdrawMode.
///
/// @param merkleProof The Merkle inclusion proof
function withdrawFromMerkleTree(
ExchangeData.MerkleProof calldata merkleProof
)
external
virtual;
/// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`.
/// @param accountID The accountID of the balance to check.
/// @param token The token address
/// @return True if it was already withdrawn, false otherwise
function isWithdrawnInWithdrawalMode(
uint32 accountID,
address token
)
external
virtual
view
returns (bool);
/// @dev Allows withdrawing funds deposited to the contract in a deposit request when
/// it was never processed by the owner within the maximum time allowed.
///
/// Can be called by anyone. The deposited tokens will be sent back to
/// the owner of the account they were deposited in.
///
/// @param owner The address of the account the withdrawal was done for.
/// @param token The token address
function withdrawFromDepositRequest(
address owner,
address token
)
external
virtual;
/// @dev Allows withdrawing funds after a withdrawal request (either onchain
/// or offchain) was submitted in a block by the operator.
///
/// Can be called by anyone. The withdrawn tokens will be sent to
/// the owner of the account they were withdrawn out.
///
/// Normally it is should not be needed for users to call this manually.
/// Funds from withdrawal requests will be sent to the account owner
/// immediately by the owner when the block is submitted.
/// The user will however need to call this manually if the transfer failed.
///
/// Tokens and owners must have the same size.
///
/// @param owners The addresses of the account the withdrawal was done for.
/// @param tokens The token addresses
function withdrawFromApprovedWithdrawals(
address[] calldata owners,
address[] calldata tokens
)
external
virtual;
/// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`.
/// @param owner The address of the account the withdrawal was done for.
/// @param token The token address
/// @return The amount withdrawable
function getAmountWithdrawable(
address owner,
address token
)
external
virtual
view
returns (uint);
/// @dev Notifies the exchange that the owner did not process a forced request.
/// If this is indeed the case, the exchange will enter withdrawal mode.
///
/// Can be called by anyone.
///
/// @param accountID The accountID the forced request was made for
/// @param token The token address of the the forced request
function notifyForcedRequestTooOld(
uint32 accountID,
address token
)
external
virtual;
/// @dev Allows a withdrawal to be done to an adddresss that is different
/// than initialy specified in the withdrawal request. This can be used to
/// implement functionality like fast withdrawals.
///
/// This function can only be called by an agent.
///
/// @param from The address of the account that does the withdrawal.
/// @param to The address to which 'amount' tokens were going to be withdrawn.
/// @param token The address of the token that is withdrawn ('0x0' for ETH).
/// @param amount The amount of tokens that are going to be withdrawn.
/// @param storageID The storageID of the withdrawal request.
/// @param newRecipient The new recipient address of the withdrawal.
function setWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID,
address newRecipient
)
external
virtual;
/// @dev Gets the withdrawal recipient.
///
/// @param from The address of the account that does the withdrawal.
/// @param to The address to which 'amount' tokens were going to be withdrawn.
/// @param token The address of the token that is withdrawn ('0x0' for ETH).
/// @param amount The amount of tokens that are going to be withdrawn.
/// @param storageID The storageID of the withdrawal request.
function getWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID
)
external
virtual
view
returns (address);
/// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance
/// the user has set for the exchange. This way the user only needs to approve a single exchange contract
/// for all exchange/agent features, which allows for a more seamless user experience.
///
/// This function can only be called by an agent.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function onchainTransferFrom(
address from,
address to,
address token,
uint amount
)
external
virtual;
/// @dev Allows an agent to approve a rollup tx.
///
/// This function can only be called by an agent.
///
/// @param owner The owner of the account
/// @param txHash The hash of the transaction
function approveTransaction(
address owner,
bytes32 txHash
)
external
virtual;
/// @dev Allows an agent to approve multiple rollup txs.
///
/// This function can only be called by an agent.
///
/// @param owners The account owners
/// @param txHashes The hashes of the transactions
function approveTransactions(
address[] calldata owners,
bytes32[] calldata txHashes
)
external
virtual;
/// @dev Checks if a rollup tx is approved using the tx's hash.
///
/// @param owner The owner of the account that needs to authorize the tx
/// @param txHash The hash of the transaction
/// @return True if the tx is approved, else false
function isTransactionApproved(
address owner,
bytes32 txHash
)
external
virtual
view
returns (bool);
// -- Admins --
/// @dev Sets the max time deposits have to wait before becoming withdrawable.
/// @param newValue The new value.
/// @return The old value.
function setMaxAgeDepositUntilWithdrawable(
uint32 newValue
)
external
virtual
returns (uint32);
/// @dev Returns the max time deposits have to wait before becoming withdrawable.
/// @return The value.
function getMaxAgeDepositUntilWithdrawable()
external
virtual
view
returns (uint32);
/// @dev Shuts down the exchange.
/// Once the exchange is shutdown all onchain requests are permanently disabled.
/// When all requirements are fulfilled the exchange owner can withdraw
/// the exchange stake with withdrawStake.
///
/// Note that the exchange can still enter the withdrawal mode after this function
/// has been invoked successfully. To prevent entering the withdrawal mode before the
/// the echange stake can be withdrawn, all withdrawal requests still need to be handled
/// for at least MIN_TIME_IN_SHUTDOWN seconds.
///
/// Can only be called by the exchange owner.
///
/// @return success True if the exchange is shutdown, else False
function shutdown()
external
virtual
returns (bool success);
/// @dev Gets the protocol fees for this exchange.
/// @return syncedAt The timestamp the protocol fees were last updated
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
/// @return previousTakerFeeBips The previous protocol taker fee
/// @return previousMakerFeeBips The previous protocol maker fee
function getProtocolFeeValues()
external
virtual
view
returns (
uint32 syncedAt,
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
/// @dev Gets the domain separator used in this exchange.
function getDomainSeparator()
external
virtual
view
returns (bytes32);
}
// Copyright 2017 Loopring Technology Limited.
/// @title Drainable
/// @author Brecht Devos - <[email protected]>
/// @dev Standard functionality to allow draining funds from a contract.
abstract contract Drainable
{
using AddressUtil for address;
using ERC20SafeTransfer for address;
event Drained(
address to,
address token,
uint amount
);
function drain(
address to,
address token
)
external
returns (uint amount)
{
require(canDrain(msg.sender, token), "UNAUTHORIZED");
if (token == address(0)) {
amount = address(this).balance;
to.sendETHAndVerify(amount, gasleft()); // ETH
} else {
amount = ERC20(token).balanceOf(address(this));
token.safeTransferAndVerify(to, amount); // ERC20 token
}
emit Drained(to, token, amount);
}
// Needs to return if the address is authorized to call drain.
function canDrain(address drainer, address token)
public
virtual
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title SelectorBasedAccessManager
/// @author Daniel Wang - <[email protected]>
contract SelectorBasedAccessManager is Claimable
{
using BytesUtil for bytes;
event PermissionUpdate(
address indexed user,
bytes4 indexed selector,
bool allowed
);
address public target;
mapping(address => mapping(bytes4 => bool)) public permissions;
modifier withAccess(bytes4 selector)
{
require(hasAccessTo(msg.sender, selector), "PERMISSION_DENIED");
_;
}
constructor(address _target)
{
require(_target != address(0), "ZERO_ADDRESS");
target = _target;
}
function grantAccess(
address user,
bytes4 selector,
bool granted
)
external
onlyOwner
{
require(permissions[user][selector] != granted, "INVALID_VALUE");
permissions[user][selector] = granted;
emit PermissionUpdate(user, selector, granted);
}
receive() payable external {}
fallback()
payable
external
{
transact(msg.data);
}
function transact(bytes memory data)
payable
public
withAccess(data.toBytes4(0))
{
(bool success, bytes memory returnData) = target
.call{value: msg.value}(data);
if (!success) {
assembly { revert(add(returnData, 32), mload(returnData)) }
}
}
function hasAccessTo(address user, bytes4 selector)
public
view
returns (bool)
{
return user == owner || permissions[user][selector];
}
}
contract LoopringIOExchangeOwner is SelectorBasedAccessManager, ERC1271, Drainable
{
using AddressUtil for address;
using AddressUtil for address payable;
using BytesUtil for bytes;
using MathUint for uint;
using SignatureUtil for bytes32;
using TransactionReader for ExchangeData.Block;
bytes4 private constant SUBMITBLOCKS_SELECTOR = IExchangeV3.submitBlocks.selector;
bool public open;
event SubmitBlocksAccessOpened(bool open);
struct TxCallback
{
uint16 txIdx;
uint16 numTxs;
uint16 receiverIdx;
bytes data;
}
struct BlockCallback
{
uint16 blockIdx;
TxCallback[] txCallbacks;
}
struct CallbackConfig
{
BlockCallback[] blockCallbacks;
address[] receivers;
}
constructor(address _exchange)
SelectorBasedAccessManager(_exchange)
{
}
function openAccessToSubmitBlocks(bool _open)
external
onlyOwner
{
open = _open;
emit SubmitBlocksAccessOpened(_open);
}
function isValidSignature(
bytes32 signHash,
bytes memory signature
)
public
view
override
returns (bytes4)
{
// Role system used a bit differently here.
return hasAccessTo(
signHash.recoverECDSASigner(signature),
this.isValidSignature.selector
) ? ERC1271_MAGICVALUE : bytes4(0);
}
function canDrain(address drainer, address /* token */)
public
override
view
returns (bool)
{
return hasAccessTo(drainer, this.drain.selector);
}
function submitBlocksWithCallbacks(
bool isDataCompressed,
bytes calldata data,
CallbackConfig calldata config
)
external
{
bool performCallback;
if (config.blockCallbacks.length > 0) {
require(config.receivers.length > 0, "MISSING_RECEIVERS");
performCallback = true;
}
require(
hasAccessTo(msg.sender, SUBMITBLOCKS_SELECTOR) || open,
"PERMISSION_DENIED"
);
bytes memory decompressed = isDataCompressed ?
ZeroDecompressor.decompress(data, 1):
data;
require(
decompressed.toBytes4(0) == SUBMITBLOCKS_SELECTOR,
"INVALID_DATA"
);
// Process the callback logic.
if (performCallback) {
_beforeBlockSubmission(_decodeBlocks(decompressed), config);
}
target.fastCallAndVerify(gasleft(), 0, decompressed);
}
function _beforeBlockSubmission(
ExchangeData.Block[] memory blocks,
CallbackConfig calldata config
)
private
{
int lastBlockIdx = -1;
for (uint i = 0; i < config.blockCallbacks.length; i++) {
BlockCallback calldata blockCallback = config.blockCallbacks[i];
uint16 blockIdx = blockCallback.blockIdx;
require(blockIdx > lastBlockIdx, "BLOCK_INDEX_OUT_OF_ORDER");
lastBlockIdx = int(blockIdx);
require(blockIdx < blocks.length, "INVALID_BLOCKIDX");
ExchangeData.Block memory _block = blocks[blockIdx];
_processTxCallbacks(_block, blockCallback.txCallbacks, config.receivers);
}
}
function _processTxCallbacks(
ExchangeData.Block memory _block,
TxCallback[] calldata txCallbacks,
address[] calldata receivers
)
private
{
uint cursor = 0;
for (uint i = 0; i < txCallbacks.length; i++) {
TxCallback calldata txCallback = txCallbacks[i];
uint txIdx = uint(txCallback.txIdx);
require(txIdx >= cursor, "TX_INDEX_OUT_OF_ORDER");
uint16 receiverIdx = txCallback.receiverIdx;
require(receiverIdx < receivers.length, "INVALID_RECEIVER_INDEX");
ExchangeData.Block memory minimalBlock = _block.createMinimalBlock(txIdx, txCallback.numTxs);
IBlockReceiver(receivers[receiverIdx]).beforeBlockSubmission(
minimalBlock,
txCallback.data,
0,
txCallback.numTxs
);
cursor = txIdx + txCallback.numTxs;
}
}
function _decodeBlocks(bytes memory data)
private
pure
returns (ExchangeData.Block[] memory)
{
// This copies the data (expensive) instead of just pointing to the correct address
//bytes memory blockData;
//assembly {
// blockData := add(data, 4)
//}
//ExchangeData.Block[] memory blocks = abi.decode(blockData, (ExchangeData.Block[]));
// Points the block data to the data in the abi encoded data.
// Only sets the data necessary in the callbacks!
// 36 := 4 (function selector) + 32 (offset to blocks)
uint numBlocks = data.toUint(36);
ExchangeData.Block[] memory blocks = new ExchangeData.Block[](numBlocks);
for (uint i = 0; i < numBlocks; i++) {
ExchangeData.Block memory _block = blocks[i];
// 68 := 36 (see above) + 32 (blocks length)
uint blockOffset = 68 + data.toUint(68 + i*32);
uint offset = blockOffset;
//_block.blockType = uint8(data.toUint(offset));
offset += 32;
_block.blockSize = uint16(data.toUint(offset));
offset += 32;
//_block.blockVersion = uint8(data.toUint(offset));
offset += 32;
uint blockDataOffset = data.toUint(offset);
offset += 32;
bytes memory blockData;
assembly {
blockData := add(data, add(32, add(blockOffset, blockDataOffset)))
}
_block.data = blockData;
}
return blocks;
}
} | Role system used a bit differently here. | function isValidSignature(
bytes32 signHash,
bytes memory signature
)
public
view
override
returns (bytes4)
{
return hasAccessTo(
signHash.recoverECDSASigner(signature),
this.isValidSignature.selector
) ? ERC1271_MAGICVALUE : bytes4(0);
}
| 2,137,941 |
./full_match/56/0xf36f3204c9B2583dF57B0A044d643983E824f7d3/sources/project_/contracts/rules/interactionRules/InvestorHasNTT.sol | the Owner of the smart contract can set the list of NTTtokens to check | function setNTTsToCheck(address[] calldata _nttsToUse) external onlyOwner {
nttTokenContracts = _nttsToUse;
}
| 3,233,798 |
pragma solidity^0.4.19;
import "menlo-token/contracts/MenloToken.sol";
// assumption: token upgrades through DappHub, such as https://etherscan.io/address/0x642ae78fafbb8032da552d619ad43f1d81e4dd7c#code
// assumption: token upgrades are 1:1
interface Redeemer {
function redeem() external;
function undo() external;
function to() external view returns (MenloToken);
function from() external view returns (MenloToken);
}
| assumption: token upgrades through DappHub, such as https:etherscan.io/address/0x642ae78fafbb8032da552d619ad43f1d81e4dd7ccode assumption: token upgrades are 1:1 | interface Redeemer {
function redeem() external;
function undo() external;
function to() external view returns (MenloToken);
function from() external view returns (MenloToken);
}
| 14,033,313 |
./full_match/1/0x10d88Ae63188987799772813778e3B697a5AE64A/sources/contracts/MCFToken.sol | 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.sub( subtractedValue));
return true;
}
| 8,492,110 |
pragma solidity ^0.5.11;
pragma experimental ABIEncoderV2;
import './ForceMoveApp.sol';
contract ForceMove {
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
struct FixedPart {
uint256 chainId;
address[] participants;
uint256 channelNonce;
address appDefinition;
uint256 challengeDuration;
}
struct State {
// participants sign the hash of this
uint256 turnNum;
bool isFinal;
bytes32 channelId; // keccack(chainId,participants,channelNonce)
bytes32 appPartHash;
// keccak256(abi.encode(
// fixedPart.challengeDuration,
// fixedPart.appDefinition,
// variablePart.appData
// )
// )
bytes32 outcomeHash;
}
struct ChannelStorage {
uint256 turnNumRecord;
uint256 finalizesAt;
bytes32 stateHash; // keccak256(abi.encode(State))
address challengerAddress;
bytes32 outcomeHash;
}
enum ChannelMode {Open, Challenge, Finalized}
mapping(bytes32 => bytes32) public channelStorageHashes;
// Public methods:
function getData(bytes32 channelId)
public
view
returns (uint48 finalizesAt, uint48 turnNumRecord, uint160 fingerprint)
{
(turnNumRecord, finalizesAt, fingerprint) = _getData(channelId);
}
function forceMove(
FixedPart memory fixedPart,
uint48 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount, // how many of the states are final
Signature[] memory sigs,
uint8[] memory whoSignedWhat,
Signature memory challengerSig
) public {
bytes32 channelId = _getChannelId(fixedPart);
// ------------
// REQUIREMENTS
// ------------
_requireNonDecreasedTurnNumber(channelId, largestTurnNum);
_requireChannelNotFinalized(channelId);
bytes32 supportedStateHash = _requireStateSupportedBy(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart,
sigs,
whoSignedWhat
);
address challenger = _requireThatChallengerIsParticipant(
supportedStateHash,
fixedPart.participants,
challengerSig
);
// ------------
// EFFECTS
// ------------
emit ChallengeRegistered(
channelId,
largestTurnNum,
now + fixedPart.challengeDuration,
challenger,
isFinalCount > 0,
fixedPart,
variableParts
);
channelStorageHashes[channelId] = _hashChannelStorage(
ChannelStorage(
largestTurnNum,
now + fixedPart.challengeDuration,
supportedStateHash,
challenger,
keccak256(abi.encode(variableParts[variableParts.length - 1].outcome))
)
);
}
function respond(
address challenger,
bool[2] memory isFinalAB,
FixedPart memory fixedPart,
ForceMoveApp.VariablePart[2] memory variablePartAB,
// variablePartAB[0] = challengeVariablePart
// variablePartAB[1] = responseVariablePart
Signature memory sig
) public {
bytes32 channelId = _getChannelId(fixedPart);
(uint48 turnNumRecord, uint48 finalizesAt, ) = _getData(channelId);
bytes32 challengeOutcomeHash = _hashOutcome(variablePartAB[0].outcome);
bytes32 responseOutcomeHash = _hashOutcome(variablePartAB[1].outcome);
bytes32 challengeStateHash = _hashState(
turnNumRecord,
isFinalAB[0],
channelId,
fixedPart,
variablePartAB[0].appData,
challengeOutcomeHash
);
bytes32 responseStateHash = _hashState(
turnNumRecord + 1,
isFinalAB[1],
channelId,
fixedPart,
variablePartAB[1].appData,
responseOutcomeHash
);
// requirements
_requireSpecificChallenge(
ChannelStorage(
turnNumRecord,
finalizesAt,
challengeStateHash,
challenger,
challengeOutcomeHash
),
channelId
);
require(
_recoverSigner(responseStateHash, sig) ==
fixedPart.participants[(turnNumRecord + 1) % fixedPart.participants.length],
'Response not signed by authorized mover'
);
_requireValidTransition(
fixedPart.participants.length,
isFinalAB,
variablePartAB,
turnNumRecord + 1,
fixedPart.appDefinition
);
// effects
_clearChallenge(channelId, turnNumRecord + 1);
}
function refute(
uint48 refutationStateTurnNum,
address challenger,
bool[2] memory isFinalAB,
FixedPart memory fixedPart,
ForceMoveApp.VariablePart[2] memory variablePartAB,
// variablePartAB[0] = challengeVariablePart
// variablePartAB[1] = refutationVariablePart
Signature memory refutationStateSig
) public {
// requirements
bytes32 channelId = _getChannelId(fixedPart);
(uint48 turnNumRecord, uint48 finalizesAt, ) = _getData(channelId);
_requireIncreasedTurnNumber(channelId, refutationStateTurnNum);
bytes32 challengeOutcomeHash = keccak256(abi.encode(variablePartAB[0].outcome));
bytes32 refutationOutcomeHash = keccak256(abi.encode(variablePartAB[1].outcome));
bytes32 challengeStateHash = _hashState(
turnNumRecord,
isFinalAB[0],
channelId,
fixedPart,
variablePartAB[0].appData,
challengeOutcomeHash
);
bytes32 refutationStateHash = _hashState(
refutationStateTurnNum,
isFinalAB[1],
channelId,
fixedPart,
variablePartAB[1].appData,
refutationOutcomeHash
);
_requireSpecificChallenge(
ChannelStorage(
turnNumRecord,
finalizesAt,
challengeStateHash,
challenger, // this is a check that the asserted challenger is in fact the challenger
challengeOutcomeHash
),
channelId
);
require(
_recoverSigner(refutationStateHash, refutationStateSig) == challenger,
'Refutation state not signed by challenger'
);
// effects
_clearChallenge(channelId, turnNumRecord);
}
function checkpoint(
FixedPart memory fixedPart,
uint48 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount, // how many of the states are final
Signature[] memory sigs,
uint8[] memory whoSignedWhat
) public {
bytes32 channelId = _getChannelId(fixedPart);
// ------------
// REQUIREMENTS
// ------------
_requireChannelNotFinalized(channelId);
_requireIncreasedTurnNumber(channelId, largestTurnNum);
_requireStateSupportedBy(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart,
sigs,
whoSignedWhat
);
// effects
_clearChallenge(channelId, largestTurnNum);
}
function conclude(
uint48 largestTurnNum,
FixedPart memory fixedPart,
bytes32 appPartHash,
bytes32 outcomeHash,
uint8 numStates,
uint8[] memory whoSignedWhat,
Signature[] memory sigs
) public {
bytes32 channelId = _getChannelId(fixedPart);
_requireChannelNotFinalized(channelId);
// By construction, the following states form a valid transition
bytes32[] memory stateHashes = new bytes32[](numStates);
for (uint256 i = 0; i < numStates; i++) {
stateHashes[i] = keccak256(
abi.encode(
State(
largestTurnNum + (i + 1) - numStates, // turnNum
true, // isFinal
channelId,
appPartHash,
outcomeHash
)
)
);
}
// check the supplied states are supported by n signatures
require(
_validSignatures(
largestTurnNum,
fixedPart.participants,
stateHashes,
sigs,
whoSignedWhat
),
'Invalid signatures'
);
// effects
// set channel storage
channelStorageHashes[channelId] = _hashChannelStorage(
ChannelStorage(0, now, bytes32(0), address(0), outcomeHash)
);
// emit event
emit Concluded(channelId);
}
// Internal methods:
function _requireThatChallengerIsParticipant(
bytes32 supportedStateHash,
address[] memory participants,
Signature memory challengerSignature
) internal pure returns (address challenger) {
challenger = _recoverSigner(
keccak256(abi.encode(supportedStateHash, 'forceMove')),
challengerSignature
);
require(_isAddressInArray(challenger, participants), 'Challenger is not a participant');
}
function _isAddressInArray(address suspect, address[] memory addresses)
internal
pure
returns (bool)
{
for (uint256 i = 0; i < addresses.length; i++) {
if (suspect == addresses[i]) {
return true;
}
}
return false;
}
function _validSignatures(
uint256 largestTurnNum,
address[] memory participants,
bytes32[] memory stateHashes,
Signature[] memory sigs,
uint8[] memory whoSignedWhat // whoSignedWhat[i] is the index of the state in stateHashes that was signed by participants[i]
) internal pure returns (bool) {
uint256 nParticipants = participants.length;
uint256 nStates = stateHashes.length;
require(
_acceptableWhoSignedWhat(whoSignedWhat, largestTurnNum, nParticipants, nStates),
'Unacceptable whoSignedWhat array'
);
for (uint256 i = 0; i < nParticipants; i++) {
address signer = _recoverSigner(stateHashes[whoSignedWhat[i]], sigs[i]);
if (signer != participants[i]) {
return false;
}
}
return true;
}
function _acceptableWhoSignedWhat(
uint8[] memory whoSignedWhat,
uint256 largestTurnNum,
uint256 nParticipants,
uint256 nStates
) internal pure returns (bool) {
require(
whoSignedWhat.length == nParticipants,
'_validSignatures: whoSignedWhat must be the same length as participants'
);
for (uint256 i = 0; i < nParticipants; i++) {
uint256 offset = (nParticipants + largestTurnNum - i) % nParticipants;
// offset is the difference between the index of participant[i] and the index of the participant who owns the largesTurnNum state
// the additional nParticipants in the dividend ensures offset always positive
if (whoSignedWhat[i] + offset < nStates - 1) {
return false;
}
}
return true;
}
bytes constant prefix = '\x19Ethereum Signed Message:\n32';
function _recoverSigner(bytes32 _d, Signature memory sig) internal pure returns (address) {
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _d));
address a = ecrecover(prefixedHash, sig.v, sig.r, sig.s);
return (a);
}
function _requireStateSupportedBy(
// returns hash of latest state, if supported
// else, reverts
uint256 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount,
bytes32 channelId,
FixedPart memory fixedPart,
Signature[] memory sigs,
uint8[] memory whoSignedWhat // whoSignedWhat[i] is the index of the state in stateHashes that was signed by participants[i]
) internal pure returns (bytes32) {
bytes32[] memory stateHashes = _requireValidTransitionChain(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart
);
require(
_validSignatures(
largestTurnNum,
fixedPart.participants,
stateHashes,
sigs,
whoSignedWhat
),
'Invalid signatures'
);
return stateHashes[stateHashes.length - 1];
}
function _requireValidTransitionChain(
// returns stateHashes array if valid
// else, reverts
uint256 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount,
bytes32 channelId,
FixedPart memory fixedPart
) internal pure returns (bytes32[] memory) {
bytes32[] memory stateHashes = new bytes32[](variableParts.length);
uint256 firstFinalTurnNum = largestTurnNum - isFinalCount + 1;
uint256 turnNum;
for (uint256 i = 0; i < variableParts.length; i++) {
turnNum = largestTurnNum - variableParts.length + 1 + i;
stateHashes[i] = _hashState(
turnNum,
turnNum >= firstFinalTurnNum,
channelId,
fixedPart,
variableParts[i].appData,
_hashOutcome(variableParts[i].outcome)
);
if (turnNum < largestTurnNum) {
_requireValidTransition(
fixedPart.participants.length,
[turnNum >= firstFinalTurnNum, turnNum + 1 >= firstFinalTurnNum],
[variableParts[i], variableParts[i + 1]],
turnNum + 1,
fixedPart.appDefinition
);
}
}
return stateHashes;
}
function _requireValidTransition(
uint256 nParticipants,
bool[2] memory isFinalAB, // [a.isFinal, b.isFinal]
ForceMoveApp.VariablePart[2] memory ab, // [a,b]
uint256 turnNumB,
address appDefinition
) internal pure returns (bool) {
// a prior check on the signatures for the submitted states implies that the following fields are equal for a and b:
// chainId, participants, channelNonce, appDefinition, challengeDuration
// and that the b.turnNum = a.turnNum + 1
if (isFinalAB[1]) {
require(
_bytesEqual(ab[1].outcome, ab[0].outcome),
'InvalidTransitionError: Cannot move to a final state with a different default outcome'
);
} else {
require(
!isFinalAB[0],
'InvalidTransitionError: Cannot move from a final state to a non final state'
);
if (turnNumB <= 2 * nParticipants) {
require(
_bytesEqual(ab[1].outcome, ab[0].outcome),
'InvalidTransitionError: Cannot change the default outcome during setup phase'
);
require(
keccak256(ab[1].appData) == keccak256(ab[0].appData),
'InvalidTransitionError: Cannot change the appData during setup phase'
);
} else {
require(
ForceMoveApp(appDefinition).validTransition(
ab[0],
ab[1],
turnNumB,
nParticipants
)
);
// reason string not necessary (called function will provide reason for reverting)
}
}
return true;
}
function _bytesEqual(bytes memory left, bytes memory right) internal pure returns (bool) {
return keccak256(left) == keccak256(right);
}
function _clearChallenge(bytes32 channelId, uint256 newTurnNumRecord) internal {
channelStorageHashes[channelId] = _hashChannelStorage(
ChannelStorage(newTurnNumRecord, 0, bytes32(0), address(0), bytes32(0))
);
emit ChallengeCleared(channelId, newTurnNumRecord);
}
function _requireIncreasedTurnNumber(bytes32 channelId, uint48 newTurnNumRecord) internal view {
(uint48 turnNumRecord, , ) = _getData(channelId);
require(newTurnNumRecord > turnNumRecord, 'turnNumRecord not increased.');
}
function _requireNonDecreasedTurnNumber(bytes32 channelId, uint48 newTurnNumRecord)
internal
view
{
(uint48 turnNumRecord, , ) = _getData(channelId);
require(newTurnNumRecord >= turnNumRecord, 'turnNumRecord decreased.');
}
function _requireSpecificChallenge(ChannelStorage memory cs, bytes32 channelId) internal view {
_requireMatchingStorage(cs, channelId);
_requireOngoingChallenge(channelId);
}
function _requireOngoingChallenge(bytes32 channelId) internal view {
require(_mode(channelId) == ChannelMode.Challenge, 'No ongoing challenge.');
}
function _requireChannelNotFinalized(bytes32 channelId) internal view {
require(_mode(channelId) != ChannelMode.Finalized, 'Channel finalized.');
}
function _requireChannelFinalized(bytes32 channelId) internal view {
require(_mode(channelId) == ChannelMode.Finalized, 'Channel not finalized.');
}
function _requireChannelOpen(bytes32 channelId) internal view {
require(_mode(channelId) == ChannelMode.Open, 'Channel not open.');
}
function _requireMatchingStorage(ChannelStorage memory cs, bytes32 channelId) internal view {
require(
_matchesHash(cs, channelStorageHashes[channelId]),
'Channel storage does not match stored version.'
);
}
function _mode(bytes32 channelId) internal view returns (ChannelMode) {
// Note that _getData(someRandomChannelId) returns (0,0,0), which is
// correct when nobody has written to storage yet.
(, uint48 finalizesAt, ) = _getData(channelId);
if (finalizesAt == 0) {
return ChannelMode.Open;
} else if (finalizesAt <= now) {
return ChannelMode.Finalized;
} else {
return ChannelMode.Challenge;
}
}
function _hashChannelStorage(ChannelStorage memory channelStorage)
internal
pure
returns (bytes32 newHash)
{
// The hash is constructed from left to right.
uint256 result;
uint16 cursor = 256;
// Shift turnNumRecord 208 bits left to fill the first 48 bits
result = uint256(channelStorage.turnNumRecord) << (cursor -= 48);
// logical or with finalizesAt padded with 160 zeros to get the next 48 bits
result |= (channelStorage.finalizesAt << (cursor -= 48));
// logical or with the last 160 bits of the hash of the encoded storage
result |= uint256(uint160(uint256(keccak256(abi.encode(channelStorage)))));
newHash = bytes32(result);
}
function _getData(bytes32 channelId)
internal
view
returns (uint48 turnNumRecord, uint48 finalizesAt, uint160 fingerprint)
{
bytes32 storageHash = channelStorageHashes[channelId];
uint16 cursor = 256;
turnNumRecord = uint48(uint256(storageHash) >> (cursor -= 48));
finalizesAt = uint48(uint256(storageHash) >> (cursor -= 48));
fingerprint = uint160(uint256(storageHash));
}
function _matchesHash(ChannelStorage memory cs, bytes32 h) internal pure returns (bool) {
return _hashChannelStorage(cs) == h;
}
function _hashState(
uint256 turnNumRecord,
bool isFinal,
bytes32 channelId,
FixedPart memory fixedPart,
bytes memory appData,
bytes32 outcomeHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
State(
turnNumRecord,
isFinal,
channelId,
keccak256(
abi.encode(
fixedPart.challengeDuration,
fixedPart.appDefinition,
appData
)
),
outcomeHash
)
)
);
}
function _hashOutcome(bytes memory outcome) internal pure returns (bytes32) {
return keccak256(abi.encode(outcome));
}
function _getChannelId(FixedPart memory fixedPart) internal pure returns (bytes32 channelId) {
channelId = keccak256(
abi.encode(fixedPart.chainId, fixedPart.participants, fixedPart.channelNonce)
);
}
// events
event ChallengeRegistered(
bytes32 indexed channelId,
// everything needed to respond or refute
uint256 turnNunmRecord,
uint256 finalizesAt,
address challenger,
bool isFinal,
FixedPart fixedPart,
ForceMoveApp.VariablePart[] variableParts
);
event ChallengeCleared(bytes32 indexed channelId, uint256 newTurnNumRecord);
event Concluded(bytes32 indexed channelId);
}
| The hash is constructed from left to right. Shift turnNumRecord 208 bits left to fill the first 48 bits logical or with finalizesAt padded with 160 zeros to get the next 48 bits logical or with the last 160 bits of the hash of the encoded storage | function _hashChannelStorage(ChannelStorage memory channelStorage)
internal
pure
returns (bytes32 newHash)
{
uint256 result;
uint16 cursor = 256;
result = uint256(channelStorage.turnNumRecord) << (cursor -= 48);
result |= (channelStorage.finalizesAt << (cursor -= 48));
result |= uint256(uint160(uint256(keccak256(abi.encode(channelStorage)))));
newHash = bytes32(result);
}
| 6,404,704 |
pragma solidity ^0.4.16;
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;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
// Public variables of the token
string public name = "Yumerium Token";
string public symbol = "YUM";
uint8 public decimals = 8;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply = 808274854 * 10 ** uint256(decimals);
// 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);
event Sell(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
// uint256 initialSupply,
// string tokenName,
// string 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 != 0x0);
// 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;
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);
}
/**
* 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
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
Burn(_from, _value);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract YumeriumToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function YumeriumToken() public {
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @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;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @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;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) payable public {
_transfer(msg.sender, owner, amount);
Sell(msg.sender, amount);
}
} | This generates a public event on the blockchain that will notify clients / Initializes contract with initial supply tokens to the creator of the contract / | function YumeriumToken() public {
}
| 14,561,064 |
./partial_match/3/0xD9ef7Fbc3655fE0A18A27e54B7eAcB67D70ED290/sources/culaRewards.sol | Excecutes a substraction operation to check if it is possible to exectute transfer | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| 5,337,936 |
/**
*Submitted for verification at Etherscan.io on 2021-01-13
*/
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "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.
// 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: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @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 returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File: contracts/interface/IGovernanceRewards.sol
pragma solidity 0.6.2;
// https://etherscan.io/address/0x0f85a912448279111694f4ba4f85dc641c54b594#writeContract
interface IGovernanceRewards {
function getReward() external;
function earned(address account) external view returns (uint256);
}
// File: contracts/interface/IExchangeGovernance.sol
pragma solidity 0.6.2;
interface IExchangeGovernance {
function leftoverShareVote(uint256 govShare, uint256 refShare) external;
}
// File: contracts/interface/IGovernanceMothership.sol
pragma solidity 0.6.2;
interface IGovernanceMothership {
function stake(uint256 amount) external;
function unstake(uint256 amount) external;
function notify() external;
}
// File: contracts/interface/IMooniswapPoolGovernance.sol
pragma solidity 0.6.2;
interface IMooniswapPoolGovernance {
function feeVote(uint256 vote) external;
function slippageFeeVote(uint256 vote) external;
function decayPeriodVote(uint256 vote) external;
}
// File: contracts/interface/IMooniswapFactoryGovernance.sol
pragma solidity 0.6.2;
// https://etherscan.io/address/0xc4a8b7e29e3c8ec560cd4945c1cf3461a85a148d#code
interface IMooniswapFactoryGovernance {
function defaultDecayPeriodVote(uint256 vote) external;
function defaultFeeVote(uint256 vote) external;
function defaultSlippageFeeVote(uint256 vote) external;
function governanceShareVote(uint256 vote) external;
function referralShareVote(uint256 vote) external;
}
// File: contracts/interface/IOneInchLiquidityProtocol.sol
pragma solidity ^0.6.0;
interface IOneInchLiquidityProtocol {
function swap(address src, address dst, uint256 amount, uint256 minReturn, address referral) external payable returns(uint256 result);
function swapFor(address src, address dst, uint256 amount, uint256 minReturn, address referral, address payable receiver) external payable returns(uint256 result);
}
// File: contracts/xINCH.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.6.2;
contract xINCH is
Initializable,
ERC20UpgradeSafe,
OwnableUpgradeSafe,
PausableUpgradeSafe
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant LIQUIDATION_TIME_PERIOD = 4 weeks;
uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10;
uint256 private constant BUFFER_TARGET = 20; // 5% target
uint256 private constant MAX_UINT = 2**256 - 1;
uint256 public adminActiveTimestamp;
uint256 public withdrawableOneInchFees;
IERC20 private oneInch;
IOneInchLiquidityProtocol private oneInchLiquidityProtocol;
IMooniswapFactoryGovernance private factoryGovernance;
IGovernanceMothership private governanceMothership;
IExchangeGovernance private exchangeGovernance;
IGovernanceRewards private governanceRewards;
address private oneInchExchange;
address private manager;
address private manager2;
address private constant ETH_ADDRESS = address(0);
struct FeeDivisors {
uint256 mintFee;
uint256 burnFee;
uint256 claimFee;
}
FeeDivisors public feeDivisors;
event Rebalance();
event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee);
event FeeWithdraw(uint256 ethFee, uint256 inchFee);
function initialize(
string calldata _symbol,
IERC20 _oneInch,
IGovernanceMothership _governanceMothership,
IOneInchLiquidityProtocol _oneInchLiquidityProtocol,
uint256 _mintFeeDivisor,
uint256 _burnFeeDivisor,
uint256 _claimFeeDivisor
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC20_init_unchained("xINCH", _symbol);
oneInch = _oneInch;
governanceMothership = _governanceMothership;
oneInchLiquidityProtocol = _oneInchLiquidityProtocol;
_setFeeDivisors(_mintFeeDivisor, _burnFeeDivisor, _claimFeeDivisor);
}
/*
* @dev Mint xINCH using ETH
* @param minReturn: Min return to pass to 1Inch trade
*/
function mint(uint256 minReturn) external payable whenNotPaused {
require(msg.value > 0, "Must send ETH");
uint256 fee = _calculateFee(msg.value, feeDivisors.mintFee);
uint256 ethValue = msg.value.sub(fee);
uint256 incrementalOneInch =
oneInchLiquidityProtocol.swap.value(ethValue)(
ETH_ADDRESS,
address(oneInch),
ethValue,
minReturn,
address(0)
);
_mintInternal(incrementalOneInch);
}
/*
* @dev Mint xINCH using INCH
* @param oneInchAmount: INCH tokens to contribute
*/
function mintWithToken(uint256 oneInchAmount) external whenNotPaused {
require(oneInchAmount > 0, "Must send token");
oneInch.safeTransferFrom(msg.sender, address(this), oneInchAmount);
uint256 fee = _calculateFee(oneInchAmount, feeDivisors.mintFee);
_incrementWithdrawableOneInchFees(fee);
return _mintInternal(oneInchAmount.sub(fee));
}
function _mintInternal(uint256 _incrementalOneInch) private {
uint256 mintAmount =
calculateMintAmount(_incrementalOneInch, totalSupply());
return super._mint(msg.sender, mintAmount);
}
/*
* @dev Burn xINCH tokens
* @notice Will fail if pro rata balance exceeds available liquidity
* @param tokenAmount: xINCH tokens to burn
* @param redeemForEth: Redeem for ETH or INCH
* @param minReturn: Min return to pass to 1Inch trade
*/
function burn(
uint256 tokenAmount,
bool redeemForEth,
uint256 minReturn
) external {
require(tokenAmount > 0, "Must send xINCH");
uint256 stakedBalance = getStakedBalance();
uint256 bufferBalance = getBufferBalance();
uint256 inchHoldings = stakedBalance.add(bufferBalance);
uint256 proRataInch = inchHoldings.mul(tokenAmount).div(totalSupply());
require(proRataInch <= bufferBalance, "Insufficient exit liquidity");
super._burn(msg.sender, tokenAmount);
if (redeemForEth) {
uint256 fee = _calculateFee(proRataInch, feeDivisors.burnFee);
_incrementWithdrawableOneInchFees(fee);
oneInchLiquidityProtocol.swapFor(
address(oneInch),
ETH_ADDRESS,
proRataInch.sub(fee),
minReturn,
address(0),
msg.sender
);
} else {
uint256 fee = _calculateFee(proRataInch, feeDivisors.burnFee);
_incrementWithdrawableOneInchFees(fee);
oneInch.safeTransfer(msg.sender, proRataInch.sub(fee));
}
}
function calculateMintAmount(
uint256 incrementalOneInch,
uint256 totalSupply
) public view returns (uint256 mintAmount) {
if (totalSupply == 0)
return incrementalOneInch.mul(INITIAL_SUPPLY_MULTIPLIER);
mintAmount = (incrementalOneInch).mul(totalSupply).div(getNav());
}
/* ========================================================================================= */
/* Management */
/* ========================================================================================= */
function getNav() public view returns (uint256) {
return getStakedBalance().add(getBufferBalance());
}
function getStakedBalance() public view returns (uint256) {
return IERC20(address(governanceMothership)).balanceOf(address(this));
}
function getBufferBalance() public view returns (uint256) {
return oneInch.balanceOf(address(this)).sub(withdrawableOneInchFees);
}
/*
* @dev Admin function for claiming INCH rewards
*/
function getReward() external onlyOwnerOrManager {
_certifyAdmin();
_getReward();
}
/*
* @dev Public callable function for claiming INCH rewards
*/
function getRewardExternal() external {
_getReward();
}
function _getReward() private {
uint256 bufferBalanceBefore = getBufferBalance();
governanceRewards.getReward();
uint256 bufferBalanceAfter = getBufferBalance();
uint256 fee =
_calculateFee(
bufferBalanceAfter.sub(bufferBalanceBefore),
feeDivisors.claimFee
);
_incrementWithdrawableOneInchFees(fee);
}
function _stake(uint256 _amount) private {
governanceMothership.stake(_amount);
}
/*
* @dev Admin function for unstaking beyond the scope of a rebalance
*/
function adminUnstake(uint256 _amount) external onlyOwnerOrManager {
_unstake(_amount);
}
/*
* @dev Public callable function for unstaking in event of admin failure/incapacitation
*/
function emergencyUnstake(uint256 _amount) external {
require(
adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp,
"Liquidation time not elapsed"
);
_unstake(_amount);
}
function unstake(uint256 _amount) external onlyOwnerOrManager {
_unstake(_amount);
}
function _unstake(uint256 _amount) private {
governanceMothership.unstake(_amount);
}
/*
* @dev Admin function for collecting reward and restoring target buffer balance
*/
function rebalance() external onlyOwnerOrManager {
_certifyAdmin();
_getReward();
_rebalance();
}
/*
* @dev Public callable function for collecting reward and restoring target buffer balance
*/
function rebalanceExternal() external {
require(
adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) > block.timestamp,
"Liquidation time elapsed; no more staking"
);
_getReward();
_rebalance();
}
function _rebalance() private {
uint256 stakedBalance = getStakedBalance();
uint256 bufferBalance = getBufferBalance();
uint256 targetBuffer =
(stakedBalance.add(bufferBalance)).div(BUFFER_TARGET);
if (bufferBalance > targetBuffer) {
_stake(bufferBalance.sub(targetBuffer));
} else {
_unstake(targetBuffer.sub(bufferBalance));
}
emit Rebalance();
}
function _calculateFee(uint256 _value, uint256 _feeDivisor)
internal
pure
returns (uint256 fee)
{
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
function _incrementWithdrawableOneInchFees(uint256 _feeAmount) private {
withdrawableOneInchFees = withdrawableOneInchFees.add(_feeAmount);
}
/* ========================================================================================= */
/* Governance */
/* ========================================================================================= */
function setFactoryGovernanceAddress(
IMooniswapFactoryGovernance _factoryGovernance
) external onlyOwnerOrManager {
factoryGovernance = _factoryGovernance;
}
function setGovernanceRewardsAddress(IGovernanceRewards _governanceRewards)
external
onlyOwnerOrManager
{
governanceRewards = _governanceRewards;
}
function setExchangeGovernanceAddress(
IExchangeGovernance _exchangeGovernance
) external onlyOwnerOrManager {
exchangeGovernance = _exchangeGovernance;
}
function defaultDecayPeriodVote(uint256 vote) external onlyOwnerOrManager {
factoryGovernance.defaultDecayPeriodVote(vote);
}
function defaultFeeVote(uint256 vote) external onlyOwnerOrManager {
factoryGovernance.defaultFeeVote(vote);
}
function defaultSlippageFeeVote(uint256 vote) external onlyOwnerOrManager {
factoryGovernance.defaultSlippageFeeVote(vote);
}
function governanceShareVote(uint256 vote) external onlyOwnerOrManager {
factoryGovernance.governanceShareVote(vote);
}
function referralShareVote(uint256 vote) external onlyOwnerOrManager {
factoryGovernance.referralShareVote(vote);
}
function leftoverShareVote(uint256 govShare, uint256 refShare)
external
onlyOwnerOrManager
{
exchangeGovernance.leftoverShareVote(govShare, refShare);
}
function poolFeeVote(address pool, uint256 vote)
external
onlyOwnerOrManager
{
IMooniswapPoolGovernance(pool).feeVote(vote);
}
function poolSlippageFeeVote(address pool, uint256 vote)
external
onlyOwnerOrManager
{
IMooniswapPoolGovernance(pool).slippageFeeVote(vote);
}
function poolDecayPeriodVote(address pool, uint256 vote)
external
onlyOwnerOrManager
{
IMooniswapPoolGovernance(pool).decayPeriodVote(vote);
}
/* ========================================================================================= */
/* Utils */
/* ========================================================================================= */
/*
* @notice Inverse of fee i.e., a fee divisor of 100 == 1%
* @notice Three fee types
* @dev Mint fee 0 or <= 2%
* @dev Burn fee 0 or <= 1%
* @dev Claim fee 0 <= 4%
*/
function setFeeDivisors(
uint256 mintFeeDivisor,
uint256 burnFeeDivisor,
uint256 claimFeeDivisor
) public onlyOwner {
_setFeeDivisors(mintFeeDivisor, burnFeeDivisor, claimFeeDivisor);
}
function _setFeeDivisors(
uint256 _mintFeeDivisor,
uint256 _burnFeeDivisor,
uint256 _claimFeeDivisor
) private {
require(_mintFeeDivisor == 0 || _mintFeeDivisor >= 50, "Invalid fee");
require(_burnFeeDivisor == 0 || _burnFeeDivisor >= 100, "Invalid fee");
require(_claimFeeDivisor >= 25, "Invalid fee");
feeDivisors.mintFee = _mintFeeDivisor;
feeDivisors.burnFee = _burnFeeDivisor;
feeDivisors.claimFee = _claimFeeDivisor;
emit FeeDivisorsSet(_mintFeeDivisor, _burnFeeDivisor, _claimFeeDivisor);
}
function pauseContract() public onlyOwnerOrManager returns (bool) {
_pause();
return true;
}
function unpauseContract() public onlyOwnerOrManager returns (bool) {
_unpause();
return true;
}
/*
* @notice Registers that admin is present and active
* @notice If admin isn't certified within liquidation time period,
* emergencyUnstake function becomes callable
*/
function _certifyAdmin() private {
adminActiveTimestamp = block.timestamp;
}
function setManager(address _manager) external onlyOwner {
manager = _manager;
}
function setManager2(address _manager2) external onlyOwner {
manager2 = _manager2;
}
function approveInch(address _toApprove) external onlyOwnerOrManager {
oneInch.safeApprove(_toApprove, MAX_UINT);
}
/*
* @notice Emergency function in case of errant transfer of
* xINCH token directly to contract
*/
function withdrawNativeToken() public onlyOwnerOrManager {
uint256 tokenBal = balanceOf(address(this));
if (tokenBal > 0) {
IERC20(address(this)).safeTransfer(msg.sender, tokenBal);
}
}
/*
* @notice Withdraw function for ETH and INCH fees
*/
function withdrawFees() public onlyOwner {
uint256 ethBal = address(this).balance;
(bool success, ) = msg.sender.call.value(ethBal)("");
require(success, "Transfer failed");
uint256 oneInchFees = withdrawableOneInchFees;
withdrawableOneInchFees = 0;
oneInch.safeTransfer(msg.sender, oneInchFees);
emit FeeWithdraw(ethBal, oneInchFees);
}
modifier onlyOwnerOrManager {
require(
msg.sender == owner() ||
msg.sender == manager ||
msg.sender == manager2,
"Non-admin caller"
);
_;
}
receive() external payable {
require(msg.sender != tx.origin, "Errant ETH deposit");
}
} | Public callable function for claiming INCH rewards/ | function getRewardExternal() external {
_getReward();
}
| 7,653,630 |
./full_match/43114/0xE487a3780D56F2ECD142201907dF16350bb09946/sources/DssProxyActions.sol | / Exits token amount to the user's wallet as a token | function freeGem(
address manager,
address gemJoin,
address end,
uint cdp,
address res
) public {
uint amt = _free(manager, end, cdp) / 10 ** (18 - GemJoin(gemJoin).dec());
if (res == address(0)) {
GemJoin(gemJoin).exit(msg.sender, amt);
GemJoin(gemJoin).exit(address(this), amt);
_withdrawVault(address(GemJoin(gemJoin).gem()), amt);
DSToken(res).transfer(msg.sender, DSToken(res).balanceOf(address(this)));
}
}
| 4,579,883 |
./full_match/1/0xF74480d927D3D34dE74C861841FCaFA2f7701617/sources/contracts/ERC1155D.sol | xref:ROOT:erc1155.adocbatch-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];
require(
_owners[id].addr == from && amounts[i] < 2,
"ERC1155: insufficient balance for transfer"
);
if (amounts[i] == 1) {
_owners[id].addr = to;
}
}
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
ids,
amounts,
data
);
}
| 16,400,104 |
//! The simple registry contract.
//!
//! Copyright 2016 Gavin Wood, Parity Technologies 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.
pragma solidity ^0.4.24;
import "./Owned.sol";
import "./Registry.sol";
contract SimpleRegistry is Owned, MetadataRegistry, OwnerRegistry, ReverseRegistry {
struct Entry {
address owner;
address reverse;
bool deleted;
mapping (string => bytes32) data;
}
event Drained(uint amount);
event FeeChanged(uint amount);
event ReverseProposed(string name, address indexed reverse);
mapping (bytes32 => Entry) entries;
mapping (address => string) reverses;
uint public fee = 1 ether;
modifier whenUnreserved(bytes32 _name) {
require(entries[_name].owner == 0);
_;
}
modifier onlyOwnerOf(bytes32 _name) {
require(entries[_name].owner == msg.sender);
_;
}
modifier whenProposed(string _name) {
require(entries[keccak256(bytes(_name))].reverse == msg.sender);
_;
}
modifier whenEntry(string _name) {
require(!entries[keccak256(bytes(_name))].deleted);
_;
}
modifier whenEntryRaw(bytes32 _name) {
require(!entries[_name].deleted);
_;
}
modifier whenFeePaid {
require(msg.value >= fee);
_;
}
// Reservation functions
function reserve(bytes32 _name)
external
payable
whenEntryRaw(_name)
whenUnreserved(_name)
whenFeePaid
returns (bool success)
{
entries[_name].owner = msg.sender;
emit Reserved(_name, msg.sender);
return true;
}
function transfer(bytes32 _name, address _to)
external
whenEntryRaw(_name)
onlyOwnerOf(_name)
returns (bool success)
{
entries[_name].owner = _to;
emit Transferred(_name, msg.sender, _to);
return true;
}
function drop(bytes32 _name)
external
whenEntryRaw(_name)
onlyOwnerOf(_name)
returns (bool success)
{
delete reverses[entries[_name].reverse];
entries[_name].deleted = true;
emit Dropped(_name, msg.sender);
return true;
}
// Data admin functions
function setData(bytes32 _name, string _key, bytes32 _value)
external
whenEntryRaw(_name)
onlyOwnerOf(_name)
returns (bool success)
{
entries[_name].data[_key] = _value;
emit DataChanged(_name, _key, _key);
return true;
}
function setAddress(bytes32 _name, string _key, address _value)
external
whenEntryRaw(_name)
onlyOwnerOf(_name)
returns (bool success)
{
entries[_name].data[_key] = bytes32(_value);
emit DataChanged(_name, _key, _key);
return true;
}
function setUint(bytes32 _name, string _key, uint _value)
external
whenEntryRaw(_name)
onlyOwnerOf(_name)
returns (bool success)
{
entries[_name].data[_key] = bytes32(_value);
emit DataChanged(_name, _key, _key);
return true;
}
// Reverse registration functions
function proposeReverse(string _name, address _who)
external
whenEntry(_name)
onlyOwnerOf(keccak256(bytes(_name)))
returns (bool success)
{
bytes32 sha3Name = keccak256(bytes(_name));
if (entries[sha3Name].reverse != 0 && keccak256(bytes(reverses[entries[sha3Name].reverse])) == sha3Name) {
delete reverses[entries[sha3Name].reverse];
emit ReverseRemoved(_name, entries[sha3Name].reverse);
}
entries[sha3Name].reverse = _who;
emit ReverseProposed(_name, _who);
return true;
}
function confirmReverse(string _name)
external
whenEntry(_name)
whenProposed(_name)
returns (bool success)
{
reverses[msg.sender] = _name;
emit ReverseConfirmed(_name, msg.sender);
return true;
}
function confirmReverseAs(string _name, address _who)
external
whenEntry(_name)
onlyOwner
returns (bool success)
{
reverses[_who] = _name;
emit ReverseConfirmed(_name, _who);
return true;
}
function removeReverse()
external
whenEntry(reverses[msg.sender])
{
emit ReverseRemoved(reverses[msg.sender], msg.sender);
delete entries[keccak256(bytes(reverses[msg.sender]))].reverse;
delete reverses[msg.sender];
}
// Admin functions for the owner
function setFee(uint _amount)
external
onlyOwner
returns (bool)
{
fee = _amount;
emit FeeChanged(_amount);
return true;
}
function drain()
external
onlyOwner
returns (bool)
{
emit Drained(address(this).balance);
msg.sender.transfer(address(this).balance);
return true;
}
// MetadataRegistry views
function getData(bytes32 _name, string _key)
external
view
whenEntryRaw(_name)
returns (bytes32)
{
return entries[_name].data[_key];
}
function getAddress(bytes32 _name, string _key)
external
view
whenEntryRaw(_name)
returns (address)
{
return address(entries[_name].data[_key]);
}
function getUint(bytes32 _name, string _key)
external
view
whenEntryRaw(_name)
returns (uint)
{
return uint(entries[_name].data[_key]);
}
// OwnerRegistry views
function getOwner(bytes32 _name)
external
view
whenEntryRaw(_name)
returns (address)
{
return entries[_name].owner;
}
// ReversibleRegistry views
function hasReverse(bytes32 _name)
external
view
whenEntryRaw(_name)
returns (bool)
{
return entries[_name].reverse != 0;
}
function getReverse(bytes32 _name)
external
view
whenEntryRaw(_name)
returns (address)
{
return entries[_name].reverse;
}
function canReverse(address _data)
external
view
returns (bool)
{
return bytes(reverses[_data]).length != 0;
}
function reverse(address _data)
external
view
returns (string)
{
return reverses[_data];
}
function reserved(bytes32 _name)
external
view
whenEntryRaw(_name)
returns (bool)
{
return entries[_name].owner != 0;
}
}
| ReversibleRegistry views | function hasReverse(bytes32 _name)
external
view
whenEntryRaw(_name)
returns (bool)
{
return entries[_name].reverse != 0;
}
| 928,852 |
./full_match/43113/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/libraries/math/TreeMath.sol | Returns the first bit in the given leaves that is strictly higher than the given bit. It will return type(uint256).max if there is no such bit. leaves The leaves bit The bit return The first bit in the given leaves that is strictly higher than the given bit/ | function _closestBitLeft(bytes32 leaves, uint8 bit) private pure returns (uint256) {
unchecked {
return uint256(leaves).closestBitLeft(bit + 1);
}
}
| 7,117,589 |
./full_match/1/0x39F05c39902A9b265Dcb4c59418657cDb9913C23/sources/contracts/nfts/ParallelAlphaInvokeProxy.sol | Called by the LayerZero endpoint when a message is sent _from The address that will have its tokens locked when bridging _tokenIds TokenIds to bridge _amounts Amount of tokens to bridge/ | function _debitFrom(
address _from,
uint16,
bytes memory,
uint256[] memory _tokenIds,
uint256[] memory _amounts
) internal virtual override {
if (_tokenIds.length > batchSizeLimit) {
revert ExceedsBatchSizeLimit();
}
if (
_from != _msgSender() &&
!parallelAlpha.isApprovedForAll(_from, _msgSender())
) {
revert InvalidCaller();
}
parallelAlpha.safeBatchTransferFrom(
_from,
address(this),
_tokenIds,
_amounts,
""
);
}
| 16,440,181 |
/*
website: yiff.farm
This project was forked from SUSHI, YUNO and KIMCHI projects.
Unless those projects have severe vulnerabilities, this contract will be fine
*/
pragma solidity ^0.6.12;
/*
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev 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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// YiffToken with Governance.
contract YiffToken is ERC20("YIFF", "YIFF"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Overlord).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract YiffLord is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of YIFFs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accYiffPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accYiffPerShare` (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.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. YIFFs to distribute per block.
uint256 lastRewardBlock; // Last block number that YIFFs distribution occurs.
uint256 accYiffPerShare; // Accumulated YIFFs per share, times 1e12. See below.
}
// The YIFF TOKEN!
YiffToken public yiff;
// Dev address.
address public devaddr;
// Block number when bonus YIFF period ends.
uint256 public bonusEndBlock;
// YIFF tokens created per block.
uint256 public yiffPerBlock;
// Bonus muliplier for early yiff makers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when YIFF mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
YiffToken _yiff,
address _devaddr,
uint256 _yiffPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
yiff = _yiff;
devaddr = _devaddr;
yiffPerBlock = _yiffPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accYiffPerShare: 0
}));
}
// Update the given pool's YIFF allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending YIFFs on frontend.
function pendingYiff(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accYiffPerShare = pool.accYiffPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 yiffReward = multiplier.mul(yiffPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accYiffPerShare = accYiffPerShare.add(yiffReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accYiffPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{
yiff.mint(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 yiffReward = multiplier.mul(yiffPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
yiff.mint(address(this), yiffReward);
pool.accYiffPerShare = pool.accYiffPerShare.add(yiffReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to Overlord for YIFF allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accYiffPerShare).div(1e12).sub(user.rewardDebt);
safeYiffTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accYiffPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from Overlord.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "OverLord::withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accYiffPerShare).div(1e12).sub(user.rewardDebt);
safeYiffTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accYiffPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe YIFF transfer function, just in case if rounding error causes pool to not have enough YIFFs.
function safeYiffTransfer(address _to, uint256 _amount) internal {
uint256 yiffBal = yiff.balanceOf(address(this));
if (_amount > yiffBal) {
yiff.transfer(_to, yiffBal);
} else {
yiff.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | View function to see pending YIFFs on frontend. | function pendingYiff(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accYiffPerShare = pool.accYiffPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 yiffReward = multiplier.mul(yiffPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accYiffPerShare = accYiffPerShare.add(yiffReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accYiffPerShare).div(1e12).sub(user.rewardDebt);
}
| 1,355,856 |
./partial_match/1/0x3735DA3c3f1d2156a0965109eB452212155EC1fE/sources/Taxable.sol | Function enables public interface for tax enabled/disabled boolean. | function taxed() public view virtual returns (bool) { | 2,695,395 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Interfaces for converter.
*/
interface IConverter {
function convert(address _from, address _to, uint256 _fromAmount, uint256 _toAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../interfaces/IConverter.sol";
/**
* @title Converter between certain assets pairs.
*/
contract Converter is IConverter, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
event AccessUpdated(address indexed _account, bool _approved);
address public constant RENCRV = address(0x49849C98ae39Fff122806C06791Fa73784FB3675);
address public constant BADGER_RENCRV = address(0x6dEf55d2e18486B9dDfaA075bc4e4EE0B28c1545);
address public constant SBTCCRV = address(0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3);
address public constant BADGER_SBTCCRV = address(0xd04c48A53c111300aD41190D63681ed3dAd998eC);
address public constant TBTCCRV = address(0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd);
address public constant BADGER_TBTCCRV = address(0xb9D076fDe463dbc9f915E5392F807315Bf940334);
address public constant BADGER_HRENCRV = address(0xAf5A1DECfa95BAF63E0084a35c62592B774A2A87);
// The address that is allowed to invoke the converter.
mapping(address => bool) public approved;
/**
* @dev Initializes the converter contract.
*/
function initialize() public initializer {
__Ownable_init();
}
/**
* @dev Core function to handle asset conversion.
*/
function convert(address _from, address _to, uint256 _fromAmount, uint256 _toAmount) external override {
require(approved[msg.sender], "not approved");
// Will update when more asset pairs are supported
if (_from == RENCRV) {
require(_to == BADGER_RENCRV || _to == BADGER_HRENCRV, "not supported");
} else if (_from == SBTCCRV) {
require(_to == BADGER_SBTCCRV, "not supported");
} else if (_from == TBTCCRV) {
require(_to == BADGER_TBTCCRV, "not supported");
} else {
revert("unsupported source token");
}
IERC20Upgradeable(_from).safeTransferFrom(msg.sender, address(this), _fromAmount);
IERC20Upgradeable(_to).safeTransfer(msg.sender, _toAmount);
}
/**
* @dev Updates the access of the account. Only owner can update access.
*/
function updateAccess(address _account, bool _approved) external onlyOwner {
approved[_account] = _approved;
emit AccessUpdated(_account, _approved);
}
/**
* @dev Withdraws asset from the converter. Only owner can withdraw.
*/
function withdraw(address _token, uint256 _amount) external onlyOwner {
IERC20Upgradeable(_token).safeTransfer(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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
// solhint-disable-next-line compiler-version
pragma solidity ^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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.8.0;
import "../IERC20Upgradeable.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 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable 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(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.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.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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
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 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) {
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;
}
}
}
| Updates the access of the account. Only owner can update access./ | function updateAccess(address _account, bool _approved) external onlyOwner {
approved[_account] = _approved;
emit AccessUpdated(_account, _approved);
}
| 11,943,422 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC721.sol";
contract RealEstateBidding is ERC721 {
// struct for each bid
struct Bid {
address bidAddress;
uint256 bidAmount;
}
//Struct for each bid process
struct SingleBidProcess {
address realtor;
bool onMarket;
Bid highestBid;
bool winnerRevealed;
address winner;
}
//tokens On market list to iterate
uint256[] public market;
//tokens on market mapping for uinqe access
mapping(uint256 => bool) inMarket;
//mapping from token Ids to bid process
mapping(uint256 => SingleBidProcess) allBids;
//-- Events ---
event PropOnMarket(uint256 indexed tokenId, address indexed realtor);
event HighBid(uint256 indexed tokenId, address indexed bidder);
event WinnerRevealed(
uint256 indexed tokenId,
address indexed winner,
uint256 indexed price
);
event PropOnWithdraw(uint256 indexed tokenId);
constructor() public ERC721("RealEstateBidding", "REB") {}
function mint(uint256 propID) public {
_mint(msg.sender, propID);
}
//Function to assign a realtor by owner
function assignRealtor(uint256 tokenId, address realtor) public {
require(
ownerOf(tokenId) == msg.sender,
"RealStatebidding: Can not assign for others token"
);
require(
ownerOf(tokenId) != address(0),
"RealStatebidding: No such token"
);
allBids[tokenId] = SingleBidProcess(
realtor,
false,
Bid(address(0), 0),
false,
address(0)
);
}
//function to place realstate on market by realtor
function putOnMarket(uint256 tokenId) public {
//check if token exists
//check if sender is the assigned realtor
require(
msg.sender == allBids[tokenId].realtor,
"RealStatebidding: Only assigned realtor can call this function."
);
//change on market to true on bidProcess struct
allBids[tokenId].onMarket = true;
if (!inMarket[tokenId]) {
inMarket[tokenId] = true;
market.push(tokenId);
}
// Fire event on market
emit PropOnMarket(tokenId, msg.sender);
}
//biding on properties
function bid(uint256 tokenId, uint256 amount) public {
//check if tokenId is still on market
require(
allBids[tokenId].onMarket,
"RealStatebidding:Property is no longer on Market"
);
//check if amount is higher than highest bid
require(
allBids[tokenId].highestBid.bidAmount < amount,
"RealStatebidding:There is already a highest bid on this property"
);
//replace highest bid with new bid
allBids[tokenId].highestBid = Bid(msg.sender, amount);
//push bid to array bids
//Fire new high bid
emit HighBid(tokenId, msg.sender);
}
// Reveal winner function
function revealWinner(uint256 tokenId) public returns (address) {
// Check is caller the realtor
require(
msg.sender == allBids[tokenId].realtor,
"RealStatebidding: Only assigned realtor can call this function."
);
// check if there is a bid on property
if (allBids[tokenId].highestBid.bidAmount == 0) {
return address(0);
} else {
allBids[tokenId].onMarket = false;
allBids[tokenId].winnerRevealed = true;
allBids[tokenId].winner = allBids[tokenId].highestBid.bidAddress;
emit WinnerRevealed(
tokenId,
allBids[tokenId].winner,
allBids[tokenId].highestBid.bidAmount
);
return allBids[tokenId].winner;
//Fire new high bid
}
}
// function view Bids on my property
function getHighestBid(uint256 tokenId) public view returns (uint256) {
return allBids[tokenId].highestBid.bidAmount;
}
// function get market size
function getMarketSize() public view returns (uint256) {
//Can only view bids On my property
return market.length;
}
// function to withdraw property from market
function withdrawFromMarket(uint256 tokenId) public returns (bool) {
//Can only wwithdraw for my property
require(
ownerOf(tokenId) == msg.sender,
"RealStatebidding: Can not withdraw others token"
);
allBids[tokenId].onMarket = false;
allBids[tokenId].realtor = address(0);
//Fire event property withdraw from market
emit PropOnWithdraw(tokenId);
return true;
}
// Getting single bid
function getBidProcess(uint256 tokenId)
public
view
returns (
address,
bool,
address,
uint256,
bool,
address
)
{
//check if tokenId is still on market
require(
allBids[tokenId].onMarket,
"RealStatebidding:Property is no longer on Market"
);
return (
allBids[tokenId].realtor,
allBids[tokenId].onMarket,
allBids[tokenId].highestBid.bidAddress,
allBids[tokenId].highestBid.bidAmount,
allBids[tokenId].winnerRevealed,
allBids[tokenId].winner
);
}
}
| Function to assign a realtor by owner | function assignRealtor(uint256 tokenId, address realtor) public {
require(
ownerOf(tokenId) == msg.sender,
"RealStatebidding: Can not assign for others token"
);
require(
ownerOf(tokenId) != address(0),
"RealStatebidding: No such token"
);
allBids[tokenId] = SingleBidProcess(
realtor,
false,
Bid(address(0), 0),
false,
address(0)
);
}
| 1,801,626 |
pragma solidity 0.4.21;
pragma experimental "v0.5.0";
interface Token {
function totalSupply() external returns (uint256);
function balanceOf(address) external returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function approve(address, uint256) external returns (bool);
function allowance(address, address) external returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Dex2 {
//------------------------------ Struct Definitions: ---------------------------------------------
struct TokenInfo {
string symbol; // e.g., "ETH", "ADX"
address tokenAddr; // ERC20 token address
uint64 scaleFactor; // <original token amount> = <scaleFactor> x <DEx amountE8> / 1e8
uint minDeposit; // mininum deposit (original token amount) allowed for this token
}
struct TraderInfo {
address withdrawAddr;
uint8 feeRebatePercent; // range: [0, 100]
}
struct TokenAccount {
uint64 balanceE8; // available amount for trading
uint64 pendingWithdrawE8; // the amount to be transferred out from this contract to the trader
}
struct Order {
uint32 pairId; // <cashId>(16) <stockId>(16)
uint8 action; // 0 means BUY; 1 means SELL
uint8 ioc; // 0 means a regular order; 1 means an immediate-or-cancel (IOC) order
uint64 priceE8;
uint64 amountE8;
uint64 expireTimeSec;
}
struct Deposit {
address traderAddr;
uint16 tokenCode;
uint64 pendingAmountE8; // amount to be confirmed for trading purpose
}
struct DealInfo {
uint16 stockCode; // stock token code
uint16 cashCode; // cash token code
uint64 stockDealAmountE8;
uint64 cashDealAmountE8;
}
struct ExeStatus {
uint64 logicTimeSec; // logic timestamp for checking order expiration
uint64 lastOperationIndex; // index of the last executed operation
}
//----------------- Constants: -------------------------------------------------------------------
uint constant MAX_UINT256 = 2**256 - 1;
uint16 constant MAX_FEE_RATE_E4 = 60; // the upper limit of a fee rate is 0.6%
// <original ETH amount in Wei> = <DEx amountE8> * <ETH_SCALE_FACTOR> / 1e8
uint64 constant ETH_SCALE_FACTOR = 10**18;
uint8 constant ACTIVE = 0;
uint8 constant CLOSED = 2;
bytes32 constant HASHTYPES =
keccak256('string title', 'address market_address', 'uint64 nonce', 'uint64 expire_time_sec',
'uint64 amount_e8', 'uint64 price_e8', 'uint8 immediate_or_cancel', 'uint8 action',
'uint16 cash_token_code', 'uint16 stock_token_code');
//----------------- States that cannot be changed once set: --------------------------------------
address public admin; // admin address, and it cannot be changed
mapping (uint16 => TokenInfo) public tokens; // mapping of token code to token information
//----------------- Other states: ----------------------------------------------------------------
uint8 public marketStatus; // market status: 0 - Active; 1 - Suspended; 2 - Closed
uint16 public makerFeeRateE4; // maker fee rate (* 10**4)
uint16 public takerFeeRateE4; // taker fee rate (* 10**4)
uint16 public withdrawFeeRateE4; // withdraw fee rate (* 10**4)
uint64 public lastDepositIndex; // index of the last deposit operation
ExeStatus public exeStatus; // status of operation execution
mapping (address => TraderInfo) public traders; // mapping of trade address to trader information
mapping (uint176 => TokenAccount) public accounts; // mapping of trader token key to its account information
mapping (uint224 => Order) public orders; // mapping of order key to order information
mapping (uint64 => Deposit) public deposits; // mapping of deposit index to deposit information
//------------------------------ Dex2 Events: ----------------------------------------------------
event DeployMarketEvent();
event ChangeMarketStatusEvent(uint8 status);
event SetTokenInfoEvent(uint16 tokenCode, string symbol, address tokenAddr, uint64 scaleFactor, uint minDeposit);
event SetWithdrawAddrEvent(address trader, address withdrawAddr);
event DepositEvent(address trader, uint16 tokenCode, string symbol, uint64 amountE8, uint64 depositIndex);
event WithdrawEvent(address trader, uint16 tokenCode, string symbol, uint64 amountE8, uint64 lastOpIndex);
event TransferFeeEvent(uint16 tokenCode, uint64 amountE8, address toAddr);
// `balanceE8` is the total balance after this deposit confirmation
event ConfirmDepositEvent(address trader, uint16 tokenCode, uint64 balanceE8);
// `amountE8` is the post-fee initiated withdraw amount
// `pendingWithdrawE8` is the total pending withdraw amount after this withdraw initiation
event InitiateWithdrawEvent(address trader, uint16 tokenCode, uint64 amountE8, uint64 pendingWithdrawE8);
event MatchOrdersEvent(address trader1, uint64 nonce1, address trader2, uint64 nonce2);
event HardCancelOrderEvent(address trader, uint64 nonce);
event SetFeeRatesEvent(uint16 makerFeeRateE4, uint16 takerFeeRateE4, uint16 withdrawFeeRateE4);
event SetFeeRebatePercentEvent(address trader, uint8 feeRebatePercent);
//------------------------------ Contract Initialization: ----------------------------------------
function Dex2(address admin_) public {
admin = admin_;
setTokenInfo(0 /*tokenCode*/, "ETH", 0 /*tokenAddr*/, ETH_SCALE_FACTOR, 0 /*minDeposit*/);
emit DeployMarketEvent();
}
//------------------------------ External Functions: ---------------------------------------------
function() external {
revert();
}
// Change the market status of DEX.
function changeMarketStatus(uint8 status_) external {
if (msg.sender != admin) revert();
if (marketStatus == CLOSED) revert(); // closed is forever
marketStatus = status_;
emit ChangeMarketStatusEvent(status_);
}
function setWithdrawAddr(address withdrawAddr) external {
if (withdrawAddr == 0) revert();
if (traders[msg.sender].withdrawAddr != 0) revert(); // cannot change withdrawAddr once set
traders[msg.sender].withdrawAddr = withdrawAddr;
emit SetWithdrawAddrEvent(msg.sender, withdrawAddr);
}
// Deposits ETH from msg.sender for the given trader.
function depositEth(address traderAddr) external payable {
if (marketStatus != ACTIVE) revert();
if (traderAddr == 0) revert();
if (msg.value < tokens[0].minDeposit) revert();
if (msg.data.length != 4 + 32) revert(); // length condition of param count
uint64 pendingAmountE8 = uint64(msg.value / (ETH_SCALE_FACTOR / 10**8)); // msg.value is in Wei
if (pendingAmountE8 == 0) revert();
uint64 depositIndex = ++lastDepositIndex;
setDeposits(depositIndex, traderAddr, 0, pendingAmountE8);
emit DepositEvent(traderAddr, 0, "ETH", pendingAmountE8, depositIndex);
}
// Deposits token (other than ETH) from msg.sender for a specified trader.
//
// After this deposit has been confirmed enough times on the blockchain, it will be added to
// the trader's token account for trading.
function depositToken(address traderAddr, uint16 tokenCode, uint originalAmount) external {
if (marketStatus != ACTIVE) revert();
if (traderAddr == 0) revert();
if (tokenCode == 0) revert(); // this function does not handle ETH
if (msg.data.length != 4 + 32 + 32 + 32) revert(); // length condition of param count
TokenInfo memory tokenInfo = tokens[tokenCode];
if (originalAmount < tokenInfo.minDeposit) revert();
if (tokenInfo.scaleFactor == 0) revert(); // unsupported token
// Remember to call Token(address).approve(this, amount) from msg.sender in advance.
if (!Token(tokenInfo.tokenAddr).transferFrom(msg.sender, this, originalAmount)) revert();
if (originalAmount > MAX_UINT256 / 10**8) revert(); // avoid overflow
uint amountE8 = originalAmount * 10**8 / uint(tokenInfo.scaleFactor);
if (amountE8 >= 2**64 || amountE8 == 0) revert();
uint64 depositIndex = ++lastDepositIndex;
setDeposits(depositIndex, traderAddr, tokenCode, uint64(amountE8));
emit DepositEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8), depositIndex);
}
// Withdraw ETH from the contract.
function withdrawEth(address traderAddr) external {
if (traderAddr == 0) revert();
if (msg.data.length != 4 + 32) revert(); // length condition of param count
uint176 accountKey = uint176(traderAddr);
uint amountE8 = accounts[accountKey].pendingWithdrawE8;
if (amountE8 == 0) return;
// Write back to storage before making the transfer.
accounts[accountKey].pendingWithdrawE8 = 0;
uint truncatedWei = amountE8 * (ETH_SCALE_FACTOR / 10**8);
address withdrawAddr = traders[traderAddr].withdrawAddr;
if (withdrawAddr == 0) withdrawAddr = traderAddr;
withdrawAddr.transfer(truncatedWei);
emit WithdrawEvent(traderAddr, 0, "ETH", uint64(amountE8), exeStatus.lastOperationIndex);
}
// Withdraw token (other than ETH) from the contract.
function withdrawToken(address traderAddr, uint16 tokenCode) external {
if (traderAddr == 0) revert();
if (tokenCode == 0) revert(); // this function does not handle ETH
if (msg.data.length != 4 + 32 + 32) revert(); // length condition of param count
TokenInfo memory tokenInfo = tokens[tokenCode];
if (tokenInfo.scaleFactor == 0) revert(); // unsupported token
uint176 accountKey = uint176(tokenCode) << 160 | uint176(traderAddr);
uint amountE8 = accounts[accountKey].pendingWithdrawE8;
if (amountE8 == 0) return;
// Write back to storage before making the transfer.
accounts[accountKey].pendingWithdrawE8 = 0;
uint truncatedAmount = amountE8 * uint(tokenInfo.scaleFactor) / 10**8;
address withdrawAddr = traders[traderAddr].withdrawAddr;
if (withdrawAddr == 0) withdrawAddr = traderAddr;
if (!Token(tokenInfo.tokenAddr).transfer(withdrawAddr, truncatedAmount)) revert();
emit WithdrawEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8),
exeStatus.lastOperationIndex);
}
function transferFee(uint16 tokenCode, uint64 amountE8, address toAddr) external {
if (msg.sender != admin) revert();
if (toAddr == 0) revert();
if (msg.data.length != 4 + 32 + 32 + 32) revert();
TokenAccount memory feeAccount = accounts[uint176(tokenCode) << 160];
uint64 withdrawE8 = feeAccount.pendingWithdrawE8;
if (amountE8 < withdrawE8) {
withdrawE8 = amountE8;
}
feeAccount.pendingWithdrawE8 -= withdrawE8;
accounts[uint176(tokenCode) << 160] = feeAccount;
TokenInfo memory tokenInfo = tokens[tokenCode];
uint originalAmount = uint(withdrawE8) * uint(tokenInfo.scaleFactor) / 10**8;
if (tokenCode == 0) { // ETH
toAddr.transfer(originalAmount);
} else {
if (!Token(tokenInfo.tokenAddr).transfer(toAddr, originalAmount)) revert();
}
emit TransferFeeEvent(tokenCode, withdrawE8, toAddr);
}
function exeSequence(uint header, uint[] body) external {
if (msg.sender != admin) revert();
uint64 nextOperationIndex = uint64(header);
if (nextOperationIndex != exeStatus.lastOperationIndex + 1) revert(); // check index
uint64 newLogicTimeSec = uint64(header >> 64);
if (newLogicTimeSec < exeStatus.logicTimeSec) revert();
for (uint i = 0; i < body.length; nextOperationIndex++) {
uint bits = body[i];
uint opcode = bits & 0xFFFF;
bits >>= 16;
if ((opcode >> 8) != 0xDE) revert(); // check the magic number
// ConfirmDeposit: <depositIndex>(64)
if (opcode == 0xDE01) {
confirmDeposit(uint64(bits));
i += 1;
continue;
}
// InitiateWithdraw: <amountE8>(64) <tokenCode>(16) <traderAddr>(160)
if (opcode == 0xDE02) {
initiateWithdraw(uint176(bits), uint64(bits >> 176));
i += 1;
continue;
}
//-------- The rest operation types are allowed only when the market is active ---------
if (marketStatus != ACTIVE) revert();
// MatchOrders
if (opcode == 0xDE03) {
uint8 v1 = uint8(bits);
bits >>= 8; // bits is now the key of the maker order
Order memory makerOrder;
if (v1 == 0) { // the order is already in storage
if (i + 1 >= body.length) revert(); // at least 1 body element left
makerOrder = orders[uint224(bits)];
i += 1;
} else {
if (orders[uint224(bits)].pairId != 0) revert(); // the order must not be already in storage
if (i + 4 >= body.length) revert(); // at least 4 body elements left
makerOrder = parseNewOrder(uint224(bits) /*makerOrderKey*/, v1, body, i);
i += 4;
}
uint8 v2 = uint8(body[i]);
uint224 takerOrderKey = uint224(body[i] >> 8);
Order memory takerOrder;
if (v2 == 0) { // the order is already in storage
takerOrder = orders[takerOrderKey];
i += 1;
} else {
if (orders[takerOrderKey].pairId != 0) revert(); // the order must not be already in storage
if (i + 3 >= body.length) revert(); // at least 3 body elements left
takerOrder = parseNewOrder(takerOrderKey, v2, body, i);
i += 4;
}
matchOrder(uint224(bits) /*makerOrderKey*/, makerOrder, takerOrderKey, takerOrder);
continue;
}
// HardCancelOrder: <nonce>(64) <traderAddr>(160)
if (opcode == 0xDE04) {
hardCancelOrder(uint224(bits) /*orderKey*/);
i += 1;
continue;
}
// SetFeeRates: <withdrawFeeRateE4>(16) <takerFeeRateE4>(16) <makerFeeRateE4>(16)
if (opcode == 0xDE05) {
setFeeRates(uint16(bits), uint16(bits >> 16), uint16(bits >> 32));
i += 1;
continue;
}
// SetFeeRebatePercent: <rebatePercent>(8) <traderAddr>(160)
if (opcode == 0xDE06) {
setFeeRebatePercent(address(bits) /*traderAddr*/, uint8(bits >> 160) /*rebatePercent*/);
i += 1;
continue;
}
} // for loop
setExeStatus(newLogicTimeSec, nextOperationIndex - 1);
} // function exeSequence
//------------------------------ Public Functions: -----------------------------------------------
// Set token information.
function setTokenInfo(uint16 tokenCode, string symbol, address tokenAddr, uint64 scaleFactor,
uint minDeposit) public {
if (msg.sender != admin) revert();
if (marketStatus != ACTIVE) revert();
if (scaleFactor == 0) revert();
TokenInfo memory info = tokens[tokenCode];
if (info.scaleFactor != 0) { // this token already exists
// For an existing token only the minDeposit field can be updated.
tokens[tokenCode].minDeposit = minDeposit;
emit SetTokenInfoEvent(tokenCode, info.symbol, info.tokenAddr, info.scaleFactor, minDeposit);
return;
}
tokens[tokenCode].symbol = symbol;
tokens[tokenCode].tokenAddr = tokenAddr;
tokens[tokenCode].scaleFactor = scaleFactor;
tokens[tokenCode].minDeposit = minDeposit;
emit SetTokenInfoEvent(tokenCode, symbol, tokenAddr, scaleFactor, minDeposit);
}
//------------------------------ Private Functions: ----------------------------------------------
function setDeposits(uint64 depositIndex, address traderAddr, uint16 tokenCode, uint64 amountE8) private {
deposits[depositIndex].traderAddr = traderAddr;
deposits[depositIndex].tokenCode = tokenCode;
deposits[depositIndex].pendingAmountE8 = amountE8;
}
function setExeStatus(uint64 logicTimeSec, uint64 lastOperationIndex) private {
exeStatus.logicTimeSec = logicTimeSec;
exeStatus.lastOperationIndex = lastOperationIndex;
}
function confirmDeposit(uint64 depositIndex) private {
Deposit memory deposit = deposits[depositIndex];
uint176 accountKey = (uint176(deposit.tokenCode) << 160) | uint176(deposit.traderAddr);
TokenAccount memory account = accounts[accountKey];
// Check that pending amount is non-zero and no overflow would happen.
if (account.balanceE8 + deposit.pendingAmountE8 <= account.balanceE8) revert();
account.balanceE8 += deposit.pendingAmountE8;
deposits[depositIndex].pendingAmountE8 = 0;
accounts[accountKey].balanceE8 += deposit.pendingAmountE8;
emit ConfirmDepositEvent(deposit.traderAddr, deposit.tokenCode, account.balanceE8);
}
function initiateWithdraw(uint176 tokenAccountKey, uint64 amountE8) private {
uint64 balanceE8 = accounts[tokenAccountKey].balanceE8;
uint64 pendingWithdrawE8 = accounts[tokenAccountKey].pendingWithdrawE8;
if (balanceE8 < amountE8 || amountE8 == 0) revert();
balanceE8 -= amountE8;
uint64 feeE8 = calcFeeE8(amountE8, withdrawFeeRateE4, address(tokenAccountKey));
amountE8 -= feeE8;
if (pendingWithdrawE8 + amountE8 < amountE8) revert(); // check overflow
pendingWithdrawE8 += amountE8;
accounts[tokenAccountKey].balanceE8 = balanceE8;
accounts[tokenAccountKey].pendingWithdrawE8 = pendingWithdrawE8;
// Note that the fee account has a dummy trader address of 0.
if (accounts[tokenAccountKey & (0xffff << 160)].pendingWithdrawE8 + feeE8 >= feeE8) { // no overflow
accounts[tokenAccountKey & (0xffff << 160)].pendingWithdrawE8 += feeE8;
}
emit InitiateWithdrawEvent(address(tokenAccountKey), uint16(tokenAccountKey >> 160) /*tokenCode*/,
amountE8, pendingWithdrawE8);
}
function getDealInfo(uint32 pairId, uint64 priceE8, uint64 amount1E8, uint64 amount2E8)
private pure returns (DealInfo deal) {
deal.stockCode = uint16(pairId);
deal.cashCode = uint16(pairId >> 16);
if (deal.stockCode == deal.cashCode) revert(); // we disallow homogeneous trading
deal.stockDealAmountE8 = amount1E8 < amount2E8 ? amount1E8 : amount2E8;
uint cashDealAmountE8 = uint(priceE8) * uint(deal.stockDealAmountE8) / 10**8;
if (cashDealAmountE8 >= 2**64) revert();
deal.cashDealAmountE8 = uint64(cashDealAmountE8);
}
function calcFeeE8(uint64 amountE8, uint feeRateE4, address traderAddr)
private view returns (uint64) {
uint feeE8 = uint(amountE8) * feeRateE4 / 10000;
feeE8 -= feeE8 * uint(traders[traderAddr].feeRebatePercent) / 100;
return uint64(feeE8);
}
function settleAccounts(DealInfo deal, address traderAddr, uint feeRateE4, bool isBuyer) private {
uint16 giveTokenCode = isBuyer ? deal.cashCode : deal.stockCode;
uint16 getTokenCode = isBuyer ? deal.stockCode : deal.cashCode;
uint64 giveAmountE8 = isBuyer ? deal.cashDealAmountE8 : deal.stockDealAmountE8;
uint64 getAmountE8 = isBuyer ? deal.stockDealAmountE8 : deal.cashDealAmountE8;
uint176 giveAccountKey = uint176(giveTokenCode) << 160 | uint176(traderAddr);
uint176 getAccountKey = uint176(getTokenCode) << 160 | uint176(traderAddr);
uint64 feeE8 = calcFeeE8(getAmountE8, feeRateE4, traderAddr);
getAmountE8 -= feeE8;
// Check overflow.
if (accounts[giveAccountKey].balanceE8 < giveAmountE8) revert();
if (accounts[getAccountKey].balanceE8 + getAmountE8 < getAmountE8) revert();
// Write storage.
accounts[giveAccountKey].balanceE8 -= giveAmountE8;
accounts[getAccountKey].balanceE8 += getAmountE8;
if (accounts[uint176(getTokenCode) << 160].pendingWithdrawE8 + feeE8 >= feeE8) { // no overflow
accounts[uint176(getTokenCode) << 160].pendingWithdrawE8 += feeE8;
}
}
function setOrders(uint224 orderKey, uint32 pairId, uint8 action, uint8 ioc,
uint64 priceE8, uint64 amountE8, uint64 expireTimeSec) private {
orders[orderKey].pairId = pairId;
orders[orderKey].action = action;
orders[orderKey].ioc = ioc;
orders[orderKey].priceE8 = priceE8;
orders[orderKey].amountE8 = amountE8;
orders[orderKey].expireTimeSec = expireTimeSec;
}
function matchOrder(uint224 makerOrderKey, Order makerOrder,
uint224 takerOrderKey, Order takerOrder) private {
// Check trading conditions.
if (marketStatus != ACTIVE) revert();
if (makerOrderKey == takerOrderKey) revert(); // the two orders must not have the same key
if (makerOrder.pairId != takerOrder.pairId) revert();
if (makerOrder.action == takerOrder.action) revert();
if (makerOrder.priceE8 == 0 || takerOrder.priceE8 == 0) revert();
if (makerOrder.action == 0 && makerOrder.priceE8 < takerOrder.priceE8) revert();
if (takerOrder.action == 0 && takerOrder.priceE8 < makerOrder.priceE8) revert();
if (makerOrder.amountE8 == 0 || takerOrder.amountE8 == 0) revert();
if (makerOrder.expireTimeSec <= exeStatus.logicTimeSec) revert();
if (takerOrder.expireTimeSec <= exeStatus.logicTimeSec) revert();
DealInfo memory deal = getDealInfo(
makerOrder.pairId, makerOrder.priceE8, makerOrder.amountE8, takerOrder.amountE8);
// Update accounts.
settleAccounts(deal, address(makerOrderKey), makerFeeRateE4, (makerOrder.action == 0));
settleAccounts(deal, address(takerOrderKey), takerFeeRateE4, (takerOrder.action == 0));
// Update orders.
if (makerOrder.ioc == 1) { // IOC order
makerOrder.amountE8 = 0;
} else {
makerOrder.amountE8 -= deal.stockDealAmountE8;
}
if (takerOrder.ioc == 1) { // IOC order
takerOrder.amountE8 = 0;
} else {
takerOrder.amountE8 -= deal.stockDealAmountE8;
}
// Write orders back to storage.
setOrders(makerOrderKey, makerOrder.pairId, makerOrder.action, makerOrder.ioc,
makerOrder.priceE8, makerOrder.amountE8, makerOrder.expireTimeSec);
setOrders(takerOrderKey, takerOrder.pairId, takerOrder.action, takerOrder.ioc,
takerOrder.priceE8, takerOrder.amountE8, takerOrder.expireTimeSec);
emit MatchOrdersEvent(address(makerOrderKey), uint64(makerOrderKey >> 160) /*nonce*/,
address(takerOrderKey), uint64(takerOrderKey >> 160) /*nonce*/);
}
function hardCancelOrder(uint224 orderKey) private {
orders[orderKey].pairId = 0xFFFFFFFF;
orders[orderKey].amountE8 = 0;
emit HardCancelOrderEvent(address(orderKey) /*traderAddr*/, uint64(orderKey >> 160) /*nonce*/);
}
function setFeeRates(uint16 makerE4, uint16 takerE4, uint16 withdrawE4) private {
if (makerE4 > MAX_FEE_RATE_E4) revert();
if (takerE4 > MAX_FEE_RATE_E4) revert();
if (withdrawE4 > MAX_FEE_RATE_E4) revert();
makerFeeRateE4 = makerE4;
takerFeeRateE4 = takerE4;
withdrawFeeRateE4 = withdrawE4;
emit SetFeeRatesEvent(makerE4, takerE4, withdrawE4);
}
function setFeeRebatePercent(address traderAddr, uint8 feeRebatePercent) private {
if (feeRebatePercent > 100) revert();
traders[traderAddr].feeRebatePercent = feeRebatePercent;
emit SetFeeRebatePercentEvent(traderAddr, feeRebatePercent);
}
function parseNewOrder(uint224 orderKey, uint8 v, uint[] body, uint i) private view returns (Order) {
// bits: <expireTimeSec>(64) <amountE8>(64) <priceE8>(64) <ioc>(8) <action>(8) <pairId>(32)
uint240 bits = uint240(body[i + 1]);
uint64 nonce = uint64(orderKey >> 160);
address traderAddr = address(orderKey);
if (traderAddr == 0) revert(); // check zero addr early since `ecrecover` returns 0 on error
// verify the signature of the trader
bytes32 hash1 = keccak256("\x19Ethereum Signed Message:\n70DEx2 Order: ", address(this), nonce, bits);
if (traderAddr != ecrecover(hash1, v, bytes32(body[i + 2]), bytes32(body[i + 3]))) {
bytes32 hashValues = keccak256("DEx2 Order", address(this), nonce, bits);
bytes32 hash2 = keccak256(HASHTYPES, hashValues);
if (traderAddr != ecrecover(hash2, v, bytes32(body[i + 2]), bytes32(body[i + 3]))) revert();
}
Order memory order;
order.pairId = uint32(bits); bits >>= 32;
order.action = uint8(bits); bits >>= 8;
order.ioc = uint8(bits); bits >>= 8;
order.priceE8 = uint64(bits); bits >>= 64;
order.amountE8 = uint64(bits); bits >>= 64;
order.expireTimeSec = uint64(bits);
return order;
}
} // contract | Change the market status of DEX. | function changeMarketStatus(uint8 status_) external {
if (msg.sender != admin) revert();
marketStatus = status_;
emit ChangeMarketStatusEvent(status_);
}
| 6,262,517 |
pragma solidity ^0.4.23;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../common/interfaces/ISettingsRegistry.sol";
import "../../common/SettingIds.sol";
contract FrozenDividend is Ownable, SettingIds{
using SafeMath for *;
event DepositKTON(address indexed _from, uint256 _value);
event WithdrawKTON(address indexed _to, uint256 _value);
event Income(address indexed _from, uint256 _value);
event OnDividendsWithdraw(address indexed _user, uint256 _ringValue);
uint256 constant internal magnitude = 2**64;
mapping(address => uint256) public ktonBalances;
mapping(address => int256) internal ringPayoutsTo;
uint256 public ktonSupply = 0;
uint256 internal ringProfitPerKTON;
ISettingsRegistry public registry;
constructor(ISettingsRegistry _registry) public {
// initializeContract
registry = _registry;
}
function tokenFallback(address _from, uint256 _value, bytes _data) public {
address ring = registry.addressOf(SettingIds.CONTRACT_RING_ERC20_TOKEN);
address kton = registry.addressOf(SettingIds.CONTRACT_KTON_ERC20_TOKEN);
if (msg.sender == ring) {
// trigger settlement
_incomeRING(_value);
}
if (msg.sender == kton) {
_depositKTON(_from, _value);
}
}
function incomeRING(uint256 _ringValue) public {
address ring = registry.addressOf(SettingIds.CONTRACT_RING_ERC20_TOKEN);
ERC20(ring).transferFrom(msg.sender, address(this), _ringValue);
_incomeRING(_ringValue);
}
function _incomeRING(uint256 _ringValue) internal {
if (ktonSupply > 0) {
ringProfitPerKTON = ringProfitPerKTON.add(
_ringValue.mul(magnitude).div(ktonSupply)
);
}
emit Income(msg.sender, _ringValue);
}
function depositKTON(uint256 _ktonValue) public {
address kton = registry.addressOf(SettingIds.CONTRACT_KTON_ERC20_TOKEN);
ERC20(kton).transferFrom(msg.sender, address(this), _ktonValue);
_depositKTON(msg.sender, _ktonValue);
}
function _depositKTON(address _from, uint256 _ktonValue) internal {
ktonBalances[_from] = ktonBalances[_from].add(_ktonValue);
ktonSupply = ktonSupply.add(_ktonValue);
int256 _updatedPayouts = (int256) (ringProfitPerKTON * _ktonValue);
ringPayoutsTo[_from] += _updatedPayouts;
emit DepositKTON(_from, _ktonValue);
}
function withdrawKTON(uint256 _ktonValue) public {
require(_ktonValue <= ktonBalances[msg.sender], "Withdraw KTON amount should not larger than balance.");
ktonBalances[msg.sender] = ktonBalances[msg.sender].sub(_ktonValue);
ktonSupply = ktonSupply.sub(_ktonValue);
// update dividends tracker
int256 _updatedPayouts = (int256) (ringProfitPerKTON * _ktonValue);
ringPayoutsTo[msg.sender] -= _updatedPayouts;
emit WithdrawKTON(msg.sender, _ktonValue);
}
function withdrawDividends() public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = dividendsOf(_customerAddress);
// update dividend tracker
ringPayoutsTo[_customerAddress] += (int256) (_dividends * magnitude);
address ring = registry.addressOf(SettingIds.CONTRACT_RING_ERC20_TOKEN);
ERC20(ring).transfer(_customerAddress, _dividends);
// fire event
emit OnDividendsWithdraw(_customerAddress, _dividends);
}
function dividendsOf(address _customerAddress) public view returns(uint256)
{
return (uint256) ((int256)(ringProfitPerKTON * ktonBalances[_customerAddress]) - ringPayoutsTo[_customerAddress]) / magnitude;
}
/**
* Retrieve the total token supply.
*/
function totalKTON() public view returns(uint256)
{
return ktonSupply;
}
function setRegistry(address _registry) public onlyOwner {
registry = ISettingsRegistry(_registry);
}
} | setup data update dividend tracker fire event | function withdrawDividends() public
{
address _customerAddress = msg.sender;
uint256 _dividends = dividendsOf(_customerAddress);
ringPayoutsTo[_customerAddress] += (int256) (_dividends * magnitude);
address ring = registry.addressOf(SettingIds.CONTRACT_RING_ERC20_TOKEN);
ERC20(ring).transfer(_customerAddress, _dividends);
emit OnDividendsWithdraw(_customerAddress, _dividends);
}
| 958,887 |
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "./base/ModuleManager.sol";
import "./base/OwnerManager.sol";
import "./base/FallbackManager.sol";
import "./base/GuardManager.sol";
import "./common/EtherPaymentFallback.sol";
import "./common/Singleton.sol";
import "./common/SignatureDecoder.sol";
import "./common/SecuredTokenTransfer.sol";
import "./common/StorageAccessible.sol";
import "./interfaces/ISignatureValidator.sol";
import "./external/GnosisSafeMath.sol";
/// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract GnosisSafe is
EtherPaymentFallback,
Singleton,
ModuleManager,
OwnerManager,
SignatureDecoder,
SecuredTokenTransfer,
ISignatureValidatorConstants,
FallbackManager,
StorageAccessible,
GuardManager
{
using GnosisSafeMath for uint256;
string public constant VERSION = "1.3.0";
// keccak256(
// "EIP712Domain(uint256 chainId,address verifyingContract)"
// );
bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
// keccak256(
// "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
// );
bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
event SignMsg(bytes32 indexed msgHash);
event ExecutionFailure(bytes32 txHash, uint256 payment);
event ExecutionSuccess(bytes32 txHash, uint256 payment);
uint256 public nonce;
bytes32 private _deprecatedDomainSeparator;
// Mapping to keep track of all message hashes that have been approved by ALL REQUIRED owners
mapping(bytes32 => uint256) public signedMessages;
// Mapping to keep track of all hashes (message or transaction) that have been approved by ANY owners
mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
// This constructor ensures that this contract can only be used as a master copy for Proxy contracts
constructor() {
// By setting the threshold it is not possible to call setup anymore,
// so we create a Safe with 0 owners and threshold 1.
// This is an unusable Safe, perfect for the singleton
threshold = 1;
}
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
/// @param fallbackHandler Handler for fallback calls to this contract
/// @param paymentToken Token that should be used for the payment (0 is ETH)
/// @param payment Value that should be paid
/// @param paymentReceiver Address that should receive the payment (or 0 if tx.origin)
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external {
// setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
setupOwners(_owners, _threshold);
if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
// As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
setupModules(to, data);
if (payment > 0) {
// To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
// baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
}
emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
}
/// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
/// Note: The fees are always transferred, even if the user transaction fails.
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @param safeTxGas Gas that should be used for the Safe transaction.
/// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Gas price that should be used for the payment calculation.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
function execTransaction(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures
) public payable virtual returns (bool success) {
bytes32 txHash;
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
bytes memory txHashData =
encodeTransactionData(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
nonce
);
// Increase nonce and execute transaction.
nonce++;
txHash = keccak256(txHashData);
checkSignatures(txHash, txHashData, signatures);
}
address guard = getGuard();
{
if (guard != address(0)) {
Guard(guard).checkTransaction(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
signatures,
msg.sender
);
}
}
// We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
// We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
uint256 gasUsed = gasleft();
// If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
// We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
gasUsed = gasUsed.sub(gasleft());
// If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
// This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
// We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
uint256 payment = 0;
if (gasPrice > 0) {
payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
}
if (success) emit ExecutionSuccess(txHash, payment);
else emit ExecutionFailure(txHash, payment);
}
{
if (guard != address(0)) {
Guard(guard).checkAfterExecution(txHash, success);
}
}
}
function handlePayment(
uint256 gasUsed,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver
) private returns (uint256 payment) {
// solhint-disable-next-line avoid-tx-origin
address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
if (gasToken == address(0)) {
// For ETH we will only adjust the gas price to not be higher than the actual used gas price
payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
require(receiver.send(payment), "GS011");
} else {
payment = gasUsed.add(baseGas).mul(gasPrice);
require(transferToken(gasToken, receiver, payment), "GS012");
}
}
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
*/
function checkSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures
) public view {
// Load threshold to avoid multiple storage loads
uint256 _threshold = threshold;
// Check that a threshold is set
require(_threshold > 0, "GS001");
checkNSignatures(dataHash, data, signatures, _threshold);
}
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
* @param requiredSignatures Amount of required valid signatures.
*/
function checkNSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures,
uint256 requiredSignatures
) public view {
// Check that the provided signature data is not too short
require(signatures.length >= requiredSignatures.mul(65), "GS020");
// There cannot be an owner with address 0.
address lastOwner = address(0);
address currentOwner;
uint8 v;
bytes32 r;
bytes32 s;
uint256 i;
for (i = 0; i < requiredSignatures; i++) {
(v, r, s) = signatureSplit(signatures, i);
if (v == 0) {
// If v is 0 then it is a contract signature
// When handling contract signatures the address of the contract is encoded into r
currentOwner = address(uint160(uint256(r)));
// Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
// This check is not completely accurate, since it is possible that more signatures than the threshold are send.
// Here we only check that the pointer is not pointing inside the part that is being processed
require(uint256(s) >= requiredSignatures.mul(65), "GS021");
// Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
require(uint256(s).add(32) <= signatures.length, "GS022");
// Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
uint256 contractSignatureLen;
// solhint-disable-next-line no-inline-assembly
assembly {
contractSignatureLen := mload(add(add(signatures, s), 0x20))
}
require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
// Check signature
bytes memory contractSignature;
// solhint-disable-next-line no-inline-assembly
assembly {
// The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
contractSignature := add(add(signatures, s), 0x20)
}
require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
} else if (v == 1) {
// If v is 1 then it is an approved hash
// When handling approved hashes the address of the approver is encoded into r
currentOwner = address(uint160(uint256(r)));
// Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
} else if (v > 30) {
// If v > 30 then default va (27,28) has been adjusted for eth_sign flow
// To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s);
} else {
// Default is the ecrecover flow with the provided data hash
// Use ecrecover with the messageHash for EOA signatures
currentOwner = ecrecover(dataHash, v, r, s);
}
require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
lastOwner = currentOwner;
}
}
/// @dev Allows to estimate a Safe transaction.
/// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
/// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
function requiredTxGas(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) external returns (uint256) {
uint256 startGas = gasleft();
// We don't provide an error message here, as we use it to return the estimate
require(execute(to, value, data, operation, gasleft()));
uint256 requiredGas = startGas - gasleft();
// Convert response to string and return via error message
revert(string(abi.encodePacked(requiredGas)));
}
/**
* @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
* @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
*/
function approveHash(bytes32 hashToApprove) external {
require(owners[msg.sender] != address(0), "GS030");
approvedHashes[msg.sender][hashToApprove] = 1;
emit ApproveHash(hashToApprove, msg.sender);
}
/// @dev Returns the chain id used by this contract.
function getChainId() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
}
/// @dev Returns the bytes that are hashed to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Gas that should be used for the safe transaction.
/// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash bytes.
function encodeTransactionData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes memory) {
bytes32 safeTxHash =
keccak256(
abi.encode(
SAFE_TX_TYPEHASH,
to,
value,
keccak256(data),
operation,
safeTxGas,
baseGas,
gasPrice,
gasToken,
refundReceiver,
_nonce
)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
}
/// @dev Returns hash to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Fas that should be used for the safe transaction.
/// @param baseGas Gas costs for data used to trigger the safe transaction.
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash.
function getTransactionHash(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes32) {
return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
/// @title Executor - A contract that can execute transactions
/// @author Richard Meissner - <[email protected]>
contract Executor {
function execute(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 txGas
) internal returns (bool success) {
if (operation == Enum.Operation.DelegateCall) {
// solhint-disable-next-line no-inline-assembly
assembly {
success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
}
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";
/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract FallbackManager is SelfAuthorized {
event ChangedFallbackHandler(address handler);
// keccak256("fallback_manager.handler.address")
bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
function internalSetFallbackHandler(address handler) internal {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, handler)
}
}
/// @dev Allows to add a contract to handle fallback calls.
/// Only fallback calls without value and with data will be forwarded.
/// This can only be done via a Safe transaction.
/// @param handler contract to handle fallback calls.
function setFallbackHandler(address handler) public authorized {
internalSetFallbackHandler(handler);
emit ChangedFallbackHandler(handler);
}
// solhint-disable-next-line payable-fallback,no-complex-fallback
fallback() external {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
let handler := sload(slot)
if iszero(handler) {
return(0, 0)
}
calldatacopy(0, 0, calldatasize())
// The msg.sender address is shifted to the left by 12 bytes to remove the padding
// Then the address without padding is stored right after the calldata
mstore(calldatasize(), shl(96, caller()))
// Add 20 bytes for the address appended add the end
let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
returndatacopy(0, 0, returndatasize())
if iszero(success) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "../interfaces/IERC165.sol";
interface Guard is IERC165 {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
abstract contract BaseGuard is Guard {
function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
return
interfaceId == type(Guard).interfaceId || // 0xe6d7a83a
interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
}
}
/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract GuardManager is SelfAuthorized {
event ChangedGuard(address guard);
// keccak256("guard_manager.guard.address")
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external authorized {
if (guard != address(0)) {
require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300");
}
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, guard)
}
emit ChangedGuard(guard);
}
function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
guard := sload(slot)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "./Executor.sol";
/// @title Module Manager - A contract that manages modules that can execute transactions via this contract
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract ModuleManager is SelfAuthorized, Executor {
event EnabledModule(address module);
event DisabledModule(address module);
event ExecutionFromModuleSuccess(address indexed module);
event ExecutionFromModuleFailure(address indexed module);
address internal constant SENTINEL_MODULES = address(0x1);
mapping(address => address) internal modules;
function setupModules(address to, bytes memory data) internal {
require(modules[SENTINEL_MODULES] == address(0), "GS100");
modules[SENTINEL_MODULES] = SENTINEL_MODULES;
if (to != address(0))
// Setup has to complete successfully or transaction fails.
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
}
/// @dev Allows to add a module to the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Enables the module `module` for the Safe.
/// @param module Module to be whitelisted.
function enableModule(address module) public authorized {
// Module address cannot be null or sentinel.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
// Module cannot be added twice.
require(modules[module] == address(0), "GS102");
modules[module] = modules[SENTINEL_MODULES];
modules[SENTINEL_MODULES] = module;
emit EnabledModule(module);
}
/// @dev Allows to remove a module from the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Disables the module `module` for the Safe.
/// @param prevModule Module that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) public authorized {
// Validate module address and check that it corresponds to module index.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
require(modules[prevModule] == module, "GS103");
modules[prevModule] = modules[module];
modules[module] = address(0);
emit DisabledModule(module);
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public virtual returns (bool success) {
// Only whitelisted modules are allowed.
require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
// Execute transaction without further confirmations.
success = execute(to, value, data, operation, gasleft());
if (success) emit ExecutionFromModuleSuccess(msg.sender);
else emit ExecutionFromModuleFailure(msg.sender);
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public returns (bool success, bytes memory returnData) {
success = execTransactionFromModule(to, value, data, operation);
// solhint-disable-next-line no-inline-assembly
assembly {
// Load free memory location
let ptr := mload(0x40)
// We allocate memory for the return data by setting the free memory location to
// current free memory location + data size + 32 bytes for data size value
mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
// Store the size
mstore(ptr, returndatasize())
// Store the data
returndatacopy(add(ptr, 0x20), 0, returndatasize())
// Point the return data to the correct memory location
returnData := ptr
}
}
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) public view returns (bool) {
return SENTINEL_MODULES != module && modules[module] != address(0);
}
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
// Init array with max page size
array = new address[](pageSize);
// Populate return array
uint256 moduleCount = 0;
address currentModule = modules[start];
while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
array[moduleCount] = currentModule;
currentModule = modules[currentModule];
moduleCount++;
}
next = currentModule;
// Set correct size of returned array
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(array, moduleCount)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";
/// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract OwnerManager is SelfAuthorized {
event AddedOwner(address owner);
event RemovedOwner(address owner);
event ChangedThreshold(uint256 threshold);
address internal constant SENTINEL_OWNERS = address(0x1);
mapping(address => address) internal owners;
uint256 internal ownerCount;
uint256 internal threshold;
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
function setupOwners(address[] memory _owners, uint256 _threshold) internal {
// Threshold can only be 0 at initialization.
// Check ensures that setup function can only be called once.
require(threshold == 0, "GS200");
// Validate that threshold is smaller than number of added owners.
require(_threshold <= _owners.length, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
// Initializing Safe owners.
address currentOwner = SENTINEL_OWNERS;
for (uint256 i = 0; i < _owners.length; i++) {
// Owner address cannot be null.
address owner = _owners[i];
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[currentOwner] = owner;
currentOwner = owner;
}
owners[currentOwner] = SENTINEL_OWNERS;
ownerCount = _owners.length;
threshold = _threshold;
}
/// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
/// @param owner New owner address.
/// @param _threshold New threshold.
function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[owner] = owners[SENTINEL_OWNERS];
owners[SENTINEL_OWNERS] = owner;
ownerCount++;
emit AddedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}
/// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
/// @param prevOwner Owner that pointed to the owner to be removed in the linked list
/// @param owner Owner address to be removed.
/// @param _threshold New threshold.
function removeOwner(
address prevOwner,
address owner,
uint256 _threshold
) public authorized {
// Only allow to remove an owner, if threshold can still be reached.
require(ownerCount - 1 >= _threshold, "GS201");
// Validate owner address and check that it corresponds to owner index.
require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == owner, "GS205");
owners[prevOwner] = owners[owner];
owners[owner] = address(0);
ownerCount--;
emit RemovedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}
/// @dev Allows to swap/replace an owner from the Safe with another address.
/// This can only be done via a Safe transaction.
/// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(
address prevOwner,
address oldOwner,
address newOwner
) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[newOwner] == address(0), "GS204");
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == oldOwner, "GS205");
owners[newOwner] = owners[oldOwner];
owners[prevOwner] = newOwner;
owners[oldOwner] = address(0);
emit RemovedOwner(oldOwner);
emit AddedOwner(newOwner);
}
/// @dev Allows to update the number of required confirmations by Safe owners.
/// This can only be done via a Safe transaction.
/// @notice Changes the threshold of the Safe to `_threshold`.
/// @param _threshold New threshold.
function changeThreshold(uint256 _threshold) public authorized {
// Validate that threshold is smaller than number of owners.
require(_threshold <= ownerCount, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
threshold = _threshold;
emit ChangedThreshold(threshold);
}
function getThreshold() public view returns (uint256) {
return threshold;
}
function isOwner(address owner) public view returns (bool) {
return owner != SENTINEL_OWNERS && owners[owner] != address(0);
}
/// @dev Returns array of owners.
/// @return Array of Safe owners.
function getOwners() public view returns (address[] memory) {
address[] memory array = new address[](ownerCount);
// populate return array
uint256 index = 0;
address currentOwner = owners[SENTINEL_OWNERS];
while (currentOwner != SENTINEL_OWNERS) {
array[index] = currentOwner;
currentOwner = owners[currentOwner];
index++;
}
return array;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
enum Operation {Call, DelegateCall}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
/// @author Richard Meissner - <[email protected]>
contract EtherPaymentFallback {
event SafeReceived(address indexed sender, uint256 value);
/// @dev Fallback function accepts Ether transactions.
receive() external payable {
emit SafeReceived(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SecuredTokenTransfer - Secure token transfer
/// @author Richard Meissner - <[email protected]>
contract SecuredTokenTransfer {
/// @dev Transfers a token and returns if it was a success
/// @param token Token that should be transferred
/// @param receiver Receiver to whom the token should be transferred
/// @param amount The amount of tokens that should be transferred
function transferToken(
address token,
address receiver,
uint256 amount
) internal returns (bool transferred) {
// 0xa9059cbb - keccack("transfer(address,uint256)")
bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
// solhint-disable-next-line no-inline-assembly
assembly {
// We write the return value to scratch space.
// See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
switch returndatasize()
case 0 {
transferred := success
}
case 0x20 {
transferred := iszero(or(iszero(success), iszero(mload(0))))
}
default {
transferred := 0
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SelfAuthorized - authorizes current contract to perform actions
/// @author Richard Meissner - <[email protected]>
contract SelfAuthorized {
function requireSelfCall() private view {
require(msg.sender == address(this), "GS031");
}
modifier authorized() {
// This is a function call as it minimized the bytecode size
requireSelfCall();
_;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SignatureDecoder - Decodes signatures that a encoded as bytes
/// @author Richard Meissner - <[email protected]>
contract SignatureDecoder {
/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
/// @notice Make sure to perform a bounds check for @param pos, to avoid out of bounds access on @param signatures
/// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
/// @param signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos)
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
// solhint-disable-next-line no-inline-assembly
assembly {
let signaturePos := mul(0x41, pos)
r := mload(add(signatures, add(signaturePos, 0x20)))
s := mload(add(signatures, add(signaturePos, 0x40)))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Singleton - Base for singleton contracts (should always be first super contract)
/// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
/// @author Richard Meissner - <[email protected]>
contract Singleton {
// singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
// It should also always be ensured that the address is stored alone (uses a full word)
address private singleton;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
/// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
contract StorageAccessible {
/**
* @dev Reads `length` bytes of storage in the currents contract
* @param offset - the offset in the current contract's storage in words to start reading from
* @param length - the number of words (32 bytes) of data to read
* @return the bytes that were read.
*/
function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
bytes memory result = new bytes(length * 32);
for (uint256 index = 0; index < length; index++) {
// solhint-disable-next-line no-inline-assembly
assembly {
let word := sload(add(offset, index))
mstore(add(add(result, 0x20), mul(index, 0x20)), word)
}
}
return result;
}
/**
* @dev Performs a delegatecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static).
*
* This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
* Specifically, the `returndata` after a call to this method will be:
* `success:bool || response.length:uint256 || response:bytes`.
*
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
// solhint-disable-next-line no-inline-assembly
assembly {
let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
mstore(0x00, success)
mstore(0x20, returndatasize())
returndatacopy(0x40, 0, returndatasize())
revert(0, add(returndatasize(), 0x40))
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
* @title GnosisSafeMath
* @dev Math operations with safety checks that revert on error
* Renamed from SafeMath to GnosisSafeMath to avoid conflicts
* TODO: remove once open zeppelin update to solc 0.5.0
*/
library GnosisSafeMath {
/**
* @dev Multiplies two numbers, 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 Subtracts two numbers, 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 numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
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: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
contract ISignatureValidatorConstants {
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
}
abstract contract ISignatureValidator is ISignatureValidatorConstants {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*
* MUST return the bytes4 magic value 0x20c13b0b when function passes.
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
} | Marks a hash as approved. This can be used to validate a hash that is used by a signature. hashToApprove The hash that should be marked as approved for signatures that are verified by this contract./ | function approveHash(bytes32 hashToApprove) external {
require(owners[msg.sender] != address(0), "GS030");
approvedHashes[msg.sender][hashToApprove] = 1;
emit ApproveHash(hashToApprove, msg.sender);
}
| 431,264 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./SigToken.sol";
/**
* @title FeeAdminV1DutchAuction
* @notice Sells admin fees from xsigma3pool for SigToken and burns it.
* Sell happens via Dutch Auction periodically from highest price to lowest one.
* Owner can change the auction settings.
*/
contract PeriodicDutchAuction is Ownable {
using SafeMath for uint256;
SigToken public sigToken;
address[] public coins;
/*
the price of the auction works like this:
from the block {startBlock} every {term} any of {coins} avaliable on balance
can be bought by Sig token using current sigPrice(currBlock).
the price(t) == a*t + b every term,
i.e. t = (currBlock - startBlock) % term,
so the highest price is b, and the lowest price is b - a*term
*/
uint256 public startBlock = 1e18; // INF at the beginning
uint256 public periodBlocks;
uint256 public a;
uint256 public b;
event SetSettings(
uint256 _startBlock,
uint256 _auctionPeriodBlocks,
uint256 _lowestSig1e18Price,
uint256 _highestSig1e18Price
);
event Bought(
address msg_sender,
uint256 sellSigAmount,
uint256 buyTokenId,
uint256 minBuyAmount,
uint256 outputAmount
);
constructor(
SigToken _sigToken,
address[3] memory _coins
) public {
sigToken = _sigToken;
for (uint256 i = 0; i < 3; i++) {
require(_coins[i] != address(0));
coins.push(_coins[i]);
}
}
/**
* @notice Set parameters for Dutch Auction as SigToken price.
* @param _startBlock - before this block number getPriceSig which revert
* @param _auctionPeriodBlocks - auction will happens every _term blocks from _startBlock
* @param _lowestSig1e18Price - start lowest price of Sig in usd,
* so if you want to start from 1 SigToken == 0.01 DAI,
* it should be 0.01*1e18.
* All stablecoins in the pool are considered worth of $1.
* @param _highestSig1e18Price - the last/highest SIG price on the auction
*/
function setAuctionSettings(
uint256 _startBlock,
uint256 _auctionPeriodBlocks,
uint256 _lowestSig1e18Price,
uint256 _highestSig1e18Price
) public onlyOwner {
startBlock = _startBlock;
periodBlocks = _auctionPeriodBlocks;
b = _lowestSig1e18Price;
a = _highestSig1e18Price.sub(_lowestSig1e18Price).div(periodBlocks.sub(1));
emit SetSettings(_startBlock, _auctionPeriodBlocks, _lowestSig1e18Price, _highestSig1e18Price);
}
/**
* @notice price for SIG token in USD * 1e18 at currBlock
*/
function getSig1e18Price(uint256 currBlock, uint256 tokenId) public view returns (uint256) {
require(startBlock <= currBlock, "Auction hasn't started yet");
uint256 t = (currBlock - startBlock) % periodBlocks;
uint256 price;
if (tokenId == 0) {
// i = 0 => DAI with 1e18 precision
price = b.add(a.mul(t));
} else {
// i = 1 || 2, => USDC/USDT with 1e6 precision
price = b.add(a.mul(t)).div(1e12);
}
return price;
}
/**
* @notice Try to exchange SIG token for one of stablecoins
* @param sellSigAmount - amount of SigToken
* @param buyTokenId - number of stablecoins, by default 0,1 or 2 for DAI, USDC or USDT
* @param buyAtLeastAmount - if there's not enough balance, buy at least specified amount of stablecoin
* if it's 0 - transaction will be reverted if there's no enough coins
*/
function sellSigForStablecoin(uint256 sellSigAmount, uint256 buyTokenId, uint256 buyAtLeastAmount) public {
// how much stablecoins should we give
uint256 sig1e18Price = getSig1e18Price(block.number, buyTokenId);
uint256 outputAmount = sellSigAmount.mul(sig1e18Price).div(1e18);
// maybe the contract has less stablecoins, but it's still enough to satisfy user request
if (IERC20(coins[buyTokenId]).balanceOf(address(this)) < outputAmount) {
//
if (buyAtLeastAmount == 0) {
revert("not enough stablecoins to buy");
}
// trying to buy as much as we can for current price
sellSigAmount = buyAtLeastAmount.mul(1e18).div(sig1e18Price);
outputAmount = buyAtLeastAmount;
}
// take Sig and burn
sigToken.burnFrom(msg.sender, sellSigAmount);
// return fee token
IERC20(coins[buyTokenId]).transfer(msg.sender, outputAmount);
emit Bought(msg.sender, sellSigAmount, buyTokenId, buyAtLeastAmount, outputAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// SushiToken with Governance.
contract SigToken is ERC20, Ownable, ERC20Burnable {
using SafeMath for uint256;
// Bitcoin-like supply system:
// 50 tokens per block (however it's Ethereum ~15 seconds block vs Bitcoin 10 minutes)
// every 210,000 blocks is halving ~ 36 days 11 hours
// 32 eras ~ 3 years 71 days 16 hours until complete mint
// 21,000,000 is total supply
//
// i,e. if each block is about 15 seconds on average:
// 40,320 blocks/week
// 2,016,000 tokens/week before first halving
// 10,500,000 total before first halving
//
uint256 constant MAX_MAIN_SUPPLY = 21_000_000 * 1e18;
// the first week mint has x2 bonus = +2,016,000
// the second week mint has x1.5 bonus = +1,008,000
//
uint256 constant BONUS_SUPPLY = 3_024_000 * 1e18;
// so total max supply is 24,024,000 + 24 to init the uniswap pool
uint256 constant MAX_TOTAL_SUPPLY = MAX_MAIN_SUPPLY + BONUS_SUPPLY;
// The block number when SIG mining starts.
uint256 public startBlock;
uint256 constant DECIMALS_MUL = 1e18;
uint256 constant BLOCKS_PER_WEEK = 40_320;
uint256 constant HALVING_BLOCKS = 210_000;
// uint265 constant INITIAL_BLOCK_REWARD = 50;
function maxRewardMintAfterBlocks(uint256 t) public pure returns (uint256) {
// the first week x2 mint
if (t < BLOCKS_PER_WEEK) {
return DECIMALS_MUL * 100 * t;
}
// second week x1.5 mint
if (t < BLOCKS_PER_WEEK * 2) {
return DECIMALS_MUL * (100 * BLOCKS_PER_WEEK + 75 * (t - BLOCKS_PER_WEEK));
}
// after two weeks standard bitcoin issuance model https://en.bitcoin.it/wiki/Controlled_supply
uint256 totalBonus = DECIMALS_MUL * (BLOCKS_PER_WEEK * 50 + BLOCKS_PER_WEEK * 25);
assert(totalBonus >= 0);
// how many halvings so far?
uint256 era = t / HALVING_BLOCKS;
assert(0 <= era);
if (32 <= era) return MAX_TOTAL_SUPPLY;
// total reward before current era (mul base reward 50)
// sum : 1 + 1/2 + 1/4 … 1/2^n == 2 - 1/2^n == 1 - 1/1<<n == 1 - 1>>n
// era reward per block (*1e18 *50)
if (era == 0) {
return totalBonus + DECIMALS_MUL* 50 * (t % HALVING_BLOCKS);
}
uint256 eraRewardPerBlock = (DECIMALS_MUL >> era);
// assert(0 <= eraRewardPerBlock);
uint256 bcReward = (DECIMALS_MUL + DECIMALS_MUL - (eraRewardPerBlock<<1) ) * 50 * HALVING_BLOCKS;
// assert(0 <= bcReward);
// reward in the last era which isn't over
uint256 eraReward = eraRewardPerBlock * 50 * (t % HALVING_BLOCKS);
// assert(0 <= eraReward);
uint256 result = totalBonus + bcReward + eraReward;
assert(0 <= result);
return result;
}
constructor(
uint256 _tinyMint
) public ERC20("xSigma", "SIG") {
// dev needs a little of SIG tokens for uniswap SIG/ETH initialization
_mint(msg.sender, _tinyMint);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SIG::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SIG::delegateBySig: invalid nonce");
require(now <= expiry, "SIG::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SIG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SIGs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "SIG::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// 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 "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: 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 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.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// 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);
} | Try to exchange SIG token for one of stablecoins sellSigAmount - amount of SigToken buyTokenId - number of stablecoins, by default 0,1 or 2 for DAI, USDC or USDT buyAtLeastAmount - if there's not enough balance, buy at least specified amount of stablecoin if it's 0 - transaction will be reverted if there's no enough coins/ how much stablecoins should we give maybe the contract has less stablecoins, but it's still enough to satisfy user request | function sellSigForStablecoin(uint256 sellSigAmount, uint256 buyTokenId, uint256 buyAtLeastAmount) public {
uint256 sig1e18Price = getSig1e18Price(block.number, buyTokenId);
uint256 outputAmount = sellSigAmount.mul(sig1e18Price).div(1e18);
if (IERC20(coins[buyTokenId]).balanceOf(address(this)) < outputAmount) {
if (buyAtLeastAmount == 0) {
revert("not enough stablecoins to buy");
}
outputAmount = buyAtLeastAmount;
}
emit Bought(msg.sender, sellSigAmount, buyTokenId, buyAtLeastAmount, outputAmount);
}
| 573,097 |
./full_match/80001/0xb897aeC5F100C906B859D7f1D307DdBeDE002F2A/sources/project_/contracts/NFTMarketPlace.sol | transferOwner payable(owner).transfer(); removed becuase we need to remove the fees from frontend | function transferOwner(
address nftContract,
address receiverAddress,
uint256 nftItemId
) public payable nonReentrant {
uint256 tokenId = idForMarketItem[nftItemId].tokenId;
IERC721(nftContract).transferFrom(
address(this),
receiverAddress,
tokenId
idForMarketItem[nftItemId].owner = payable(receiverAddress);
idForMarketItem[nftItemId].sold = true;
itemsSold.increment();
}
| 5,575,803 |
// SPDX-License-Identifier: MIT License
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module which provides access control
*
* the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* mapped to
* `onlyOwner`
*/
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);
}
}
contract CryptoPhunksMarket is ReentrancyGuard, Pausable, Ownable {
IERC721 phunksContract; // instance of the CryptoPhunks contract
struct Offer {
bool isForSale;
uint phunkIndex;
address seller;
uint minValue; // in ether
address onlySellTo;
}
struct Bid {
bool hasBid;
uint phunkIndex;
address bidder;
uint value;
}
// A record of phunks that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping (uint => Offer) public phunksOfferedForSale;
// A record of the highest phunk bid
mapping (uint => Bid) public phunkBids;
// A record of pending ETH withdrawls by address
mapping (address => uint) public pendingWithdrawals;
event PhunkOffered(uint indexed phunkIndex, uint minValue, address indexed toAddress);
event PhunkBidEntered(uint indexed phunkIndex, uint value, address indexed fromAddress);
event PhunkBidWithdrawn(uint indexed phunkIndex, uint value, address indexed fromAddress);
event PhunkBought(uint indexed phunkIndex, uint value, address indexed fromAddress, address indexed toAddress);
event PhunkNoLongerForSale(uint indexed phunkIndex);
/* Initializes contract with an instance of CryptoPhunks contract, and sets deployer as owner */
constructor(address initialPhunksAddress) {
IERC721(initialPhunksAddress).balanceOf(address(this));
phunksContract = IERC721(initialPhunksAddress);
}
function pause() public whenNotPaused onlyOwner {
_pause();
}
function unpause() public whenPaused onlyOwner {
_unpause();
}
/* Returns the CryptoPhunks contract address currently being used */
function phunksAddress() public view returns (address) {
return address(phunksContract);
}
/* Allows the owner of the contract to set a new CryptoPhunks contract address */
function setPhunksContract(address newPhunksAddress) public onlyOwner {
phunksContract = IERC721(newPhunksAddress);
}
/* Allows the owner of a CryptoPhunks to stop offering it for sale */
function phunkNoLongerForSale(uint phunkIndex) public nonReentrant() {
if (phunkIndex >= 10000) revert('token index not valid');
if (phunksContract.ownerOf(phunkIndex) != msg.sender) revert('you are not the owner of this token');
phunksOfferedForSale[phunkIndex] = Offer(false, phunkIndex, msg.sender, 0, address(0x0));
emit PhunkNoLongerForSale(phunkIndex);
}
/* Allows a CryptoPhunk owner to offer it for sale */
function offerPhunkForSale(uint phunkIndex, uint minSalePriceInWei) public whenNotPaused nonReentrant() {
if (phunkIndex >= 10000) revert('token index not valid');
if (phunksContract.ownerOf(phunkIndex) != msg.sender) revert('you are not the owner of this token');
phunksOfferedForSale[phunkIndex] = Offer(true, phunkIndex, msg.sender, minSalePriceInWei, address(0x0));
emit PhunkOffered(phunkIndex, minSalePriceInWei, address(0x0));
}
/* Allows a CryptoPhunk owner to offer it for sale to a specific address */
function offerPhunkForSaleToAddress(uint phunkIndex, uint minSalePriceInWei, address toAddress) public whenNotPaused nonReentrant() {
if (phunkIndex >= 10000) revert();
if (phunksContract.ownerOf(phunkIndex) != msg.sender) revert('you are not the owner of this token');
phunksOfferedForSale[phunkIndex] = Offer(true, phunkIndex, msg.sender, minSalePriceInWei, toAddress);
emit PhunkOffered(phunkIndex, minSalePriceInWei, toAddress);
}
/* Allows users to buy a CryptoPhunk offered for sale */
function buyPhunk(uint phunkIndex) payable public whenNotPaused nonReentrant() {
if (phunkIndex >= 10000) revert('token index not valid');
Offer memory offer = phunksOfferedForSale[phunkIndex];
if (!offer.isForSale) revert('phunk is not for sale'); // phunk not actually for sale
if (offer.onlySellTo != address(0x0) && offer.onlySellTo != msg.sender) revert();
if (msg.value != offer.minValue) revert('not enough ether'); // Didn't send enough ETH
address seller = offer.seller;
if (seller == msg.sender) revert('seller == msg.sender');
if (seller != phunksContract.ownerOf(phunkIndex)) revert('seller no longer owner of phunk'); // Seller no longer owner of phunk
phunksOfferedForSale[phunkIndex] = Offer(false, phunkIndex, msg.sender, 0, address(0x0));
phunksContract.safeTransferFrom(seller, msg.sender, phunkIndex);
pendingWithdrawals[seller] += msg.value;
emit PhunkBought(phunkIndex, msg.value, seller, msg.sender);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid memory bid = phunkBids[phunkIndex];
if (bid.bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += bid.value;
phunkBids[phunkIndex] = Bid(false, phunkIndex, address(0x0), 0);
}
}
/* Allows users to retrieve ETH from sales */
function withdraw() public nonReentrant() {
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
/* Allows users to enter bids for any CryptoPhunk */
function enterBidForPhunk(uint phunkIndex) payable public whenNotPaused nonReentrant() {
if (phunkIndex >= 10000) revert('token index not valid');
if (phunksContract.ownerOf(phunkIndex) == msg.sender) revert('you already own this phunk');
if (msg.value == 0) revert('cannot enter bid of zero');
Bid memory existing = phunkBids[phunkIndex];
if (msg.value <= existing.value) revert('your bid is too low');
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
phunkBids[phunkIndex] = Bid(true, phunkIndex, msg.sender, msg.value);
emit PhunkBidEntered(phunkIndex, msg.value, msg.sender);
}
/* Allows CryptoPhunk owners to accept bids for their Phunks */
function acceptBidForPhunk(uint phunkIndex, uint minPrice) public whenNotPaused nonReentrant() {
if (phunkIndex >= 10000) revert('token index not valid');
if (phunksContract.ownerOf(phunkIndex) != msg.sender) revert('you do not own this token');
address seller = msg.sender;
Bid memory bid = phunkBids[phunkIndex];
if (bid.value == 0) revert('cannot enter bid of zero');
if (bid.value < minPrice) revert('your bid is too low');
address bidder = bid.bidder;
if (seller == bidder) revert('you already own this token');
phunksOfferedForSale[phunkIndex] = Offer(false, phunkIndex, bidder, 0, address(0x0));
uint amount = bid.value;
phunkBids[phunkIndex] = Bid(false, phunkIndex, address(0x0), 0);
phunksContract.safeTransferFrom(msg.sender, bidder, phunkIndex);
pendingWithdrawals[seller] += amount;
emit PhunkBought(phunkIndex, bid.value, seller, bidder);
}
/* Allows bidders to withdraw their bids */
function withdrawBidForPhunk(uint phunkIndex) public nonReentrant() {
if (phunkIndex >= 10000) revert('token index not valid');
Bid memory bid = phunkBids[phunkIndex];
if (bid.bidder != msg.sender) revert('the bidder is not message sender');
emit PhunkBidWithdrawn(phunkIndex, bid.value, msg.sender);
uint amount = bid.value;
phunkBids[phunkIndex] = Bid(false, phunkIndex, address(0x0), 0);
// Refund the bid money
payable(msg.sender).transfer(amount);
}
}
// 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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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 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);
}
| Allows a CryptoPhunk owner to offer it for sale to a specific address / | function offerPhunkForSaleToAddress(uint phunkIndex, uint minSalePriceInWei, address toAddress) public whenNotPaused nonReentrant() {
if (phunkIndex >= 10000) revert();
if (phunksContract.ownerOf(phunkIndex) != msg.sender) revert('you are not the owner of this token');
phunksOfferedForSale[phunkIndex] = Offer(true, phunkIndex, msg.sender, minSalePriceInWei, toAddress);
emit PhunkOffered(phunkIndex, minSalePriceInWei, toAddress);
}
| 15,795,821 |
./partial_match/3/0xc7920b800569AC8895e1a0bA3869B6ddF56717e3/sources/PoR.sol | Extracts the value from the output in a tx Value is an 8-byte little-endian number _output The output return The output value | function extractValue(bytes memory _output) internal pure returns (uint64) {
bytes memory _leValue = extractValueLE(_output);
bytes memory _beValue = reverseEndianness(_leValue);
return uint64(bytesToUint(_beValue));
}
| 5,220,564 |
./full_match/1/0x29F933645F8086719236825A28d04D8A055D98dB/sources/_arbitrum/token-bridge-contracts/contracts/tokenbridge/ethereum/gateway/L1ArbitrumGateway.sol | Only excess gas is refunded to the _refundTo account, l2 call value is always returned to the _to account/ We make this function virtual since outboundTransfer logic is the same for many gateways but sometimes (ie weth) you construct the outgoing message differently. msg.value is sent, but 0 is set to the L2 call value the eth sent is used to pay for the tx's gas | function createOutboundTxCustomRefund(
address _refundTo,
address _from,
uint256, /* _tokenAmount */
uint256 _maxGas,
uint256 _gasPriceBid,
uint256 _maxSubmissionCost,
bytes memory _outboundCalldata
) internal virtual returns (uint256) {
return
sendTxToL2CustomRefund(
inbox,
counterpartGateway,
_refundTo,
_from,
L2GasParams({
_maxSubmissionCost: _maxSubmissionCost,
_maxGas: _maxGas,
_gasPriceBid: _gasPriceBid
}),
_outboundCalldata
);
}
| 8,380,376 |
./full_match/4/0xb8dE86fEF02D3b5225DC71b3Ddc8ec01c0711853/sources/contracts/HauntooBreeding.sol | Internal check to see if a given sire and matron are a valid mating pair for breeding via auction (i.e. skips ownership and siring approval checks). | function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Hauntoo storage matron = hauntoos[_matronId];
Hauntoo storage sire = hauntoos[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
| 12,509,906 |
./full_match/1/0xE0fC587E1F56b5968a7d5DC3667bA1f385fddb38/sources/contracts/TermRepoToken.sol | Calculates the total USD redemption value of all outstanding TermRepoTokens return totalRedemptionValue The total redemption value of TermRepoTokens in USD | function totalRedemptionValue() external view returns (uint256) {
uint256 totalValue = truncate(
mul_(
)
);
return totalValue;
}
| 9,687,058 |
/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
/// @title DeSo
/// @notice SocialMedia content creation and voting
/// @dev This contract keeps track of all the posts created by registered users
contract SocialMedia is Initializable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _idCounter;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
uint private downVoteThreshold;
uint private numberOfExcuses;
uint private suspensionPeriod;
struct Post {
uint id;
uint createDate;
bool visible;
address creator;
string description;
string content;
}
struct Vote {
uint postId;
uint upVote;
uint downVote;
}
struct Violation {
uint[] postIds;
uint count;
address postCreator;
}
Post[] private posts;
mapping(uint => Post) postById;
mapping(address => Post[]) userPosts;
mapping(uint => Vote) voteMap;
mapping(address => Violation) postViolation;
/// @notice Emitted when the new post is created
/// @param postId The unique identifier of post
/// @param createDate The date of post creation
/// @param creator The address of post creator
/// @param description The description of the post
/// @param contentUri The IPFS content uri
event PostAdded(
uint indexed postId,
uint indexed createDate,
address indexed creator,
string description,
string contentUri
);
/// @notice Emitted when any post is voted
/// @param postId The unique identifier of post
/// @param upVote The kind of vote, true = upVote, false = downVote
/// @param voter The address of the voter
event PostVote(
uint indexed postId,
bool upVote,
address indexed voter
);
/// @notice Emitted when any post is reported for violation
/// @param postIds The post ids that are considered violated
/// @param count The counter tracking the number of violations by user
/// @param suspensionDays The number of days user is suspended
/// @param banned The flag represents if the user is banned
/// @param postCreator The address of the post(s) creator
event PostViolation(
uint[] postIds,
uint indexed count,
uint suspensionDays,
bool banned,
address indexed postCreator
);
/// @notice The starting point of the contract, which defines the initial values
/// @dev This is an upgradeable contract, DO NOT have constructor, and use this function for
/// initialization of this and inheriting contracts
function initialize()
initializer
public
{
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
_setupRole(UPGRADER_ROLE, msg.sender);
downVoteThreshold = 5;
numberOfExcuses = 1;
suspensionPeriod = 7;
}
/// @inheritdoc UUPSUpgradeable
/// @dev The contract upgrade authorization handler. Only the users with role 'UPGRADER_ROLE' are allowed to upgrade the contract
/// @param newImplementation The address of the new implementation contract
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
/// @notice Called by owner to pause, transitons the contract to stopped state
/// @dev This function can be accessed by the user with role PAUSER_ROLE
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
/// @notice Called by owner to unpause, transitons the contract back to normal state
/// @dev This function can be accessed by the user with role PAUSER_ROLE
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
/// @notice Function to get the down vote theshold
function getDownVoteThreshold()
view
public
returns (uint)
{
return downVoteThreshold;
}
/// @notice Function to set down vote threshold
/// @dev This function can be accessed by the user with role ADMIN
function setDownVoteThreshold(uint _limit)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
downVoteThreshold = _limit;
}
/// @notice Function to get the number of excuses before the user is permanently banned
function getNumberOfExcuses()
view
public
returns (uint)
{
return numberOfExcuses;
}
/// @notice Function to set number of excuses for post violations
/// @dev This function can be accessed by the user with role ADMIN
function setNumberOfExcuses(uint _excuses)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
numberOfExcuses = _excuses;
}
/// @notice Function to get the suspension period for user incase of violation
function getSuspensionPeriod()
view
public
returns (uint)
{
return suspensionPeriod;
}
/// @notice Function to set the suspension period in days for each post violation
/// @dev This function can be accessed by the user with role ADMIN
function setSuspensionPeriod(uint _duration)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
suspensionPeriod = _duration;
}
/// @dev Post mappings to maintain
function postOperations(Post memory post)
internal
{
posts.push(post);
userPosts[msg.sender].push(post);
postById[post.id] = post;
}
/// @dev Increment and get the counter, which is used as the unique identifier for post
/// @return The unique identifier
function incrementAndGet()
internal
returns (uint)
{
_idCounter.increment();
return _idCounter.current();
}
/// @notice Create a post with any multimedia and description. The multimedia should be stored in external storage and the record pointer to be used
/// @dev Require a valid and not empty multimedia uri pointer. Emits PostAdded event.
/// @param _description The description of the uploaded multimedia
/// @param _contentUri The uri of the multimedia record captured in external storage
function createPost(string memory _description, string memory _contentUri)
external
{
require(bytes(_contentUri).length > 0, "Empty content uri");
uint postId = incrementAndGet();
Post memory post = Post(postId, block.timestamp, true, msg.sender, _description, _contentUri);
postOperations(post);
emit PostAdded(postId, block.timestamp, msg.sender, _description, _contentUri);
}
/// @notice Fetch the post record by its unique identifier
/// @param _id The unique identifier of the post
/// @return The post record
function getPostById(uint _id)
view
external
returns(Post memory)
{
return postById[_id];
}
/// @notice Fetch all the post records created by user
/// @param _user The address of the user to fetch the post records
/// @return The list of post records
function getPostsByUser(address _user)
view
external
returns(Post[] memory)
{
return userPosts[_user];
}
/// @notice Fetch all the posts created accross users
/// @return The list of post records
function getAllPosts()
view
external
returns (Post[] memory)
{
return posts;
}
/// @notice Right to up vote or down vote any posts.
/// @dev The storage vote instance is matched on identifier and updated with the vote. Emits PostVote event
/// @param _postId The unique identifier of post
/// @param _upVote True to upVote, false to downVote
function vote(uint _postId, bool _upVote)
external
{
Vote storage voteInstance = voteMap[_postId];
voteInstance.postId = _postId;
if(_upVote)
voteInstance.upVote += 1;
else
voteInstance.downVote += 1;
emit PostVote(_postId, _upVote, msg.sender);
}
/// @notice Function to get the vote details by post ID
/// @param _postId Unique identifier of the post
/// @return The post's voting information
function getVoteByPostId(uint _postId)
view
external
returns (Vote memory)
{
return voteMap[_postId];
}
/// @notice Function to get the violation report of a post
/// @param _postId Unique identifier of the post
/// @return The post violation report
function getPostViolation(uint _postId)
view
external
returns (Violation memory)
{
return postViolation[postById[_postId].creator];
}
/// @notice Function to report the post violation
/// @dev Require a valid post ID and the number of down votes should be equal or exceeds the threshold
/// @param _postId Unique identifier of the post
/// @return suspensionDays The number of days user is suspended for the violation
/// @return ban If true, user is permanently banned from the application
function reportPostViolation(uint _postId)
external
returns (uint suspensionDays, bool ban)
{
Post memory post = postById[_postId];
require(post.id == _postId, "Check the post ID");
Vote memory postVote = voteMap[_postId];
require(postVote.downVote >= downVoteThreshold, "Can not take down the post");
Violation storage violation = postViolation[post.creator];
violation.postIds.push(_postId);
violation.count += 1;
violation.postCreator = post.creator;
post.visible = false;
postOperations(post);
if (violation.count <= numberOfExcuses) {
emit PostViolation(violation.postIds, violation.count, suspensionPeriod, false, violation.postCreator);
return (suspensionPeriod, false);
} else {
// ban the user permanently from application
// TODO add the user address to blacklist data structure
emit PostViolation(violation.postIds, violation.count, 0, true, violation.postCreator);
return (0, true);
}
}
} | The starting point of the contract, which defines the initial values This is an upgradeable contract, DO NOT have constructor, and use this function for initialization of this and inheriting contracts | function initialize()
initializer
public
{
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
_setupRole(UPGRADER_ROLE, msg.sender);
downVoteThreshold = 5;
numberOfExcuses = 1;
suspensionPeriod = 7;
}
| 7,267,473 |
./full_match/56/0xa83B3E821F6CF63Cde35c9aC7012c00bF57a438D/sources/contracts/NewAlver.sol | Disable the GREED mode | function disableGREED() external authorized {
GREEDTriggeredAt = 0;
}
| 3,245,854 |
pragma solidity ^0.4.24;
import "./Asset.sol";
import "./Events.sol";
contract StakeInterface {
function calculateStakeTokens(uint _itemCost) public returns (uint _stakeToken);
}
contract TokenInterface {
function transferFrom(address _from, address _to, uint _value) public returns (bool);
function balanceOf(address _wallet) public returns (uint);
}
contract ArbitratorInterface {
function createArbitration(string _reason, address _requesdedBy) public returns (address);
}
contract SplytTracker is Events {
uint public version;
string public ownedBy;
address public satToken;
address public arbitrator;
address public stake;
mapping (address => bytes12) assetIdByAddress;
mapping (bytes32 => address) addressByassetId;
// Events to notify other market places of something
// Success events gets triggered when a listing is created or a listing is fully funded
// _code: 1 = listing created, 2 = contributions came in
// _assetAddress: the asset address for which the code happened
// event Success(uint _code, address _assetAddress);
// event Error(uint _code, string _message);
constructor(uint _version, string _ownedBy, address _satToken, address _arbitratorAddr, address _stake) public {
version = _version;
ownedBy = _ownedBy;
satToken = _satToken;
arbitrator = _arbitratorAddr;
stake = _stake;
}
// Setter functions. creates new asset contract given the parameters
function createAsset(
bytes12 _assetId,
uint _term,
address _seller,
string _title,
uint _totalCost,
uint _exiprationDate,
address _mpAddress,
uint _mpAmount)
public {
StakeInterface stakeContract = StakeInterface(stake);
uint sellersBal = getBalance(_seller);
uint stakeTokens = stakeContract.calculateStakeTokens(_totalCost);
if(stakeTokens > sellersBal) {
revert();
}
address newAsset = new Asset(_assetId, _term, _seller, _title, _totalCost, _exiprationDate, _mpAddress, _mpAmount, stakeTokens);
assetIdByAddress[newAsset] = _assetId;
addressByassetId[_assetId] = newAsset;
internalContribute(_seller, newAsset, stakeTokens);
emit Success(1, newAsset);
}
// Getter function. returns asset contract address given asset UUID
function getAddressById(bytes12 _listingId) public view returns (address) {
return addressByassetId[_listingId];
}
// Getter function. returns asset's UUID given asset's contract address
function getIdByAddress(address _contractAddr) public view returns (bytes12) {
return assetIdByAddress[_contractAddr];
}
// User for single buy to transfer tokens from buyer address to seller address
function internalContribute(address _from, address _to, uint _amount) public returns (bool) {
if(assetIdByAddress[msg.sender] == "0x0")
return false;
TokenInterface tokenContract = TokenInterface(satToken);
bool result = tokenContract.transferFrom(_from, _to, _amount);
if(result == true)
emit Success(2, msg.sender);
else
emit Error(2, msg.sender, "Could not make transfer happen");
return result;
}
// Used for fractional ownership to transfer tokens from user address to listing address
function internalRedeemFunds(address _listingAddress, address _seller, uint _amount) public returns (bool) {
if(assetIdByAddress[msg.sender] == "0x0") {
emit Error(1, msg.sender, "Asset contract not in splyt tracker");
return false;
}
TokenInterface tokenContract = TokenInterface(satToken);
bool result = tokenContract.transferFrom(_listingAddress, _seller, _amount);
if(result == true)
emit Success(2, msg.sender);
else
emit Error(2, msg.sender, "Could not make transfer happen");
return result;
}
function internalArbitrate(string _reason, address _requestedBy) public returns (address) {
ArbitratorInterface arbitratorContract = ArbitratorInterface(arbitrator);
address arbCont = arbitratorContract.createArbitration(_reason, _requestedBy);
emit Success(3, _requestedBy);
return arbCont;
}
// Getter function. returns token contract address
function getBalance(address _wallet) public returns (uint) {
TokenInterface tokenContract = TokenInterface(satToken);
return tokenContract.balanceOf(_wallet);
}
} | Getter function. returns token contract address | function getBalance(address _wallet) public returns (uint) {
TokenInterface tokenContract = TokenInterface(satToken);
return tokenContract.balanceOf(_wallet);
}
| 2,565,415 |
./full_match/4/0x29d932Ccd887860f8f29c15fD7f09D5Bd82080e8/sources/util/ABDKMath64x64.sol | Calculate x - y. Revert on overflow. x signed 64.64-bit fixed point number 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);
}
}
| 717,074 |
pragma solidity >=0.5.10;
import "ROOT/0x/utils/contracts/src/LibSafeMath.sol";
library LibFractions {
using LibSafeMath for uint256;
/// @dev Safely adds two fractions `n1/d1 + n2/d2`
/// @param n1 numerator of `1`
/// @param d1 denominator of `1`
/// @param n2 numerator of `2`
/// @param d2 denominator of `2`
/// @return numerator Numerator of sum
/// @return denominator Denominator of sum
function add(
uint256 n1,
uint256 d1,
uint256 n2,
uint256 d2
)
internal
pure
returns (
uint256 numerator,
uint256 denominator
)
{
if (n1 == 0) {
return (numerator = n2, denominator = d2);
}
if (n2 == 0) {
return (numerator = n1, denominator = d1);
}
numerator = n1
.safeMul(d2)
.safeAdd(n2.safeMul(d1));
denominator = d1.safeMul(d2);
return (numerator, denominator);
}
/// @dev Rescales a fraction to prevent overflows during addition if either
/// the numerator or the denominator are > `maxValue`.
/// @param numerator The numerator.
/// @param denominator The denominator.
/// @param maxValue The maximum value allowed for both the numerator and
/// denominator.
/// @return scaledNumerator The rescaled numerator.
/// @return scaledDenominator The rescaled denominator.
function normalize(
uint256 numerator,
uint256 denominator,
uint256 maxValue
)
internal
pure
returns (
uint256 scaledNumerator,
uint256 scaledDenominator
)
{
// If either the numerator or the denominator are > `maxValue`,
// re-scale them by `maxValue` to prevent overflows in future operations.
if (numerator > maxValue || denominator > maxValue) {
uint256 rescaleBase = numerator >= denominator ? numerator : denominator;
rescaleBase = rescaleBase.safeDiv(maxValue);
scaledNumerator = numerator.safeDiv(rescaleBase);
scaledDenominator = denominator.safeDiv(rescaleBase);
} else {
scaledNumerator = numerator;
scaledDenominator = denominator;
}
return (scaledNumerator, scaledDenominator);
}
/// @dev Rescales a fraction to prevent overflows during addition if either
/// the numerator or the denominator are > 2 ** 127.
/// @param numerator The numerator.
/// @param denominator The denominator.
/// @return scaledNumerator The rescaled numerator.
/// @return scaledDenominator The rescaled denominator.
function normalize(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (
uint256 scaledNumerator,
uint256 scaledDenominator
)
{
return normalize(numerator, denominator, 2 ** 127);
}
/// @dev Safely scales the difference between two fractions.
/// @param n1 numerator of `1`
/// @param d1 denominator of `1`
/// @param n2 numerator of `2`
/// @param d2 denominator of `2`
/// @param s scalar to multiply by difference.
/// @return result `s * (n1/d1 - n2/d2)`.
function scaleDifference(
uint256 n1,
uint256 d1,
uint256 n2,
uint256 d2,
uint256 s
)
internal
pure
returns (uint256 result)
{
if (s == 0) {
return 0;
}
if (n2 == 0) {
return result = s
.safeMul(n1)
.safeDiv(d1);
}
uint256 numerator = n1
.safeMul(d2)
.safeSub(n2.safeMul(d1));
uint256 tmp = numerator.safeDiv(d2);
return s
.safeMul(tmp)
.safeDiv(d1);
}
}
| Rescales a fraction to prevent overflows during addition if either the numerator or the denominator are > 2 127. numerator The numerator. denominator The denominator. return scaledNumerator The rescaled numerator. return scaledDenominator The rescaled denominator. | function normalize(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (
uint256 scaledNumerator,
uint256 scaledDenominator
)
{
return normalize(numerator, denominator, 2 ** 127);
}
| 1,041,018 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './Roc.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import './Randomize.sol';
import './Trignometry.sol';
/**
* @title RocRenderer
* @notice Renderer for roc-male-gen0
* @author Tfs128.eth (@trickerfs128)
*/
contract RocRenderer {
using Strings for uint256;
using Strings for uint16;
using Strings for uint8;
using Randomize for Randomize.Random;
Roc public immutable rocContract;
address public immutable pathsContractAddress;
/**
* @notice constructor
* @param pathsAddress - address of contract which contains paths.
* @param rocMainContractAddress - Roc Main contract address
*/
constructor(address pathsAddress, address rocMainContractAddress) {
pathsContractAddress = pathsAddress;
rocContract = Roc(rocMainContractAddress);
}
struct Info {
uint8 facePoints;
uint8 hat;
uint8 glasses;
uint8 moustache;
uint8 race;
}
/**
* @notice render the svg.
* @param tokenId - tokenId
* @param dna - dna
* @return json
*/
function render(uint256 tokenId, uint256 dna)
public
view
returns (string memory)
{
Randomize.Random memory random = Randomize.Random({seed: dna,nonce: 0});
Info memory info = Info({
facePoints: uint8(random.next(4, 40)),
hat: uint8(random.next(1,8)), //≈62%
glasses: uint8(random.next(1,10)), //10%
moustache: uint8(random.next(1,9)), //≈%33
race: uint8(random.next(1,4)) //Fency 25% Normal 75%;
});
uint16[] memory charAttributes = _getAttributesValues(info);
bytes memory svg = _getSvg(info,random,charAttributes);
bytes memory metaData = _getMetaData(info,charAttributes,rocContract._child_rem(tokenId));
bytes memory json = abi.encodePacked(
'data:application/json;utf8,{"name":"ROC #',
tokenId.toString(),
'","image":"data:image/svg+xml;utf8,',
svg,
'","description":"Rebels On Chain - Male Gen-0","attributes":[',
metaData,
']}'
);
return string(json);
}
/**
* @notice getSvg
*/
function _getSvg(
Info memory info,
Randomize.Random memory random,
uint16[] memory charAttributes
)
internal
view
returns (bytes memory)
{
uint256 clrHue = random.next(1,360);
bytes memory facePath = _getFacePath(info,random);
bytes memory background = _getBackground(random,info.race);
(bytes memory face, bytes memory defs) = _getFaceAndDefs(random,info.race,facePath);
bytes memory mouth = _getMouth(random.next(1,4));
bytes memory hat;
bytes memory glasses;
bytes memory moustache;
bytes memory eyes;
bytes memory attributesSvg;
if(info.hat < 6) {
hat = _extractWearable(info.hat,clrHue);
}
if(info.moustache > 6) {
moustache = _extractWearable(info.moustache,clrHue);
}
if(info.glasses == 6) {
glasses = _extractWearable(info.glasses,clrHue);
}
else {
eyes = _getEyes(random);
}
attributesSvg = _getCharAttributesSvg(charAttributes);
bytes memory svg = abi.encodePacked(
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 200 200'>",
background,
face,
eyes,
mouth,
moustache,
glasses,
hat,
attributesSvg,
defs,
"</svg>"
);
return svg;
}
/**
* @notice get path of svg layer stores in a seperate
* @notice contract.
*/
function _extractWearable(uint8 index,uint256 clrHue)
internal
view
returns(bytes memory)
{
bytes memory layer;
uint24[3][] memory pathsInfo = _getPathsInfo(index);
for(uint8 i = 0; i < pathsInfo.length; i++) {
uint24 offset = pathsInfo[i][0];
uint24 size = pathsInfo[i][1];
bytes memory path_ = new bytes(size);
address contractAddress = pathsContractAddress;
assembly {
extcodecopy(contractAddress, add(path_, 32), offset, size)
}
bytes memory clr;
uint16 clr1Sat = (index == 6) ? 75 : 100;
uint16 clr1Ligth = (index == 6) ? 40 : 55;
if(pathsInfo[i][2] == 0x000000) {
clr = abi.encodePacked('hsl(',clrHue.toString(),' ',clr1Sat.toString(),'% ',clr1Ligth.toString(),'%)');
}
else if(pathsInfo[i][2] == 0xffffff) {
clr = abi.encodePacked('hsl(',clrHue.toString(),' 78% 50%)');
}
else {
clr = abi.encodePacked('#',_bytes3ToHexBytes(bytes3(pathsInfo[i][2])));
}
if(index == 5 && i == 0) {
layer = abi.encodePacked(layer,"<path fill='",clr,"' stroke='black' d='",path_,"' />");
}
else {
layer = abi.encodePacked(
layer,"<path fill='",clr,"' d='",path_,"' />");
}
}
bytes memory transform = (index > 1 && index < 6) ? bytes('5') : bytes('0');
layer = abi.encodePacked(
"<g transform='matrix(1,0,0,1,0,",
transform,
")'>",
layer,
"</g>"
);
return layer;
}
/**
* @notice getMetaData
*/
function _getMetaData(
Info memory info,
uint16[] memory charAttributes,
uint256 childRemaining
)
internal
pure
returns(bytes memory metadata) {
string[10] memory names = ['Null','Derby','Beret','Trilby','Witch','Cowboy','Yes','Chevron','Pencil','HandleBar'];
string memory hatName;
string memory glassesName;
string memory moustacheName;
string memory raceName;
hatName = info.hat < 6 ? names[info.hat]: 'No';
glassesName = (info.glasses == 6) ? names[info.glasses] : 'No';
moustacheName = info.moustache > 6 ? names[info.moustache] : 'No';
raceName = info.race == 4 ? 'Fency' : 'Normal';
bytes memory scoreMeta;
{
scoreMeta = abi.encodePacked(
'{"trait_type": "Strength", "value": ',
charAttributes[0].toString(),
'},{"trait_type": "Knowledge", "value": ',
charAttributes[1].toString(),
'},{"trait_type": "Charm", "value": ',
charAttributes[2].toString(),
'},{"trait_type": "Money", "value": ',
charAttributes[3].toString(),
'}'
);
}
metadata = abi.encodePacked(
'{"trait_type": "Childs Remaining", "value": "',
childRemaining.toString(),
'"},{"trait_type": "Hat", "value": "',
hatName,
'"},{"trait_type": "Glasses", "value": "',
glassesName,
'"},{"trait_type": "Moustache", "value": "',
moustacheName,
'"},{"trait_type": "Race", "value": "',
raceName,
'"},{"trait_type": "FacePoints", "value": "',
info.facePoints.toString(),
'"},',
scoreMeta
);
}
/**
* @notice calculate character attributes
*/
function _getAttributesValues(Info memory info)
internal
pure
returns (uint16[] memory)
{
uint16 initialPoints = info.facePoints / 2;
//Set initial score based on facepoints.
uint16 knowledge = (20 + initialPoints);
uint16 strength = (20 + initialPoints);
uint16 charm = (40 - initialPoints);
//if race == fency add charm and strength.
if(info.race == 4) {
strength += 5;
charm += 5;
}
//if hat, add knowledge
if(info.hat < 6) {
knowledge += 10;
}
//if glasses, add charm
if(info.glasses == 6) {
knowledge += 10;
charm += 25;
strength += 5;
}
//if moustach, add stregth.
if(info.moustache > 6) {
strength += 15;
}
//if hat,moustach and glasses then add extra score
if(info.hat < 6 && info.glasses == 6 && info.moustache > 6) {
charm += 15;
knowledge += 15;
strength += 15;
}
uint16 money = (strength + knowledge + charm) / 3;
uint16[] memory charAttributes = new uint16[](4);
charAttributes[0] = strength;
charAttributes[1] = knowledge;
charAttributes[2] = charm;
charAttributes[3] = money;
return charAttributes;
}
/**
* @notice getfacepath by generating random points around circumference
* @notice of a circle and then generating path using spline.
*/
function _getFacePath(Info memory info,Randomize.Random memory random)
internal
pure
returns (bytes memory)
{
uint8 z = 4;
uint8 facePoints = info.facePoints;
int256[] memory points = new int256[](facePoints * 2 + 8);
int256 oneAtPrecision = 18446744073709551616; // 2**64
int256 twoPi = 115904311329233965478; //2pi @ oneAtPrecision
int256 angle = twoPi / int8(facePoints);
for (int8 i = 1; i <= int8(facePoints); i++) {
int8 pull = int8(uint8(random.next(80,100)));
int256 xx = 100 + (Trignometry.cos(i * angle) * 50 * pull) / oneAtPrecision / 100;
int256 yy = 100 + (Trignometry.sin(i * angle) * 50 * pull) / oneAtPrecision / 100;
points[z] = xx;
z++;
points[z] = yy;
z++;
}
points[0] = points[facePoints * 2];
points[1] = points[facePoints * 2 + 1];
points[2] = points[facePoints * 2 + 2];
points[3] = points[facePoints * 2 + 3];
points[facePoints * 2 + 4] = points[4];
points[facePoints * 2 + 5] = points[5];
points[facePoints * 2 + 6] = points[6];
points[facePoints * 2 + 7] = points[7];
return _calculateFacePath(points);
}
/**
* @notice convert points into svg path.
* @dev https://github.com/georgedoescode/splinejs/blob/main/spline.js
*/
function _calculateFacePath(int256[] memory points)
internal
pure
returns (bytes memory)
{
uint256 last = points.length - 4;
uint256 maxIteration = last;
bytes memory path = abi.encodePacked('M',uint256(points[2]).toString(),',',uint256(points[3]).toString());
for (uint256 ii = 2; ii < maxIteration; ii+=2) {
int256[] memory values = new int256[](6);
values[0] = ii != last ? points[ii + 4] : points[ii + 2];
values[1] = ii != last ? points[ii + 5] : points[ii + 3];
values[2] = points[ii + 0] + ((points[ii + 2] - points[ii - 2]) / 6);
values[3] = points[ii + 1] + ((points[ii + 3] - points[ii - 1]) / 6);
values[4] = points[ii + 2] - ((values[0] - points[ii + 0] ) / 6);
values[5] = points[ii + 3] - ((values[1] - points[ii + 1] ) / 6);
path = abi.encodePacked(
path,
'C',
uint256(values[2]).toString(),
',',
uint256(values[3]).toString(),
',',
uint256(values[4]).toString(),
',',
uint256(values[5]).toString(),
',',
uint256(points[ii + 2]).toString(),
',',
uint256(points[ii + 3]).toString()
);
}
return path;
}
/**
* @notice getBackground
*/
function _getBackground(Randomize.Random memory random, uint8 race)
internal
pure
returns(bytes memory) {
uint256 lightness = race == 4 ? 10 : 90;
uint256 backgroundClrHue = random.next(1,360);
bytes memory background = abi.encodePacked(
"<rect width='200' height='200' fill='hsl(",
backgroundClrHue.toString(),
" 100% ",
lightness.toString(),
"%)' />"
);
return background;
}
/**
* @notice getFaceAndDefs
*/
function _getFaceAndDefs(Randomize.Random memory random ,uint256 race, bytes memory facePath)
internal
pure
returns(bytes memory face, bytes memory defs)
{
if(race == 4) {
defs = abi.encodePacked(
"<defs>",
"<clipPath id='face'><path d='",
facePath,
"'></path></clipPath></defs>"
);
bytes memory skin = _getSkin(random);
face = abi.encodePacked(
"<g clip-path='url(#face)'>",
skin,
"</g>"
);
}
else {
uint256 hue = random.next(1,360);
uint256 saturation = random.next(75,100);
uint256 lightness = random.next(50,90);
face = abi.encodePacked(
"<path d='",
facePath,
"' stroke-width='0.1' stroke='hsl(",
hue.toString(),
", ",
saturation.toString(),
"%, 30%)' fill='hsl(",
hue.toString(),
", ",
saturation.toString(),
"%, ",
lightness.toString(),
"%)'></path>"
);
}
return (face, defs);
}
/**
* @notice get skin by generating random Lines
* @notice and filling with random colors
*/
function _getSkin(Randomize.Random memory random)
internal
pure
returns(bytes memory) {
bytes memory lines = abi.encodePacked(
"<rect width='200' height='200' fill='hsl(",
random.next(1, 360).toString(),
" ",
random.next(1, 100).toString(),
"% 25%)'></rect>"
);
uint256 totalLines = random.next(2,6);
for(uint i; i <= totalLines; i++) {
uint256[] memory points = new uint256[](8);
points[0] = random.next(1,200);
points[1] = random.next(1,200);
points[2] = random.next(50,150);
points[3] = random.next(50,150);
points[4] = random.next(50,150);
points[5] = random.next(50,150);
points[6] = random.next(1,200);
points[7] = random.next(1,200);
uint256 hue = random.next(1, 360);
uint256 saturation = random.next(75, 100);
uint256 lightness = random.next(50, 90);
bytes memory path = abi.encodePacked(
points[0].toString(),
",",
points[1].toString(),
" ",
points[2].toString(),
",",
points[3].toString(),
" ",
points[4].toString(),
",",
points[5].toString(),
" S50,150 ",
points[7].toString(),
",200'"
);
lines = abi.encodePacked(
lines,
"<path d='M",
points[6].toString(),
",0 C",
path,
" stroke-width='3' fill='hsl(",
hue.toString(),
",",
saturation.toString(),
"%,",
lightness.toString(),
"%)' fill-opacity='0.5'></path>"
);
}
return lines;
}
/**
* @notice getMouth
*/
function _getMouth(uint256 mouthType)
internal
pure
returns(bytes memory)
{
bytes memory mouth = abi.encodePacked(
"<ellipse cx='100' cy='125' rx='20' ry='",
mouthType.toString(),
"' fill='white' stroke='black' stroke-width='2'></ellipse>"
);
return mouth;
}
/**
* @notice getEyes
*/
function _getEyes(Randomize.Random memory random)
internal
pure
returns(bytes memory)
{
uint256 eyeInnerType = random.next(1,2);
uint256 eyePositionX = random.next(1,8); //random (-4,4);
uint256 eyePositionY = random.next(1,10); //random(-5,5);
uint256 circlePostionX = random.next(1,5); //random (-2,3);
bytes memory inner;
bytes memory outer;
bytes memory eyePositionBytesX = eyePositionX < 5 ? abi.encodePacked('-',eyePositionX.toString()) : abi.encodePacked((eyePositionX - 4).toString());
bytes memory eyePositionBytesY = eyePositionY < 6 ? abi.encodePacked('-',eyePositionY.toString()) : abi.encodePacked((eyePositionY - 5).toString());
bytes memory circlePostionBytesX = circlePostionX < 3 ? abi.encodePacked('-',circlePostionX.toString()) : abi.encodePacked((circlePostionX - 2).toString());
if(eyeInnerType == 1) {
inner = "<ellipse rx='7' ry='5' cx='0' cy='0' fill='hsl(315, 87%, 2%)'></ellipse>";
}
else {
inner = abi.encodePacked("<circle r='",random.next(4,7).toString(),"' cx='0' cy='0' fill='hsl(315, 87%, 2%)'></circle>"
);
}
outer = abi.encodePacked(
"<g transform='matrix(1,0,0,1,",
eyePositionBytesX,
",",
eyePositionBytesY,
")'><ellipse rx='7' ry='5' cx='0' cy='0' fill='hsl(315, 87%, 2%)'></ellipse>",
"<circle r='2' cx='",
circlePostionBytesX,
"' cy='-2' fill='white'></circle></g>"
);
bytes memory eyes = abi.encodePacked(
"<g transform='matrix(1,0,0,1,82.5,90)'><circle r='10' cx='0' cy='0' stroke-width='2' stroke='hsl(315, 87%, 2%)' fill='hsl(315, 87%, 98%)'></circle>",
outer,
"</g><g transform='matrix(1,0,0,1,117.5,90)'><circle r='10' cx='0' cy='0' stroke-width='2' stroke='hsl(315, 87%, 2%)' fill='hsl(315, 87%, 98%)'></circle>",
outer,
"</g>"
);
return eyes;
}
/**
* @notice get Attributes Svg to display attributes score.
*/
function _getCharAttributesSvg(uint16[] memory charAttributes)
internal
pure
returns(bytes memory attributesSvg)
{
attributesSvg = abi.encodePacked(
"<rect x='5' y='150' width='50' height='10' fill='#C2B280' stroke='#C2B280'></rect><text x='7' y='158' font-size='7'>Strength</text><rect x='45' y='150' width='20' height='10' fill='#000' stroke='#C2B280'></rect><text x='50' y='158' font-size='8' fill='#fff'>",
charAttributes[0].toString(),
"</text><rect x='5' y='162' width='50' height='10' fill='#C2B280' stroke='#C2B280'></rect><text x='7' y='170' font-size='7'>Knowledge</text><rect x='45' y='162' width='20' height='10' fill='#000' stroke='#C2B280'></rect><text x='50' y='170' font-size='8' fill='#fff'>",
charAttributes[1].toString(),
"</text><rect x='5' y='174' width='50' height='10' fill='#C2B280' stroke='#C2B280'></rect><text x='7' y='182' font-size='7'>Charm</text><rect x='45' y='174' width='20' height='10' fill='#000' stroke='#C2B280'></rect><text x='50' y='182' font-size='8' fill='#fff'>",
charAttributes[2].toString(),
"</text><rect x='5' y='186' width='50' height='10' fill='#C2B280' stroke='#C2B280'></rect><text x='7' y='194' font-size='7'>Money</text><rect x='45' y='186' width='20' height='10' fill='#000' stroke='#C2B280'></rect><text x='50' y='194' font-size='8' fill='#fff'>",
charAttributes[3].toString(),
"</text>"
);
}
/**
* @notice getPathsInfo
* @dev 0=offset, 1=size, 2=clr
*/
function _getPathsInfo(uint8 index)
internal
pure
returns(uint24[3][] memory) {
if(index == 1) {
uint24[3][] memory info = new uint24[3][](6);
info[0] = [uint24(0), uint24(175), 0x000001];
info[1] = [uint24(175), uint24(121), 0x2b2c2d];
info[2] = [uint24(296), uint24(89), 0x2b2c2d];
info[3] = [uint24(385), uint24(117), 0x6a6a6d];
info[4] = [uint24(502), uint24(86), 0x000000];
info[5] = [uint24(588), uint24(63), 0xffffff];
return (info);
}
else if(index == 2) {
uint24[3][] memory info = new uint24[3][](4);
info[0] = [uint24(651), uint24(128), 0x333333];
info[1] = [uint24(779), uint24(209), 0x1e1e1e];
info[2] = [uint24(988), uint24(49), 0x333333];
info[3] = [uint24(1037), uint24(87), 0x474c51];
return (info);
}
else if(index == 3) {
uint24[3][] memory info = new uint24[3][](6);
info[0] = [uint24(1124), uint24(93), 0x303030];
info[1] = [uint24(1217), uint24(36), 0x303030];
info[2] = [uint24(1253), uint24(33), 0x000000];
info[3] = [uint24(1286), uint24(44), 0xffffff];
info[4] = [uint24(1330), uint24(62), 0x000000];
info[5] = [uint24(1392), uint24(90), 0x21201e];
return (info);
}
else if(index == 4) {
uint24[3][] memory info = new uint24[3][](4);
info[0] = [uint24(1482), uint24(139), 0x2b2c2d];
info[1] = [uint24(1621), uint24(183), 0x111111];
info[2] = [uint24(1804), uint24(58), 0x000000];
info[3] = [uint24(1862), uint24(96), 0xffffff];
return (info);
}
else if(index == 5) {
uint24[3][] memory info = new uint24[3][](2);
info[0] = [uint24(1958), uint24(1436), 0x2b2c2d];
info[1] = [uint24(3394), uint24(998), 0x222222];
return (info);
}
else if(index == 6) {
uint24[3][] memory info = new uint24[3][](3);
info[0] = [uint24(4392), uint24(131), 0x272626];
info[1] = [uint24(4523), uint24(420), 0x000000];
info[2] = [uint24(4943), uint24(93), 0xfcfadd];
return (info);
}
else if(index == 7) {
uint24[3][] memory info = new uint24[3][](2);
info[0] = [uint24(5036), uint24(535), 0x1c1c1c];
info[1] = [uint24(5571), uint24(346), 0x848484];
return (info);
}
else if(index == 8) {
uint24[3][] memory info = new uint24[3][](2);
info[0] = [uint24(5917), uint24(484), 0x1c1c1c];
info[1] = [uint24(6401), uint24(488), 0x848484];
return (info);
}
else { //index == 9
uint24[3][] memory info = new uint24[3][](2);
info[0] = [uint24(6889), uint24(734), 0x1c1c1c];
info[1] = [uint24(7623), uint24(315), 0x848484];
return (info);
}
}
/**
* @notice bytes3ToHexBytes
*/
function _bytes3ToHexBytes(bytes3 _color)
internal
pure
returns (bytes memory)
{
bytes memory numbers = "0123456789ABCDEF";
bytes memory hexBytes = new bytes(6);
uint256 pos;
for (uint256 i; i < 3; i++) {
hexBytes[pos] = numbers[uint8(_color[i] >> 4)];
pos++;
hexBytes[pos] = numbers[uint8(_color[i] & 0x0f)];
pos++;
}
return hexBytes;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Roc
* @author Tfs128.eth (@trickerfs128)
*/
contract Roc {
mapping(uint256 => uint256) public _child_rem;
}
// 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;
// small library to get random number
library Randomize {
struct Random {
uint256 seed;
uint256 nonce;
}
function next(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256 result) {
max += 1;
uint256 number = uint256(keccak256(abi.encode(random.seed,random.nonce))) % (max - min);
random.nonce++;
result = number + min;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @notice library to evaluate sin and cos using expanded taylor series by horner's rule.
*/
library Trignometry {
int256 private constant PRECISION = 64;
int256 private constant ONE_AT_PRECISION = 18446744073709551616; //2**64
int256 private constant PI = 57952155664616982739; // PI * ONE_AT_PRECISION
/**
* @notice evaluate sin(x).
* @dev sin(x) != sin(x + 2pi)
*/
function sin(int256 x) internal pure returns(int256) {
int256 value;
assembly {
let xsq := sar(PRECISION, mul(x, x)) // xsq = x^2
let xx := add(51862, sar(PRECISION, mul(xsq, sub(0, 151)))) // b8 = 1/17! + xsq*(-1/19!)
xx := add(sub(0, 14106527), sar(PRECISION, mul(xsq, xx))) // b7 = -1/15! + xsq*b8
xx := add(2962370717, sar(PRECISION, mul(xsq, xx))) // b6 = 1/13! + xsq*b7
xx := add(sub(0, 462129831893), sar(PRECISION, mul(xsq, xx))) // b5 = -1/11! + xsq*b6
xx := add(50834281508238, sar(PRECISION, mul(xsq, xx))) // b4 = 1/9! + xsq*b5
xx := add(sub(0, 3660068268593165), sar(PRECISION, mul(xsq, xx))) // b3 = -1/7! + xsq*b4
xx := add(153722867280912930, sar(PRECISION, mul(xsq, xx))) // b2 = 1/5! + xsq*b3
xx := add(sub(0, 3074457345618258602), sar(PRECISION, mul(xsq, xx))) // b1 = -1/3! + xsq*b2
xx := add(ONE_AT_PRECISION, sar(PRECISION, mul(xsq, xx))) // t = 1 + xsq*b1
xx := sar(PRECISION, mul(xx, x)) // sin(x) = t*x
value := xx
}
return value;
}
/**
* @notice evaluate cos(x)
* @dev cos(x) = sin(90 - x)
*/
function cos(int256 x) internal pure returns(int256) {
int256 cx = PI/2 - x;
if(cx < 0) {
return -sin(cx * -1); //sin(-x) = -sin(x)
}
else {
return sin(cx);
}
}
} | get skin by generating random Lines and filling with random colors/ | function _getSkin(Randomize.Random memory random)
internal
pure
returns(bytes memory) {
bytes memory lines = abi.encodePacked(
"<rect width='200' height='200' fill='hsl(",
random.next(1, 360).toString(),
" ",
random.next(1, 100).toString(),
"% 25%)'></rect>"
);
uint256 totalLines = random.next(2,6);
for(uint i; i <= totalLines; i++) {
uint256[] memory points = new uint256[](8);
points[0] = random.next(1,200);
points[1] = random.next(1,200);
points[2] = random.next(50,150);
points[3] = random.next(50,150);
points[4] = random.next(50,150);
points[5] = random.next(50,150);
points[6] = random.next(1,200);
points[7] = random.next(1,200);
uint256 hue = random.next(1, 360);
uint256 saturation = random.next(75, 100);
uint256 lightness = random.next(50, 90);
bytes memory path = abi.encodePacked(
points[0].toString(),
",",
points[1].toString(),
" ",
points[2].toString(),
",",
points[3].toString(),
" ",
points[4].toString(),
",",
points[5].toString(),
" S50,150 ",
points[7].toString(),
",200'"
);
lines = abi.encodePacked(
lines,
"<path d='M",
points[6].toString(),
",0 C",
path,
" stroke-width='3' fill='hsl(",
hue.toString(),
",",
saturation.toString(),
"%,",
lightness.toString(),
"%)' fill-opacity='0.5'></path>"
);
}
return lines;
}
| 14,771,333 |
./full_match/4/0x8de75F203346bb6232478A40AC7E183a0C8E6A68/sources/contracts/test.sol | Send balance of contract to address referenced in `vault` | function withdraw() external payable onlyOwner {
require(vault != address(0), 'Vault Invalid');
require(payable(vault).send(address(this).balance));
}
| 673,818 |
./full_match/5/0x0840602fe76d523db09c1246FA5c021BF006de36/sources/contracts/CrowdFunding.sol | TODO write delete campaign | function deleteCampaign(uint256 campaignId) public returns(Campaign[] memory){
Campaign[] memory allCampaigns = new Campaign[](NumberOfCampaigns);
delete allCampaigns[campaignId];
NumberOfCampaigns--;
return allCampaigns;
}
| 7,064,252 |
./full_match/83/0xFFE4480A22eB3A42ECE67A196933eb2A180c4876/sources/contracts/BaseV1-periphery.sol | performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(uint256 amountIn, route[] memory routes)
public
view
returns (uint256[] memory amounts)
{
require(routes.length >= 1, "BaseV1Router: INVALID_PATH");
amounts = new uint256[](routes.length + 1);
amounts[0] = amountIn;
for (uint256 i = 0; i < routes.length; i++) {
address pair = pairFor(
routes[i].from,
routes[i].to,
routes[i].stable
);
if (IBaseV1Factory(factory).isPair(pair)) {
amounts[i + 1] = IBaseV1Pair(pair).getAmountOut(
amounts[i],
routes[i].from
);
}
}
}
| 9,560,990 |
./full_match/100/0xD3794DABFfcc9581B3c76b963e0A7e9e3e764EaE/sources/contracts/rollup/facets/RollupAdmin.sol | this skips deadline, staker and zombie validation | function forceConfirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
) external override whenPaused {
confirmNode(
nodeNum,
beforeSendAcc,
sendsData,
sendLengths,
afterSendCount,
afterLogAcc,
afterLogCount,
outbox,
rollupEventBridge
);
emit OwnerFunctionCalled(24);
}
| 14,280,776 |
./full_match/42/0x725DDa8A778B507bA02a7F56146a2D5D7f5740CE/sources/home/didi/src/sf/streaming-faucet/contracts/StreamingFaucet.sol | stops the stream to the message sender if open (useful for testing, otherwise not needed) | function stopStream() external {
address receiver = msg.sender;
_sfHost.callAgreement(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
token,
address(this),
receiver,
new bytes(0)
),
"0x"
);
}
| 9,598,164 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*pragma solidity >=0.6.0 <0.8.0;*/
import "contracts/IVote.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/*import "IVote.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";
*/
/**
* @notice Implementation of IVote interface. Majority_Judgment_Ballot contract implement the Majority Judgment which is a ballot process proven to be able to avoid biases of classical Uninominal ballot such as strategic vote. In Majority Judgment ballot,
* citizens assess each candidat and give it a grade. In our implementation, each candidat proposition can be assessed as «Reject», «Bad», «Neutral», «Good» and «Excelent».
* For each candidat proposition, citizens assessment are sorted from best grades to worst ones (from «Excelent» to «Reject»). The majority grade of a proposition corresponds to it’s median grade. If the majority grade of a candidat proposition is «Good»,
* it means that 50% of citizens think that this proposition is «Good» or Better.
* Winning propositions are the M candidats propositions that have the best Majority grade.
* If the most popular proposition is the blank vote, then we ignore the other M-1 winning propositions.
* */
/// @dev Implementation of IVote interface. Majority_Judgment_Ballot contract implement the Majority Judgment which is a ballot process proven to be able to avoid biases of classical Uninominal ballot such as strategic vote. In Majority Judgment ballot,
contract Majority_Judgment_Ballot is IVote{
enum Assessement{
EXCELENT,
GOOD,
NEUTRAL,
BAD,
REJECT
}
enum Ballot_Status{
NON_CREATED,
VOTE,
VOTE_VALIDATION,
FINISHED
}
struct Voter{
bool Voted;
bool Validated;
bytes32 Choice;
}
struct Propositions_Result{
uint[5] Cumulated_Score;
Assessement Median_Grade;
}
struct Ballot{
address Voters_Register_Address;
bytes4 Check_Voter_Selector;
Ballot_Status Status;
uint Creation_Timestamp;
uint End_Vote_Timestamp;
uint Vote_Duration;
uint Vote_Validation_Duration;
uint Propositions_Number;
uint Max_Winning_Propositions_Number;
uint Voter_Number;
uint[] Winning_Propositions;
mapping(address=>Voter) Voters;
mapping(uint=>Propositions_Result) Propositions_Results; //From 0 to Propositions_Number. If the 0 proposition get the first place, the oder propositions are rejected.
}
event Ballot_Created(bytes32 key);
event Voted_Clear(bytes32 key, address voter);
event Voted_Hashed(bytes32 key, address voter);
event Begin_Validation(bytes32 key);
event Validated_Vote(bytes32 key, address voter);
event Vote_Finished(bytes32 key);
/// @dev Mapping of all voting sessions of the contract.
mapping(bytes32=>Ballot) public Ballots;
/// @dev See {IVote} interface.
function Create_Ballot(bytes32 key, address Voters_Register_Address, bytes4 Check_Voter_Selector, uint Vote_Duration, uint Vote_Validation_Duration, uint Propositions_Number, uint Max_Winning_Propositions_Number) external override {
require(Ballots[key].Creation_Timestamp == 0, "Already Existing Ballot");
if(Voters_Register_Address==address(0) || Check_Voter_Selector==bytes4(0) || Vote_Duration==0 || Max_Winning_Propositions_Number==0 ){
revert("Bad Argument Values");
}
if(Propositions_Number==1){
require(Max_Winning_Propositions_Number==1, "Argument Inconsistency");
}else{
require(Propositions_Number>Max_Winning_Propositions_Number, "Argument Inconsistency");
}
Ballots[key].Voters_Register_Address =Voters_Register_Address;
Ballots[key].Check_Voter_Selector = Check_Voter_Selector;
Ballots[key].Vote_Duration = Vote_Duration;
Ballots[key].Vote_Validation_Duration = Vote_Validation_Duration;
Ballots[key].Propositions_Number = Propositions_Number;
Ballots[key].Max_Winning_Propositions_Number = Max_Winning_Propositions_Number;
Ballots[key].Creation_Timestamp =block.timestamp;
Ballots[key].Status = Ballot_Status.VOTE;
emit Ballot_Created(key);
}
/// @dev See {IVote} interface.
function Vote_Clear(bytes32 key, uint[] calldata Choices) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration == 0, "Should Use Vote_Hashed");
uint choice_len = Choices.length ;
require(Ballots[key].Propositions_Number + 1 == choice_len, "Choices argument wrong size");
Ballots[key].Voter_Number = Ballots[key].Voter_Number +1;
Ballots[key].Voters[msg.sender].Voted = true;
for(uint i=0; i< choice_len; i++){
for(uint j=Choices[i]; j<5; j++){
Ballots[key].Propositions_Results[i].Cumulated_Score[j]++;
}
}
emit Voted_Clear(key, msg.sender);
}
/// @dev See {IVote} interface.
function Vote_Hashed(bytes32 key, bytes32 Hash) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration > 0, "Should Use Vote_Clear");
Ballots[key].Voters[msg.sender].Voted = true;
Ballots[key].Voters[msg.sender].Choice = Hash;
emit Voted_Hashed( key, msg.sender);
}
/// @dev See {IVote} interface.
function End_Vote(bytes32 key)external override{
require(Ballots[key].Status==Ballot_Status.VOTE, "Not at voting stage");
require(Ballots[key].Vote_Duration < block.timestamp - Ballots[key].Creation_Timestamp, "Voting stage not finished");
if(Ballots[key].Vote_Validation_Duration>0){
Ballots[key].Status = Ballot_Status.VOTE_VALIDATION;
emit Begin_Validation(key);
}else{
_Talling_Votes(key);
Ballots[key].Status = Ballot_Status.FINISHED;
emit Vote_Finished(key);
}
Ballots[key].End_Vote_Timestamp = block.timestamp;
}
/// @dev See {IVote} interface.
function Valdiate_Vote(bytes32 key, uint[] calldata Choices, bytes32 salt )external override {
require(Ballots[key].Status==Ballot_Status.VOTE_VALIDATION, "Not at vote validation stage");
require(!Ballots[key].Voters[msg.sender].Validated, "Vote Already Validated");
uint choice_len = Choices.length ;
require(Ballots[key].Propositions_Number+1 == choice_len, "Choices argument wrong size");
bytes32 hash = keccak256(abi.encode(Choices, salt));
require(hash==Ballots[key].Voters[msg.sender].Choice, "Hashes don't match");
Ballots[key].Voters[msg.sender].Validated = true;
Ballots[key].Voter_Number = Ballots[key].Voter_Number+1;
for(uint i=0; i<Choices.length; i++){
for(uint j=Choices[i]; j<5; j++){
Ballots[key].Propositions_Results[i].Cumulated_Score[j]++;
}
}
emit Validated_Vote(key, msg.sender);
}
/// @dev See {IVote} interface.
function End_Validation_Vote(bytes32 key) external override{
require( (Ballots[key].Status == Ballot_Status.VOTE_VALIDATION && Ballots[key].Vote_Validation_Duration < block.timestamp - Ballots[key].End_Vote_Timestamp), "Not at vote counting stage");
_Talling_Votes(key);
Ballots[key].Status = Ballot_Status.FINISHED;
emit Vote_Finished(key);
}
/**
* @dev Count votes.
* @param key Id of the voting session
*/
function _Talling_Votes(bytes32 key) internal{
uint number_propositions = Ballots[key].Propositions_Number;
uint half_voters = Ballots[key].Voter_Number/2 + Ballots[key].Voter_Number%2;
uint winning_propositions_number = Ballots[key].Max_Winning_Propositions_Number;
uint[] memory winning_propositions = new uint[](winning_propositions_number+1);
uint[] memory winning_propositions_grades = new uint[](winning_propositions_number+1);
uint mention;
uint rank;
uint winning_list_size;
bool continu;
uint Temp_prop;
//Assessement of eaxh proposition
for(uint prop=0; prop<=number_propositions; prop++){
while(Ballots[key].Propositions_Results[prop].Cumulated_Score[mention]<half_voters){
mention++;
}
Ballots[key].Propositions_Results[prop].Median_Grade = Assessement(mention);
//Fetching the "winning_propositions_number" winning propositions.
continu=true;
while(continu && rank<winning_list_size){
if(winning_propositions_grades[rank]<mention || (winning_propositions_grades[rank]==mention && Order_Proposition_Result(key, winning_propositions[rank], prop, mention)!=prop)){
rank++;
}else{
continu=false;
}
}
if(winning_list_size<winning_propositions_number+1){
winning_list_size++;
}
Temp_prop=prop;
while(rank<winning_list_size){
if(rank+1<winning_list_size){
(winning_propositions[rank], Temp_prop) = (Temp_prop, winning_propositions[rank]);
(winning_propositions_grades[rank], mention) = (mention, winning_propositions_grades[rank]);
rank++;
}else{
winning_propositions[rank]=Temp_prop;
winning_propositions_grades[rank]=mention;
rank = winning_list_size;
}
}
rank=0;
mention=0;
}
if(winning_propositions[0]==0){ //If the first proposition is the default proposition
Ballots[key].Winning_Propositions.push(0);
}else{
uint i;
while(Ballots[key].Winning_Propositions.length<winning_propositions_number){
if(winning_propositions[i]!=0){ //0 proposition is conssidered only if it is in the first position
Ballots[key].Winning_Propositions.push(winning_propositions[i]);
}
i++;
}
}
}
/**
* @dev Sort by their score two propositions that have the same {median_grade}. The function returns the id of the most popular function.
* @param key Id of the voting session
* @param prop1 First proposition Id.
* @param prop2 Second proposition Id.
* @param median_grade Median grade score.
*
*/
function Order_Proposition_Result(bytes32 key, uint prop1, uint prop2, uint median_grade)internal view returns(uint){
if(median_grade==0){
return (Ballots[key].Propositions_Results[prop1].Cumulated_Score[0]<Ballots[key].Propositions_Results[prop2].Cumulated_Score[0])? prop2:prop1;
}else{
return (Ballots[key].Propositions_Results[prop1].Cumulated_Score[median_grade-1]<Ballots[key].Propositions_Results[prop2].Cumulated_Score[median_grade-1])? prop2:prop1;
}
}
/**
* @dev Check whether an account is registered in the {Voters_Register_Address} contract. In other words, it checks whether the account has the right to vote in the voting session or not.
* @param key Id of the voting session
* @param voter_address Address of the account.
*
*/
function Check_Voter_Address(bytes32 key, address voter_address) internal returns(bool){
(bool success, bytes memory Data) = Ballots[key].Voters_Register_Address.call(abi.encodeWithSelector(Ballots[key].Check_Voter_Selector, voter_address));
require(success, "Voter check function reverted");
return abi.decode(Data, (bool));
}
/*GETTER*/
/// @dev See {IVote} interface
function Get_Winning_Propositions(bytes32 key)external view override returns(uint[] memory Winning_Propositions_List){
require(Ballots[key].Status == Ballot_Status.FINISHED, "Ballot still Pending");
return Ballots[key].Winning_Propositions;
}
/// @dev See {IVote} interface
function Get_Winning_Proposition_byId(bytes32 key, uint Id)external view override returns(uint Winning_Proposition){
require(Id<Ballots[key].Winning_Propositions.length, "Id exceed Winning length");
return Ballots[key].Winning_Propositions[Id];
}
/// @dev See {IVote} interface
function HasVoted(bytes32 key, address voter_address) external view override returns(bool hasvoted){
return Ballots[key].Voters[voter_address].Voted;
}
/// @dev See {IVote} interface
function HasValidated(bytes32 key, address voter_address) external view override returns(bool Validated, bytes32 Choice){
return (Ballots[key].Voters[voter_address].Validated, Ballots[key].Voters[voter_address].Choice);
}
/// @dev See {IVote} interface
function Get_Voter_Number(bytes32 key)external view override returns(uint voter_num){
return Ballots[key].Voter_Number;
}
/**
* @dev Get the score obtained by a proposition
* @param key Id of the voting session
* @param proposition_Id Index of the proposition
* @return proposition_result
*
* */
function Get_Propositions_Result(bytes32 key, uint proposition_Id) external view returns(Propositions_Result memory proposition_result){
return Ballots[key].Propositions_Results[proposition_Id];
}
}
| See {IVote} interface. | function Vote_Hashed(bytes32 key, bytes32 Hash) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration > 0, "Should Use Vote_Clear");
Ballots[key].Voters[msg.sender].Voted = true;
Ballots[key].Voters[msg.sender].Choice = Hash;
emit Voted_Hashed( key, msg.sender);
}
| 1,043,587 |
./full_match/25/0xBf0Ca142dE65250c38B9C682c5Dd51d56E18dF6A/sources/gist-c1eb4b41642a69b5a7232840482b6e91/IERC721.sol | Required interface of an ERC721 compliant contract./ | interface 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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function setApprovalForAll(address operator, bool _approved) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
| 16,382,404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.