file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IWETH.sol"; contract ETHTosDisTransit is Ownable { using SafeMath for uint; address public signWallet; address public developWallet; address public WETH; uint public totalFee; uint public developFee; // key: payback_id mapping (bytes32 => bool) public executedMap; uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'Locked'); unlocked = 0; _; unlocked = 1; } event Transit(address indexed from, address indexed token, uint amount); event Withdraw(bytes32 paybackId, address indexed to, address indexed token, uint amount); event CollectFee(address indexed handler, uint amount); event ChangedSigner(address wallet); event ChangedDevelopWallet(address wallet); event ChangedDevelopFee(uint amount); constructor(address _WETH, address _signer, address _developer) public { WETH = _WETH; signWallet = _signer; developWallet = _developer; } receive() external payable { assert(msg.sender == WETH); } function changeSigner(address _wallet) external onlyOwner{ // require(msg.sender == owner, "CHANGE_SIGNER_FORBIDDEN"); signWallet = _wallet; emit ChangedSigner(signWallet); } function changeDevelopWallet(address _wallet) external onlyOwner{ // require(msg.sender == owner, "CHANGE_DEVELOP_WALLET_FORBIDDEN"); developWallet = _wallet; emit ChangedDevelopWallet(developWallet); } function changeDevelopFee(uint _amount) external onlyOwner{ // require(msg.sender == owner, "CHANGE_DEVELOP_FEE_FORBIDDEN"); developFee = _amount; emit ChangedDevelopFee(developFee); } function collectFee() external onlyOwner lock{ // require(msg.sender == owner, "FORBIDDEN"); require(developWallet != address(0), "SETUP_DEVELOP_WALLET"); require(totalFee > 0, "NO_FEE"); TransferHelper.safeTransferETH(developWallet, totalFee); totalFee = 0; } function transitForBSC(address _tokenAddress, uint _amount) external { require(_amount > 0, "INVALID_AMOUNT"); IERC20 token = IERC20(_tokenAddress); uint256 balanceBefore = token.balanceOf(address(this)); TransferHelper.safeTransferFrom(_tokenAddress, msg.sender, address(this), _amount); uint256 received = token.balanceOf(address(this)).sub(balanceBefore); require(received ==_amount, "UNSUPPORTED_TOKEN"); emit Transit(msg.sender, _tokenAddress, _amount); } function transitETHForBSC() external payable { require(msg.value > 0, "INVALID_AMOUNT"); IWETH(WETH).deposit{value: msg.value}(); emit Transit(msg.sender, WETH, msg.value); } function withdrawFromBSC(bytes calldata _signature, bytes32 _paybackId, address _token, uint _amount) external lock payable { require(!executedMap[_paybackId], "ALREADY_EXECUTED"); executedMap[_paybackId] = true; require(_amount > 0, "NOTHING_TO_WITHDRAW"); require(msg.value == developFee, "INSUFFICIENT_VALUE"); bytes32 message = keccak256(abi.encodePacked(_paybackId, _token, msg.sender, _amount)); require(_verify(message, _signature), "INVALID_SIGNATURE"); if(_token == WETH) { IWETH(WETH).withdraw(_amount); TransferHelper.safeTransferETH(msg.sender, _amount); } else { TransferHelper.safeTransfer(_token, msg.sender, _amount); } totalFee = totalFee.add(developFee); emit Withdraw(_paybackId, msg.sender, _token, _amount); } function _verify(bytes32 _message, bytes memory _signature) internal view returns (bool) { bytes32 hash = _toEthBytes32SignedMessageHash(_message); address[] memory signList = _recoverAddresses(hash, _signature); return signList[0] == signWallet; } function _toEthBytes32SignedMessageHash (bytes32 _msg) pure internal returns (bytes32 signHash) { signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _msg)); } function _recoverAddresses(bytes32 _hash, bytes memory _signatures) pure internal returns (address[] memory addresses) { uint8 v; bytes32 r; bytes32 s; uint count = _countSignatures(_signatures); addresses = new address[](count); for (uint i = 0; i < count; i++) { (v, r, s) = _parseSignature(_signatures, i); addresses[i] = ecrecover(_hash, v, r, s); } } function _parseSignature(bytes memory _signatures, uint _pos) pure internal returns (uint8 v, bytes32 r, bytes32 s) { uint offset = _pos * 65; assembly { r := mload(add(_signatures, add(32, offset))) s := mload(add(_signatures, add(64, offset))) v := and(mload(add(_signatures, add(65, offset))), 0xff) } if (v < 27) v += 27; require(v == 27 || v == 28); } function _countSignatures(bytes memory _signatures) pure internal returns (uint) { return _signatures.length % 65 == 0 ? _signatures.length / 65 : 0; } } pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint) external; } pragma solidity >=0.6.0; library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // 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 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
require(msg.sender == owner, "CHANGE_SIGNER_FORBIDDEN");
function changeSigner(address _wallet) external onlyOwner{ signWallet = _wallet; emit ChangedSigner(signWallet); }
1,377,486
[ 1, 6528, 12, 3576, 18, 15330, 422, 3410, 16, 315, 14473, 67, 11260, 654, 67, 7473, 30198, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 15647, 12, 2867, 389, 19177, 13, 3903, 1338, 5541, 95, 203, 3639, 1573, 16936, 273, 389, 19177, 31, 203, 3639, 3626, 27707, 15647, 12, 2977, 16936, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x72AD58f0917deB04eC8b6AdA584ABd0dBe502128/sources/SafeTransferLib.sol
Get a pointer to some free memory. Write the abi-encoded calldata to memory piece by piece: Call the token and store if it succeeded or not. We use 100 because the calldata length is 4 + 32 * 3.
function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { let freeMemoryPointer := mload(0x40) mstore( freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000 mstore( add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff) mstore( add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff) callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require( didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED" ); }
3,587,196
[ 1, 967, 279, 4407, 358, 2690, 4843, 3778, 18, 2598, 326, 24126, 17, 10787, 745, 892, 358, 3778, 11151, 635, 11151, 30, 3049, 326, 1147, 471, 1707, 309, 518, 15784, 578, 486, 18, 1660, 999, 2130, 2724, 326, 745, 892, 769, 353, 1059, 397, 3847, 225, 890, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 4232, 39, 3462, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 288, 203, 3639, 1426, 745, 1482, 31, 203, 203, 3639, 19931, 288, 203, 5411, 2231, 4843, 6031, 4926, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 203, 5411, 312, 2233, 12, 203, 7734, 4843, 6031, 4926, 16, 203, 7734, 374, 92, 4366, 70, 28, 9060, 449, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 203, 5411, 312, 2233, 12, 203, 7734, 527, 12, 9156, 6031, 4926, 16, 1059, 3631, 203, 7734, 471, 12, 2080, 16, 374, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 13, 203, 5411, 312, 2233, 12, 203, 7734, 527, 12, 9156, 6031, 4926, 16, 6580, 3631, 203, 7734, 471, 12, 869, 16, 374, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 13, 203, 203, 5411, 745, 1482, 519, 745, 12, 31604, 9334, 1147, 16, 374, 16, 4843, 6031, 4926, 16, 2130, 16, 374, 16, 374, 13, 203, 3639, 289, 203, 203, 3639, 2583, 12, 203, 5411, 5061, 3024, 6542, 990, 1477, 55, 5286, 5288, 12, 1991, 1482, 3631, 203, 5411, 315, 16596, 6553, 67, 11249, 67, 11965, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x8D506fbAb52d3982f32d23E3A8c987F83ae4E792/sources/contracts/ccip/Recoverable.sol
* @notice Allows the owner to recover eth sent to the contract by mistake @param _recipient: recipient @dev Callable by owner/
function recoverEth(address payable _recipient) external onlyOwner { uint256 balance = address(this).balance; require(balance != 0, "Cannot recover zero balance"); Address.sendValue(_recipient, balance); }
8,812,448
[ 1, 19132, 326, 3410, 358, 5910, 13750, 3271, 358, 326, 6835, 635, 27228, 911, 225, 389, 20367, 30, 8027, 225, 10464, 635, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 41, 451, 12, 2867, 8843, 429, 389, 20367, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 2583, 12, 12296, 480, 374, 16, 315, 4515, 5910, 3634, 11013, 8863, 203, 203, 3639, 5267, 18, 4661, 620, 24899, 20367, 16, 11013, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./EpochUtils.sol"; import "./interfaces/IGetterUtils.sol"; /// @title Contract where getters and some convenience methods are implemented /// for the API3 pool contract GetterUtils is EpochUtils, IGetterUtils { /// @param api3TokenAddress Address of the API3 token contract /// @param epochPeriodInSeconds Length of epochs used to quantize time /// @param firstEpochStartTimestamp Starting timestamp of epoch #1 constructor( address api3TokenAddress, uint256 epochPeriodInSeconds, uint256 firstEpochStartTimestamp ) EpochUtils( api3TokenAddress, epochPeriodInSeconds, firstEpochStartTimestamp ) public {} /// @notice Returns the amount of funds the user has pooled /// @param userAddress User address function getPooled(address userAddress) public view override returns(uint256 pooled) { pooled = shares[userAddress].mul(totalPooled).div(totalShares); } /// @notice Calculates how many shares an amount of tokens corresponds to /// @param amount Amount of funds function convertToShares(uint256 amount) internal view returns(uint256 amountInShares) { amountInShares = amount.mul(totalShares).div(totalPooled); } /// @notice Calculates how many tokens an amount of shares corresponds to /// @param amountInShares Amount in shares function convertFromShares(uint256 amountInShares) internal view returns(uint256 amount) { amount = amountInShares.mul(totalPooled).div(totalShares); } /// @notice Returns the amount of voting power a delegate has at a given /// timestamp /// @dev Total voting power of all delegates adds up to 1e18 /// @param delegate Delegate address /// @param timestamp Timestamp function getVotingPower( address delegate, uint256 timestamp ) external view override returns(uint256 votingPower) { uint256 epochIndex = getEpochIndex(timestamp); votingPower = delegatedAtEpoch[delegate][epochIndex] .mul(1e18).div(totalStakedAtEpoch[epochIndex]); } /// @notice Returns the total pooled funds minus ghost funds. This is /// needed because ghost funds may be removed as IOUs are redeemed, and /// thus cannot be considered as collateral reliably. /// @return totalRealPooled Total pooled funds minus ghost funds function getTotalRealPooled() public view override returns(uint256 totalRealPooled) { totalRealPooled = totalPooled.sub(convertFromShares(totalGhostShares)); } /// @notice Returns the user balance. Includes vested and uvested funds, /// but not IOUs. /// @param userAddress User address /// @return balance User balance function getBalance(address userAddress) external view override returns(uint256 balance) { balance = balances[userAddress]; } /// @notice Returns the number of shares the user has pooled /// @param userAddress User address /// @return share Number of shares function getShare(address userAddress) external view override returns(uint256 share) { share = shares[userAddress]; } /// @notice Returns the epoch when the user has made their last unpooling /// request /// @param userAddress User address /// @return unpoolRequestEpoch The epoch when the user has made their last /// unpooling request function getUnpoolRequestEpoch(address userAddress) external view override returns(uint256 unpoolRequestEpoch) { unpoolRequestEpoch = unpoolRequestEpochs[userAddress]; } /// @notice Returns the total number of shares staked at epochIndex /// @param epochIndex Epoch index /// @return totalStaked Total number of shares staked function getTotalStaked(uint256 epochIndex) external view override returns(uint256 totalStaked) { totalStaked = totalStakedAtEpoch[epochIndex]; } /// @notice Returns the total number of shares the user has staked at /// epochIndex /// @param userAddress User address /// @param epochIndex Epoch index /// @return staked Number of shares the user has staked function getStaked( address userAddress, uint256 epochIndex ) external view override returns(uint256 staked) { staked = stakedAtEpoch[userAddress][epochIndex]; } /// @notice Returns the delegate of the user /// @dev 0 being returned means the user is their own delegate /// @param userAddress User address /// @return delegate The address that will vote on behalf of the user function getDelegate(address userAddress) external view override returns(address delegate) { delegate = delegates[userAddress]; } /// @notice Returns the delegated voting power of the delegate /// @param delegate Delegate address /// @param epochIndex Epoch index /// @return delegated Delegated voting power function getDelegated( address delegate, uint256 epochIndex ) external view override returns(uint256 delegated) { delegated = delegatedAtEpoch[delegate][epochIndex]; } /// @notice Returns the vested rewards that will be distributed at /// epochIndex /// @param epochIndex Epoch index /// @return vestedRewards Vested rewards function getVestedRewards(uint256 epochIndex) external view override returns(uint256 vestedRewards) { vestedRewards = vestedRewardsAtEpoch[epochIndex]; } /// @notice Returns the vested rewards that has not been distributed at /// epochIndex yet /// @param epochIndex Epoch index /// @return unpaidVestedRewards Unpaid vested rewards function getUnpaidVestedRewards(uint256 epochIndex) external view override returns(uint256 unpaidVestedRewards) { unpaidVestedRewards = unpaidVestedRewardsAtEpoch[epochIndex]; } /// @notice Returns the instant rewards that will be distributed at /// epochIndex /// @param epochIndex Epoch index /// @return instantRewards Instant rewards function getInstantRewards(uint256 epochIndex) external view override returns(uint256 instantRewards) { instantRewards = instantRewardsAtEpoch[epochIndex]; } /// @notice Returns the instant rewards that has not been distributed at /// epochIndex yet /// @param epochIndex Epoch index /// @return unpaidInstantRewards Unpaid instant rewards function getUnpaidInstantRewards(uint256 epochIndex) external view override returns(uint256 unpaidInstantRewards) { unpaidInstantRewards = unpaidInstantRewardsAtEpoch[epochIndex]; } /// @notice Returns the vesting /// @param vestingId Vesting ID /// @return userAddress User address /// @return amount Number of tokens to be vested /// @return epoch Index of the epoch when the funds will be /// available function getVesting(bytes32 vestingId) external view override returns( address userAddress, uint256 amount, uint256 epoch ) { Vesting memory vesting = vestings[vestingId]; userAddress = vesting.userAddress; amount = vesting.amount; epoch = vesting.epoch; } /// @notice Returns the total funds of the user locked by vestings /// @param userAddress User address /// @return unvestedFund Total funds of the user locked by vestings function getUnvestedFund(address userAddress) external view override returns(uint256 unvestedFund) { unvestedFund = unvestedFunds[userAddress]; } /// @notice Returns the claim /// @param claimId Claim ID /// @return beneficiary Address that will receive the payout upon /// acceptance of the claim /// @return amount Payout amount /// @return status Claim status function getClaim(bytes32 claimId) external view override returns( address beneficiary, uint256 amount, ClaimStatus status ) { Claim memory claim = claims[claimId]; beneficiary = claim.beneficiary; amount = claim.amount; status = claim.status; } /// @notice Returns the array of active claim IDs /// @return _activeClaims Array of active claim IDs function getActiveClaims() external view override returns(bytes32[] memory _activeClaims) { _activeClaims = activeClaims; } /// @notice Returns the IOU /// @param iouId IOU ID /// @return userAddress User address that will receive the IOU payment if /// redemptionCondition is met /// @return amountInShares Amount that will be paid in shares if /// redemptionCondition is met /// @return claimId Claim ID /// @return redemptionCondition Claim status needed for payment to be made function getIou(bytes32 iouId) external view override returns( address userAddress, uint256 amountInShares, bytes32 claimId, ClaimStatus redemptionCondition ) { Iou memory iou = ious[iouId]; userAddress = iou.userAddress; amountInShares = iou.amountInShares; claimId = iou.claimId; redemptionCondition = iou.redemptionCondition; } }
@notice Returns the vested rewards that will be distributed at epochIndex @param epochIndex Epoch index @return vestedRewards Vested rewards
function getVestedRewards(uint256 epochIndex) external view override returns(uint256 vestedRewards) { vestedRewards = vestedRewardsAtEpoch[epochIndex]; }
966,911
[ 1, 1356, 326, 331, 3149, 283, 6397, 716, 903, 506, 16859, 622, 7632, 1016, 225, 7632, 1016, 512, 6127, 770, 327, 331, 3149, 17631, 14727, 776, 3149, 283, 6397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11031, 3149, 17631, 14727, 12, 11890, 5034, 7632, 1016, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 12, 11890, 5034, 331, 3149, 17631, 14727, 13, 203, 565, 288, 203, 3639, 331, 3149, 17631, 14727, 273, 331, 3149, 17631, 14727, 861, 14638, 63, 12015, 1016, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/lib/zeppelin/math/SafeMath.sol"; contract VotingApp is AragonApp { using SafeMath for uint256; // Events event Increment(address indexed entity, uint256 step); event Decrement(address indexed entity, uint256 step); event VotePass(); // Tracks the vote // TODO: make this signed uint256 public value; // Voting Increment uint256 public step; // Threshold uint256 public goal = 10; // Tracks accounts that have voted mapping(address => bool) public voters; // Tracks vote passed bool public votePassed; /// ACL bytes32 constant public VOTING_ROLE = keccak256("VOTING_ROLE"); /** * @notice Decrement the counter by `step` */ function incrementVote(uint256 step) auth(VOTING_ROLE) external { // require(!voters[msg.sender]); // require(!votePassed); value = value.add(step); Increment(msg.sender, step); if(value >= goal) { votePassed = true; VotePass(); // TODO: Forward an action here... } } /** * @notice Decrement the counter by `step` */ function decrementVote(uint256 step) auth(VOTING_ROLE) external { // require(!voters[msg.sender]); // require(!votePassed); value = value.sub(step); Decrement(msg.sender, step); } }
Events Tracks the vote TODO: make this signed Voting Increment Threshold Tracks accounts that have voted Tracks vote passed
contract VotingApp is AragonApp { using SafeMath for uint256; event Increment(address indexed entity, uint256 step); event Decrement(address indexed entity, uint256 step); event VotePass(); uint256 public value; uint256 public step; uint256 public goal = 10; mapping(address => bool) public voters; bool public votePassed; bytes32 constant public VOTING_ROLE = keccak256("VOTING_ROLE"); function incrementVote(uint256 step) auth(VOTING_ROLE) external { value = value.add(step); Increment(msg.sender, step); if(value >= goal) { votePassed = true; VotePass(); } } function incrementVote(uint256 step) auth(VOTING_ROLE) external { value = value.add(step); Increment(msg.sender, step); if(value >= goal) { votePassed = true; VotePass(); } } function decrementVote(uint256 step) auth(VOTING_ROLE) external { value = value.sub(step); Decrement(msg.sender, step); } }
12,652,016
[ 1, 3783, 11065, 87, 326, 12501, 2660, 30, 1221, 333, 6726, 776, 17128, 17883, 27139, 11065, 87, 9484, 716, 1240, 331, 16474, 11065, 87, 12501, 2275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 776, 17128, 3371, 353, 1201, 346, 265, 3371, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 17883, 12, 2867, 8808, 1522, 16, 2254, 5034, 2235, 1769, 203, 565, 871, 31073, 475, 12, 2867, 8808, 1522, 16, 2254, 5034, 2235, 1769, 203, 565, 871, 27540, 6433, 5621, 203, 203, 565, 2254, 5034, 1071, 460, 31, 203, 565, 2254, 5034, 1071, 2235, 31, 203, 565, 2254, 5034, 1071, 17683, 273, 1728, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 331, 352, 414, 31, 203, 565, 1426, 1071, 12501, 22530, 31, 203, 203, 565, 1731, 1578, 5381, 1071, 776, 1974, 1360, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 58, 1974, 1360, 67, 16256, 8863, 203, 203, 565, 445, 5504, 19338, 12, 11890, 5034, 2235, 13, 1357, 12, 58, 1974, 1360, 67, 16256, 13, 3903, 288, 203, 203, 3639, 460, 273, 460, 18, 1289, 12, 4119, 1769, 203, 203, 3639, 17883, 12, 3576, 18, 15330, 16, 2235, 1769, 203, 203, 3639, 309, 12, 1132, 1545, 17683, 13, 288, 203, 5411, 12501, 22530, 273, 638, 31, 203, 5411, 27540, 6433, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 5504, 19338, 12, 11890, 5034, 2235, 13, 1357, 12, 58, 1974, 1360, 67, 16256, 13, 3903, 288, 203, 203, 3639, 460, 273, 460, 18, 1289, 12, 4119, 1769, 203, 203, 3639, 17883, 12, 3576, 18, 15330, 16, 2235, 1769, 203, 203, 3639, 309, 12, 1132, 1545, 17683, 13, 288, 203, 5411, 12501, 22530, 273, 638, 31, 203, 5411, 2 ]
pragma solidity ^0.5.0; library SafeMath{ /** * Returns the addition of two unsigned integers, reverting on * overflow. * * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * - 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; } } contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner,"ERC20: Required Owner !"); _; } function transferOwnership(address newOwner) onlyOwner public { require (newOwner != address(0),"ERC20 New Owner cannot be zero address"); owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external ; } contract TOKENERC20 { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; /* This generates a public event on the blockchain that will notify clients */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) private _allowance; mapping (address => bool) public LockList; mapping (address => uint256) public LockedTokens; // 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); /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { uint256 stage; require(_from != address(0), "ERC20: transfer from the zero address"); require(_to != address(0), "ERC20: transfer to the zero address"); // Prevent transfer to 0x0 address. Use burn() instead require (LockList[msg.sender] == false,"ERC20: Caller Locked !"); // Check if msg.sender is locked or not require (LockList[_from] == false, "ERC20: Sender Locked !"); require (LockList[_to] == false,"ERC20: Receipient Locked !"); // Check if sender balance is locked stage=balanceOf[_from].sub(_value, "ERC20: transfer amount exceeds balance"); require (stage >= LockedTokens[_from],"ERC20: transfer amount exceeds Senders Locked Amount"); //Deduct and add balance balanceOf[_from]=stage; balanceOf[_to]=balanceOf[_to].add(_value,"ERC20: Addition overflow"); //emit Transfer event emit Transfer(_from, _to, _value); } /** * 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"); _allowance[owner][_spender] = amount; emit Approval(owner, _spender, amount); } /** * 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){ _transfer(msg.sender, _to, _value); return true; } function burn(uint256 _value) public returns(bool){ require (LockList[msg.sender] == false,"ERC20: User Locked !"); uint256 stage; stage=balanceOf[msg.sender].sub(_value, "ERC20: transfer amount exceeds balance"); require (stage >= LockedTokens[msg.sender],"ERC20: transfer amount exceeds Senders Locked Amount"); balanceOf[msg.sender]=balanceOf[msg.sender].sub(_value,"ERC20: Burn amount exceeds balance."); totalSupply=totalSupply.sub(_value,"ERC20: Burn amount exceeds total supply"); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param Account address * * @param _value the amount of money to burn * * Safely check if total supply is not overdrawn */ function burnFrom(address Account, uint256 _value) public returns (bool success) { require (LockList[msg.sender] == false,"ERC20: User Locked !"); require (LockList[Account] == false,"ERC20: Owner Locked !"); uint256 stage; require(Account != address(0), "ERC20: Burn from the zero address"); //Safely substract amount to be burned from callers allowance _approve(Account, msg.sender, _allowance[Account][msg.sender].sub(_value,"ERC20: burn amount exceeds allowance")); //Do not allow burn if Accounts tokens are locked. stage=balanceOf[Account].sub(_value,"ERC20: Transfer amount exceeds allowance"); require(stage>=LockedTokens[Account],"ERC20: Burn amount exceeds accounts locked amount"); balanceOf[Account] =stage ; // Subtract from the sender //Deduct burn amount from totalSupply totalSupply=totalSupply.sub(_value,"ERC20: Burn Amount exceeds totalSupply"); emit Burn(Account, _value); emit Transfer(Account, address(0), _value); return true; } /** * 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) { _transfer(_from, _to, _value); _approve(_from,msg.sender,_allowance[_from][msg.sender].sub(_value,"ERC20: transfer amount exceeds allowance")); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * Emits Approval Event * @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) { uint256 unapprovbal; // Do not allow approval if amount exceeds locked amount unapprovbal=balanceOf[msg.sender].sub(_value,"ERC20: Allowance exceeds balance of approver"); require(unapprovbal>=LockedTokens[msg.sender],"ERC20: Approval amount exceeds locked amount "); _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } function allowance(address _owner,address _spender) public view returns(uint256){ return _allowance[_owner][_spender]; } } contract StreamCoin is owned, TOKENERC20 { /* Initializes contract with initial supply tokens to the creator of the contract */ constructor () TOKENERC20( 100000000000 * 1 ** uint256(decimals), "Stream Coin", "STRM") public { } /** * User Lock * * @param Account the address of account to lock for transaction * * @param mode true or false for lock mode * */ function UserLock(address Account, bool mode) onlyOwner public { LockList[Account] = mode; } /** * Lock tokens * * @param Account the address of account to lock * * @param amount the amount of money to lock * * */ function LockTokens(address Account, uint256 amount) onlyOwner public{ LockedTokens[Account]=amount; } function UnLockTokens(address Account) onlyOwner public{ LockedTokens[Account]=0; } }
Subtract from the sender
balanceOf[Account] =stage ;
1,290,582
[ 1, 27904, 628, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 11013, 951, 63, 3032, 65, 273, 12869, 274, 2398, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Corporation SmartContract. developed by: cryptonomica.net, 2016 used sources: https://www.ethereum.org/token // example of the token standart https://github.com/ethereum/EIPs/issues/20 // token standart description https://www.ethereum.org/dao // voting example */ /* How to deploy (estimated: 1,641,268 gas): 1) For development: use https://ethereum.github.io/browser-solidity/ 2) For testing on Testnet: Open the default (&#39;Mist&#39;) wallet (if you are only testing, go to the menu develop > network > testnet), go to the Contracts tab and then press deploy contract, and on the solidity code box, paste the code above. 3) For prodaction, like in 2) but on Main Network. To verify your deployed smartcontract source code for public go to: https://etherscan.io/verifyContract */ // &#39;interface&#39;: // this is expected from another contract, // if it wants to spend tokens (shares) of behalf of the token owner // in our contract // f.e.: a &#39;multisig&#39; SmartContract for transfering shares from seller // to buyer contract tokenRecipient { function receiveApproval(address _from, // sharehoder uint256 _value, // number of shares address _share, // - will be this contract bytes _extraData); // } contract Corporation { /* Standard public variables of the token */ string public standard = &#39;Token 0.1&#39;; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* ------------------- Corporate Stock Ledger ---------- */ // Shares, shareholders, balances ect. // list of all sharehoders (represented by Ethereum accounts) // in this Corporation&#39;s history, # is ID address[] public shareholder; // this helps to find address by ID without loop mapping (address => uint256) public shareholderID; // list of adresses, that who currently own at least share // not public, use getCurrentShareholders() address[] activeShareholdersArray; // balances: mapping (address => uint256) public balanceOf; // shares that have to be managed by external contract mapping (address => mapping (address => uint256)) public allowance; /* --------------- Constructor --------- */ // Initializes contract with initial supply tokens to the creator of the contract function Corporation () { // - truffle compiles only no args Constructor uint256 initialSupply = 12000; // shares quantity, constant balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = &quot;shares&quot;; //tokenName; // Set the name for display purposes symbol = &quot;sh&quot;; // tokenSymbol; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes // -- start corporate stock ledger shareholderID[this] = shareholder.push(this)-1; // # 0 shareholderID[msg.sender] = shareholder.push(msg.sender)-1; // #1 activeShareholdersArray.push(msg.sender); // add to active shareholders } /* --------------- Shares management ------ */ // This generates a public event on the blockchain that will notify clients. In &#39;Mist&#39; SmartContract page enable &#39;Watch contract events&#39; event Transfer(address indexed from, address indexed to, uint256 value); function getCurrentShareholders() returns (address[]){ delete activeShareholdersArray; for (uint256 i=0; i < shareholder.length; i++){ if (balanceOf[shareholder[i]] > 0){ activeShareholdersArray.push(shareholder[i]); } } return activeShareholdersArray; } /* -- can be used to transfer shares to new contract together with getCurrentShareholders() */ function getBalanceByAdress(address _address) returns (uint256) { return balanceOf[_address]; } function getMyShareholderID() returns (uint256) { return shareholderID[msg.sender]; } function getShareholderAdressByID(uint256 _id) returns (address){ return shareholder[_id]; } function getMyShares() returns (uint256) { return balanceOf[msg.sender]; } /* ---- Transfer shares to another adress ---- (shareholder&#39;s address calls this) */ function transfer(address _to, uint256 _value) { // check arguments: if (_value < 1) throw; if (this == _to) throw; // do not send shares to contract itself; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough // make transaction balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient // if new address, add it to shareholders history (stock ledger): if (shareholderID[_to] == 0){ // ----------- check if works shareholderID[_to] = shareholder.push(_to)-1; } // Notify anyone listening that this transfer took place Transfer(msg.sender, _to, _value); } /* Allow another contract to spend some shares in your behalf (shareholder calls this) */ function approveAndCall(address _spender, // another contract&#39;s adress uint256 _value, // number of shares bytes _extraData) // data for another contract returns (bool success) { // msg.sender - account owner who gives allowance // _spender - address of another contract // it writes in &quot;allowance&quot; that this owner allows another // contract (_spender) to spend thi amont (_value) of shares // in his behalf allowance[msg.sender][_spender] = _value; // &#39;spender&#39; is another contract that implements code // prescribed in &#39;shareRecipient&#39; above tokenRecipient spender = tokenRecipient(_spender); // this contract calls &#39;receiveApproval&#39; function // of another contract to send information about // allowance spender.receiveApproval(msg.sender, // shares owner _value, // number of shares this, // this contract&#39;s adress _extraData);// data from shares owner return true; } /* this function can be called from another contract, after it have allowance to transfer shares in behalf of sharehoder */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { // Check arguments: // should one share or more if (_value < 1) throw; // do not send shares to this contract itself; if (this == _to) throw; // Check if the sender has enough if (balanceOf[_from] < _value) throw; // Check allowance if (_value > allowance[_from][msg.sender]) throw; // if transfer to new address -- add him to ledger if (shareholderID[_to] == 0){ shareholderID[_to] = shareholder.push(_to)-1; // push function returns the new length } // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; // Change allowances correspondingly allowance[_from][msg.sender] -= _value; // Notify anyone listening that this transfer took place Transfer(_from, _to, _value); return true; } /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } /* --------- Voting -------------- */ // we only count &#39;yes&#39; votes, not voting &#39;yes&#39; // considered as voting &#39;no&#39; (as stated in Bylaws) // each proposal should contain it&#39;s text // index of text in this array is a proposal ID string[] public proposalText; // proposalID => (shareholder => &quot;if already voted for this proposal&quot;) mapping (uint256 => mapping (address => bool)) voted; // proposalID => addresses voted &#39;yes&#39; // exact number of votes according to shares will be counted // after deadline mapping (uint256 => address[]) public votes; // proposalID => deadline mapping (uint256 => uint256) public deadline; // proposalID => final &#39;yes&#39; votes mapping (uint256 => uint256) public results; // proposals of every shareholder mapping (address => uint256[]) public proposalsByShareholder; event ProposalAdded(uint256 proposalID, address initiator, string description, uint256 deadline); event VotingFinished(uint256 proposalID, uint256 votes); function makeNewProposal(string _proposalDescription, uint256 _debatingPeriodInMinutes) returns (uint256){ // only shareholder with one or more shares can make a proposal // !!!! can be more then one share required if (balanceOf[msg.sender] < 1) throw; uint256 id = proposalText.push(_proposalDescription)-1; deadline[id] = now + _debatingPeriodInMinutes * 1 minutes; // add to proposals of this shareholder: proposalsByShareholder[msg.sender].push(id); // initiator always votes &#39;yes&#39; votes[id].push(msg.sender); voted[id][msg.sender] = true; ProposalAdded(id, msg.sender, _proposalDescription, deadline[id]); return id; // returns proposal id } function getMyProposals() returns (uint256[]){ return proposalsByShareholder[msg.sender]; } function voteForProposal(uint256 _proposalID) returns (string) { // if no shares currently owned - no right to vote if (balanceOf[msg.sender] < 1) return &quot;no shares, vote not accepted&quot;; // if already voted - throw, else voting can be spammed if (voted[_proposalID][msg.sender]){ return &quot;already voted, vote not accepted&quot;; } // no votes after deadline if (now > deadline[_proposalID] ){ return &quot;vote not accepted after deadline&quot;; } // add to list of voted &#39;yes&#39; votes[_proposalID].push(msg.sender); voted[_proposalID][msg.sender] = true; return &quot;vote accepted&quot;; } // to count votes this transaction should be started manually // from _any_ Ethereum address after deadline function countVotes(uint256 _proposalID) returns (uint256){ // if not after deadline - throw if (now < deadline[_proposalID]) throw; // if already counted return result; if (results[_proposalID] > 0) return results[_proposalID]; // else should count results and store in public variable uint256 result = 0; for (uint256 i = 0; i < votes[_proposalID].length; i++){ address voter = votes[_proposalID][i]; result = result + balanceOf[voter]; } // Log and notify anyone listening that this voting finished // with &#39;result&#39; - number of &#39;yes&#39; votes VotingFinished(_proposalID, result); return result; } }
no votes after deadline
if (now > deadline[_proposalID] ){ return &quot;vote not accepted after deadline&quot;; } voted[_proposalID][msg.sender] = true; return &quot;vote accepted&quot;;
12,829,260
[ 1, 2135, 19588, 1839, 14096, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 3338, 405, 14096, 63, 67, 685, 8016, 734, 65, 262, 95, 203, 5411, 327, 473, 9270, 31, 25911, 486, 8494, 1839, 14096, 10, 9270, 25708, 203, 3639, 289, 203, 203, 3639, 331, 16474, 63, 67, 685, 8016, 734, 6362, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 327, 473, 9270, 31, 25911, 8494, 10, 9270, 25708, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY39() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF342(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER892(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE335(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE49(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM790(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER356(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL503(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER272() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA393() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY39() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF342(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER892(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER337(_MSGSENDER272(), recipient, amount); return true; } function ALLOWANCE335(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE49(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, amount); return true; } function TRANSFERFROM790(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER337(sender, recipient, amount); _APPROVE27(sender, _MSGSENDER272(), _allowances[sender][_MSGSENDER272()].SUB956(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE743(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, _allowances[_MSGSENDER272()][spender].ADD786(addedValue)); return true; } function DECREASEALLOWANCE224(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, _allowances[_MSGSENDER272()][spender].SUB956(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER337(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB956(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD786(amount); emit TRANSFER356(sender, recipient, amount); } function _MINT977(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD786(amount); _balances[account] = _balances[account].ADD786(amount); emit TRANSFER356(address(0), account, amount); } function _BURN905(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB956(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB956(amount); emit TRANSFER356(account, address(0), amount); } function _APPROVE27(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL503(owner, spender, amount); } function _BURNFROM541(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN905(account, amount); _APPROVE27(account, _MSGSENDER272(), _allowances[account][_MSGSENDER272()].SUB956(amount, "ERC20: burn amount exceeds allowance")); } } library SafeMath { function ADD786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB956(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB956(a, b, "SafeMath: subtraction overflow"); } function SUB956(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 MUL88(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV343(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV343(a, b, "SafeMath: division by zero"); } function DIV343(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; return c; } function MOD197(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD197(a, b, "SafeMath: modulo by zero"); } function MOD197(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT818(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE126(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE5(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER46(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.TRANSFER892.selector, to, value)); } function SAFETRANSFERFROM146(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.TRANSFERFROM790.selector, from, to, value)); } function SAFEAPPROVE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE335(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, value)); } function SAFEINCREASEALLOWANCE235(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE335(address(this), spender).ADD786(value); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE541(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE335(address(this), spender).SUB956(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, newAllowance)); } function CALLOPTIONALRETURN200(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT818(), "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"); } } } contract pLINKVault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct RewardDivide { mapping (address => uint256) amount; uint256 time; } IERC20 public token = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); address public governance; uint256 public totalDeposit; mapping(address => uint256) public depositBalances; mapping(address => uint256) public rewardBalances; address[] public addressIndices; mapping(uint256 => RewardDivide) public _rewards; uint256 public _rewardCount = 0; event WITHDRAWN459(address indexed user, uint256 amount); //inject NONSTANDARD NAMING constructor () public { governance = msg.sender; } function BALANCE221() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF342(address(this)); } function SETGOVERNANCE269(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function DEPOSITALL567() external { //inject NONSTANDARD NAMING DEPOSIT500(token.BALANCEOF342(msg.sender)); } function DEPOSIT500(uint256 _amount) public { //inject NONSTANDARD NAMING require(_amount > 0, "can't deposit 0"); uint arrayLength = addressIndices.length; bool found = false; for (uint i = 0; i < arrayLength; i++) { if(addressIndices[i]==msg.sender){ found=true; break; } } if(!found){ addressIndices.push(msg.sender); } uint256 realAmount = _amount.MUL88(995).DIV343(1000); uint256 feeAmount = _amount.MUL88(5).DIV343(1000); address feeAddress = 0xD319d5a9D039f06858263E95235575Bb0Bd630BC; address vaultAddress = 0x32e4bD46e7cee1797b22B02c0340818B6e75C75a; // Vault7 Address token.SAFETRANSFERFROM146(msg.sender, feeAddress, feeAmount); token.SAFETRANSFERFROM146(msg.sender, vaultAddress, realAmount); totalDeposit = totalDeposit.ADD786(realAmount); depositBalances[msg.sender] = depositBalances[msg.sender].ADD786(realAmount); } function REWARD357(uint256 _amount) external { //inject NONSTANDARD NAMING require(_amount > 0, "can't reward 0"); require(totalDeposit > 0, "totalDeposit must bigger than 0"); token.SAFETRANSFERFROM146(msg.sender, address(this), _amount); uint arrayLength = addressIndices.length; for (uint i = 0; i < arrayLength; i++) { rewardBalances[addressIndices[i]] = rewardBalances[addressIndices[i]].ADD786(_amount.MUL88(depositBalances[addressIndices[i]]).DIV343(totalDeposit)); _rewards[_rewardCount].amount[addressIndices[i]] = _amount.MUL88(depositBalances[addressIndices[i]]).DIV343(totalDeposit); } _rewards[_rewardCount].time = block.timestamp; _rewardCount++; } function WITHDRAWALL757() external { //inject NONSTANDARD NAMING WITHDRAW270(rewardBalances[msg.sender]); } function WITHDRAW270(uint256 _amount) public { //inject NONSTANDARD NAMING require(_rewardCount > 0, "no reward amount"); require(_amount > 0, "can't withdraw 0"); uint256 availableWithdrawAmount = AVAILABLEWITHDRAW17(msg.sender); if (_amount > availableWithdrawAmount) { _amount = availableWithdrawAmount; } token.SAFETRANSFER46(msg.sender, _amount); rewardBalances[msg.sender] = rewardBalances[msg.sender].SUB956(_amount); emit WITHDRAWN459(msg.sender, _amount); } function AVAILABLEWITHDRAW17(address owner) public view returns(uint256){ //inject NONSTANDARD NAMING uint256 availableWithdrawAmount = rewardBalances[owner]; for (uint256 i = _rewardCount - 1; block.timestamp < _rewards[i].time.ADD786(7 days); --i) { availableWithdrawAmount = availableWithdrawAmount.SUB956(_rewards[i].amount[owner].MUL88(_rewards[i].time.ADD786(7 days).SUB956(block.timestamp)).DIV343(7 days)); if (i == 0) break; } return availableWithdrawAmount; } }
inject NONSTANDARD NAMING
function SETGOVERNANCE269(address _governance) public {
12,811,435
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7855, 43, 12959, 50, 4722, 5558, 29, 12, 2867, 389, 75, 1643, 82, 1359, 13, 1071, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x66cD884c1C56bf00616e8c26FD89a96CaaA12d4D/sources/Pepe025.sol
0.5% * 0.81 = 0.4%
uint256 public _maxTxAmount = 2103450000000 * 10**_decimals;
15,615,367
[ 1, 20, 18, 25, 9, 225, 374, 18, 11861, 273, 374, 18, 24, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 389, 1896, 4188, 6275, 273, 3639, 576, 2163, 25574, 17877, 380, 1728, 636, 67, 31734, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/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); function decimals() external view returns (uint8); /** * @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; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/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 Ownable is Context { address private _governance; event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _governance = msgSender; emit GovernanceTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function governance() public view returns (address) { return _governance; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_governance == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit GovernanceTransferred(_governance, newOwner); _governance = newOwner; } } // File: contracts/strategies/StabilizeStrategyUSTFlashArbV2.sol pragma solidity ^0.6.6; // This is a strategy that takes advantage of arb opportunities for ust // Users deposit ust into the strategy and the strategy will sell into usdt when above usdt and usdt into ust when below // Selling will occur via Uniswap or Curve and buying WETH via Uniswap // Half the profit earned from the sell will be used to buy WETH and split it between the treasury, executor and staking pool // Half will remain // This strategy also uses flash loans to take advantage of opportunities in price inversions between exchanges // Strategy takes into account 0.3% slippage estimate for large sells on Uniswap interface StabilizeStakingPool { function notifyRewardAmount(uint256) external; } interface UniswapRouter { function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory); function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory); function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out } interface CurvePool { function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens } interface LendingPoolAddressesProvider { function getLendingPool() external view returns (address); } interface LendingPool { function flashLoan(address, address[] calldata, uint256[] calldata, uint256[] calldata, address, bytes calldata params, uint16) external; } interface AggregatorV3Interface { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } contract StabilizeStrategyUSTFlashArbV2 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; address public treasuryAddress; // Address of the treasury address public stakingAddress; // Address to the STBZ staking pool address public zsTokenAddress; // The address of the controlling zs-Token uint256 constant DIVISION_FACTOR = 100000; uint256 public lastTradeTime = 0; uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw uint256 public maxPoolSize = 3000000e18; // The maximum amount of ust tokens this strategy can hold, 3 mil by default uint256 public percentTradeTrigger = 10000; // 10% change in value will trigger a trade uint256 public maxSlippage = 300; // 0.3% max slippage is ok uint256 public maxPercentSell = 80000; // 80% of the tokens are sold to the cheapest token if slippage is ok on Uni uint256 public maxAmountSell = 500000; // The maximum amount of tokens that can be sold at once uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains uint256 public percentExecutor = 10000; // 30000 = 30% of WETH goes to executor, 15% of total profit uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed uint256 public minTradeSplit = 20000; // If the balance is less than or equal to this, it trades the entire balance uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit uint256[3] private flashParams; // Global parameters guiding the flash loan setup uint256 constant minGain = 1e16; // Minimum amount of gain (0.01 coin) before buying WETH and splitting it // Token information // This strategy accepts frax and usdc struct TokenInfo { IERC20 token; // Reference of token uint256 decimals; // Decimals of token } TokenInfo[] private tokenList; // An array of tokens accepted as deposits // Strategy specific variables address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap address constant CURVE_UST_POOL = address(0x890f4e345B1dAED0367A877a1612f86A1f86985f); address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle address constant LENDING_POOL_ADDRESS_PROVIDER = address(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); // Provider for Aave addresses constructor( address _treasury, address _staking, address _zsToken ) public { treasuryAddress = _treasury; stakingAddress = _staking; zsTokenAddress = _zsToken; setupWithdrawTokens(); } // Initialization functions function setupWithdrawTokens() internal { // Start with UST IERC20 _token = IERC20(address(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals() }) ); // USDT _token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals() }) ); } // Modifier modifier onlyZSToken() { require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token"); _; } // Read functions function rewardTokensCount() external view returns (uint256) { return tokenList.length; } function rewardTokenAddress(uint256 _pos) external view returns (address) { require(_pos < tokenList.length,"No token at that position"); return address(tokenList[_pos].token); } function balance() public view returns (uint256) { return getNormalizedTotalBalance(address(this)); } function getNormalizedTotalBalance(address _address) public view returns (uint256) { uint256 _balance = 0; for(uint256 i = 0; i < tokenList.length; i++){ uint256 _bal = tokenList[i].token.balanceOf(_address); _bal = _bal.mul(1e18).div(10**tokenList[i].decimals); _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals } return _balance; } function withdrawTokenReserves() public view returns (address, uint256) { // This function will return the address and amount of frax, then usdc if(tokenList[0].token.balanceOf(address(this)) > 0){ return (address(tokenList[0].token), tokenList[0].token.balanceOf(address(this))); }else if(tokenList[1].token.balanceOf(address(this)) > 0){ return (address(tokenList[1].token), tokenList[1].token.balanceOf(address(this))); }else{ return (address(0), 0); // No balance } } // Write functions function enter() external onlyZSToken { deposit(false); } function exit() external onlyZSToken { // The ZS token vault is removing all tokens from this strategy withdraw(_msgSender(),1,1, false); } function deposit(bool nonContract) public onlyZSToken { // Only the ZS token can call the function // No trading is performed on deposit if(nonContract == true){ } lastActionBalance = balance(); require(lastActionBalance <= maxPoolSize,"This strategy has reached its maximum balance"); } function simulateExchange(address _inputToken, address _outputToken, uint256 _amount, bool _uniswap) internal view returns (uint256) { if(_uniswap == true){ // Possible Uniswap routes, UST / USDT, USDT / ETH UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS); address[] memory path; if(_inputToken == address(tokenList[0].token) && _outputToken == WETH_ADDRESS){ // Selling UST for WETH, must go through USDT path = new address[](3); path[0] = _inputToken; path[1] = address(tokenList[1].token); path[2] = _outputToken; }else{ path = new address[](2); path[0] = _inputToken; path[1] = _outputToken; } uint256[] memory estimates = router.getAmountsOut(_amount, path); _amount = estimates[estimates.length - 1]; // This is the amount of WETH returned return _amount; }else{ // We are swapping via curve CurvePool pool = CurvePool(CURVE_UST_POOL); int128 inCurve = 0; int128 outCurve = 0; if(_inputToken == address(tokenList[1].token)){inCurve = 3;} if(_outputToken == address(tokenList[1].token)){outCurve = 3;} return pool.get_dy_underlying(inCurve, outCurve, _amount); } } function exchange(address _inputToken, address _outputToken, uint256 _amount, bool _uniswap) internal { if(_uniswap == true){ // Possible Uniswap routes, UST / USDT, USDT / ETH UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS); address[] memory path; if(_inputToken == address(tokenList[0].token) && _outputToken == WETH_ADDRESS){ // Selling UST for WETH, must go through USDT path = new address[](3); path[0] = _inputToken; path[1] = address(tokenList[1].token); path[2] = _outputToken; }else{ path = new address[](2); path[0] = _inputToken; path[1] = _outputToken; } IERC20(_inputToken).safeApprove(UNISWAP_ROUTER_ADDRESS, 0); IERC20(_inputToken).safeApprove(UNISWAP_ROUTER_ADDRESS, _amount); router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token return; }else{ // We are swapping via curve CurvePool pool = CurvePool(CURVE_UST_POOL); int128 inCurve = 0; int128 outCurve = 0; if(_inputToken == address(tokenList[1].token)){inCurve = 3;} if(_outputToken == address(tokenList[1].token)){outCurve = 3;} IERC20(_inputToken).safeApprove(CURVE_UST_POOL, 0); IERC20(_inputToken).safeApprove(CURVE_UST_POOL, _amount); pool.exchange_underlying(inCurve, outCurve, _amount, 1); } } function getCheaperToken() internal view returns (uint256, uint256, bool) { // This will give us the ID of the cheapest token for both Uniswap and Curve // We will estimate the return for trading 10000 UST // The higher the return, the lower the price of the other token // It will also suggest which exchange we should use, Uniswap or Curve uint256 targetID_1 = 0; // Our target ID is UST first uint256 targetID_2 = 0; bool useUni = false; uint256 ustAmount = uint256(10000).mul(10**tokenList[0].decimals); // Now compare it to USDT on Uniswap uint256 estimate = simulateExchange(address(tokenList[0].token),address(tokenList[1].token),ustAmount,true); estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals); if(estimate > ustAmount){ // This token is worth less than the UST on Uniswap targetID_1 = 1; } // Now on Curve uint256 estimate2 = simulateExchange(address(tokenList[0].token),address(tokenList[1].token),ustAmount,false); estimate2 = estimate2.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals); if(estimate2 > ustAmount){ // This token is worth less than UST on curve targetID_2 = 1; } // Now determine which exchange offers the better rate between the two if(targetID_1 == targetID_2){ if(targetID_1 == 1){ // USDT is weaker token on both exchanges if(estimate2 >= estimate){ // Get more USDT from Curve useUni = false; }else{ useUni = true; } }else{ // UST is weaker token on both exchanges if(estimate2 > estimate){ // Get more UST from Uni useUni = true; }else{ useUni = false; } } }else{ if(targetID_1 == 0){ // When we flash loan to increase our USDT, sell it on Uni as it is more valuable on there useUni = true; }else{ // When we flash loan to increase our USDT, sell it on Curve as it is more valuable there useUni = false; } } return (targetID_1, targetID_2, useUni); } function estimateSellAtMaxSlippage(uint256 originID, uint256 targetID, uint256 _balance) internal view returns (uint256) { // This will estimate the amount that can be sold at the maximum slippage // We discover the price then compare it to the actual return // The estimate is based on a linear curve so not 100% representative of Uniswap but close enough // It will use a 0.1% sell to discover the price first uint256 minSellPercent = maxPercentSell.div(1000); uint256 _amount = _balance.mul(minSellPercent).div(DIVISION_FACTOR); if(_amount == 0){ return 0; } // Nothing to sell, can't calculate uint256 _maxReturn = simulateExchange(address(tokenList[originID].token), address(tokenList[targetID].token), _amount, true); _maxReturn = _maxReturn.mul(1000); // Without slippage, this would be our maximum return // Now calculate the slippage at the max percent _amount = _balance.mul(maxPercentSell).div(DIVISION_FACTOR); uint256 _return = simulateExchange(address(tokenList[originID].token), address(tokenList[targetID].token), _amount, true); if(_return >= _maxReturn){ // This shouldn't be possible return _amount; // Sell the entire amount } // Calculate slippage uint256 percentSlip = uint256(_maxReturn.mul(DIVISION_FACTOR)).sub(_return.mul(DIVISION_FACTOR)).div(_maxReturn); if(percentSlip <= maxSlippage){ return _amount; // This is less than our maximum slippage, sell it all } return _amount.mul(maxSlippage).div(percentSlip); // This will be the sell amount at max slip } function estimateFlashLoanResult(uint256 point1, uint256 point2, uint256 _amount) internal view returns (uint256) { // This will estimate the return of our flash loan minus the fee uint256 fee = _amount.mul(90).div(DIVISION_FACTOR); // This is the Aave fee (0.09%) uint256 gain = 0; if(point2 > point1){ // USL price is lower than USDT on Uniswap, while higher on Curve // Use the borrowed USDT to buy USL on Uniswap gain = simulateExchange(address(tokenList[1].token), address(tokenList[0].token), _amount, true); // Receive USL gain = simulateExchange(address(tokenList[0].token), address(tokenList[1].token), gain, false); // Receive USDT }else{ // USL price higher than USDT on Uniswap while lower on Curve gain = simulateExchange(address(tokenList[1].token), address(tokenList[0].token), _amount, false); // Receive USL gain = simulateExchange(address(tokenList[0].token), address(tokenList[1].token), gain, true); // Receive USDT } if(gain > _amount.add(fee)){ // Positive return on the flash gain = gain.sub(fee).sub(_amount); // Get the pure gain after returning the funds with a fee return gain; }else{ return 0; // Do not take out a flash loan as not enough gain } } function performFlashLoan(uint256 point1, uint256 point2, uint256 _amount) internal returns (uint256) { // Will call Aave uint256 flashGain = tokenList[1].token.balanceOf(address(this)); flashParams[0] = 1; // Authorize flash loan receiving flashParams[1] = point1; flashParams[2] = point2; // Call the flash loan LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool address[] memory assets = new address[](1); assets[0] = address(tokenList[1].token); uint256[] memory amounts = new uint256[](1); amounts[0] = _amount; // The amount we want to borrow uint256[] memory modes = new uint256[](1); modes[0] = 0; // Revert if fail to return funds bytes memory params = ""; lender.flashLoan(address(this), assets, amounts, modes, address(this), params, 0); flashParams[0] = 0; // Deactivate flash loan receiving uint256 newBal = tokenList[1].token.balanceOf(address(this)); require(newBal > flashGain, "Flash loan failed to increase balance"); flashGain = newBal.sub(flashGain); uint256 payout = flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR); if(payout > 0){ // Convert part to WETH exchange(address(tokenList[1].token), WETH_ADDRESS, payout, true); } return flashGain; } function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool) { require(flashParams[0] == 1, "No flash loan authorized on this contract"); address lendingPool = LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool(); require(_msgSender() == lendingPool, "Not called from Aave"); require(initiator == address(this), "Not Authorized"); // Prevent other contracts from calling this function if(params.length == 0){} // Removes the warning flashParams[0] = 0; // Prevent a replay; { // Create inner scope to prevent stack too deep error uint256 point1 = flashParams[1]; uint256 point2 = flashParams[2]; uint256 _bal; // Swap the amounts to earn more if(point2 > point1){ // USL price is lower than USDT on Uniswap, while higher on Curve // Use the borrowed USDT to buy USL on Uniswap _bal = tokenList[0].token.balanceOf(address(this)); exchange(address(tokenList[1].token), address(tokenList[0].token), amounts[0], true); // Receive USL _bal = tokenList[0].token.balanceOf(address(this)).sub(_bal); exchange(address(tokenList[0].token), address(tokenList[1].token), _bal, false); // Receive USDT }else{ // USL price higher than USDT on Uniswap while lower on Curve _bal = tokenList[0].token.balanceOf(address(this)); exchange(address(tokenList[1].token), address(tokenList[0].token), amounts[0], false); // Receive USL _bal = tokenList[0].token.balanceOf(address(this)).sub(_bal); exchange(address(tokenList[0].token), address(tokenList[1].token), _bal, true); // Receive USDT } } // Authorize Aave to pull funds from this contract // Approve the LendingPool contract allowance to *pull* the owed amount for(uint256 i = 0; i < assets.length; i++) { uint256 amountOwing = amounts[i].add(premiums[i]); IERC20(assets[i]).safeApprove(lendingPool, 0); IERC20(assets[i]).safeApprove(lendingPool, amountOwing); } return true; } function getFastGasPrice() internal view returns (uint256) { AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS); ( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer return uint256(intGasPrice); } function checkAndSwapTokens(address _executor) internal { lastTradeTime = now; // Now find our target token to sell into (uint256 targetID_1, uint256 targetID_2, bool useUniswap) = getCheaperToken(); // Normally both these values should point to the same ID uint256 targetID; if(targetID_1 == targetID_2){ targetID = targetID_1; }else{ // The fun part (flash laon) // Since prices are inverse between the exchanges // We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed // First determine borrow size at the max slippage uint256 maxBorrow = uint256(1000000).mul(10**tokenList[1].decimals); // Predict based on $1million maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow); // Now estimate the return of the flash loan if(estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow) > 2){ // Flash loan will be profitable, borrow the funds performFlashLoan(targetID_1, targetID_2, maxBorrow); // This will return USDT earned and exchange it for WETH } targetID = 0; // Sell whatever gains are possible for more UST } uint256 length = tokenList.length; // Now sell all the other tokens into this token uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase bool _expectIncrease = false; for(uint256 i = 0; i < length; i++){ if(i != targetID){ uint256 sellBalance = 0; uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals); uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){ // If balance is too small,sell all tokens at once sellBalance = tokenList[i].token.balanceOf(address(this)); }else{ if(useUniswap == true){ sellBalance = estimateSellAtMaxSlippage(i, targetID, tokenList[i].token.balanceOf(address(this))); // This will select a balance with a max slippage }else{ // Curve supports larger sells sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR); } } if(sellBalance > _maxTradeTarget){ // If greater than the maximum trade allowed, match it sellBalance = _maxTradeTarget; } uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination if(sellBalance > 0){ uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap); if(estimate > minReceiveBalance){ _expectIncrease = true; exchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap); } } } } uint256 _newBalance = balance(); if(_expectIncrease == true){ // There may be rare scenarios where we don't gain any by calling this function require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens"); } uint256 gain = _newBalance.sub(_totalBalance); IERC20 weth = IERC20(WETH_ADDRESS); uint256 _wethBalance = weth.balanceOf(address(this)); if(gain >= minGain || _wethBalance > 0){ // Minimum gain required to buy WETH is about 0.01 tokens if(gain >= minGain){ // Buy WETH from Uniswap with tokens uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR); sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){ // Sell some of our gained token for WETH exchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true); _wethBalance = weth.balanceOf(address(this)); } } if(_wethBalance > 0){ // Split the rest between the stakers and such // This is pure profit, figure out allocation // Split the amount sent to the treasury, stakers and executor if one exists if(_executor != address(0)){ // Executors will get a gas reimbursement in WETH and a percent of the remaining uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested if(gasFee > maxGasFee){ gasFee = maxGasFee; // Gas fee cannot be greater than the maximum } uint256 executorAmount = gasFee; if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){ executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point }else{ // Add the executor percent on top of gas fee executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); } if(executorAmount > 0){ weth.safeTransfer(_executor, executorAmount); _wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract } } if(_wethBalance > 0){ uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR); uint256 treasuryAmount = _wethBalance.sub(stakersAmount); if(treasuryAmount > 0){ weth.safeTransfer(treasuryAddress, treasuryAmount); } if(stakersAmount > 0){ if(stakingAddress != address(0)){ weth.safeTransfer(stakingAddress, stakersAmount); StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount); }else{ // No staking pool selected, just send to the treasury weth.safeTransfer(treasuryAddress, stakersAmount); } } } } } } function expectedProfit(bool inWETHForExecutor) external view returns (uint256) { // This view will return the amount of gain a forced swap will make on next call // Now find our target token to sell into (uint256 targetID_1, uint256 targetID_2, bool useUniswap) = getCheaperToken(); // Normally both these values should point to the same ID uint256 targetID; uint256 flashGain = 0; if(targetID_1 == targetID_2){ targetID = targetID_1; }else{ // The fun part (flash loan) // Since prices are inverse between the exchanges // We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed // First determine borrow size at the max slippage uint256 maxBorrow = uint256(1000000).mul(10**tokenList[1].decimals); // Predict based on $1million maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow); // Now estimate the return of the flash loan flashGain = estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow); if(flashGain > 0){ if(inWETHForExecutor == true){ flashGain = simulateExchange(address(tokenList[1].token), WETH_ADDRESS, flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR), true); }else{ // Normalize it flashGain = flashGain.mul(1e18).div(10**tokenList[1].decimals); } } targetID = 0; } uint256 length = tokenList.length; // Now simulate sell all the other tokens into this token uint256 _normalizedGain = 0; for(uint256 i = 0; i < length; i++){ if(i != targetID){ uint256 sellBalance = 0; uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals); uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){ // If balance is too small,sell all tokens at once sellBalance = tokenList[i].token.balanceOf(address(this)); }else{ if(useUniswap == true){ sellBalance = estimateSellAtMaxSlippage(i, targetID, tokenList[i].token.balanceOf(address(this))); // This will select a balance with a max slippage }else{ // Curve supports larger sells sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR); } } if(sellBalance > _maxTradeTarget){ // If greater than the maximum trade allowed, match it sellBalance = _maxTradeTarget; } uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination if(sellBalance > 0){ uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap); if(estimate > minReceiveBalance){ uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain _normalizedGain = _normalizedGain.add(_gain); } } } } if(inWETHForExecutor == false){ return _normalizedGain.add(flashGain); }else{ if(_normalizedGain.add(flashGain) == 0){ return 0; } // Calculate how much WETH the executor would make as profit uint256 estimate = flashGain; // WETH earned from flashloan if(_normalizedGain > 0){ uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR); sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount // Estimate output estimate = estimate.add(simulateExchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true)); } // Now calculate the amount going to the executor uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total }else{ estimate = estimate.sub(gasFee); // Subtract fee from remaining balance return estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); // Executor amount with fee added } } } function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) { require(balance() > 0, "There are no tokens in this strategy"); if(nonContract == true){ if( _share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){ checkAndSwapTokens(_depositor); } } uint256 withdrawAmount = 0; uint256 _balance = balance(); if(_share < _total){ uint256 _myBalance = _balance.mul(_share).div(_total); withdrawPerOrder(_depositor, _myBalance, false); // This will withdraw based on token price withdrawAmount = _myBalance; }else{ // We are all shares, transfer all withdrawPerOrder(_depositor, _balance, true); withdrawAmount = _balance; } lastActionBalance = balance(); return withdrawAmount; } // This will withdraw the tokens from the contract based on their order function withdrawPerOrder(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal { uint256 length = tokenList.length; if(_takeAll == true){ // Send the entire balance for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } for(uint256 i = 0; i < length; i++){ // Determine the balance left uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals); if(_normalizedBalance <= _withdrawAmount){ // Withdraw the entire balance of this token if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this))); } }else{ // Withdraw a partial amount of this token if(_withdrawAmount > 0){ // Convert the withdraw amount to the token's decimal amount uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18); _withdrawAmount = 0; tokenList[i].token.safeTransfer(_receiver, _balance); } break; // Nothing more to withdraw } } } function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external { // Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent"); require(_msgSender() == tx.origin, "Contracts cannot interact with this function"); checkAndSwapTokens(_executor); lastActionBalance = balance(); } // Governance functions function governanceSwapTokens() external onlyGovernance { // This is function that force trade tokens at anytime. It can only be called by governance checkAndSwapTokens(governance()); lastActionBalance = balance(); } // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; uint256[7] private _timelock_data; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used if(balance() > 0){ // Timelock only applies when balance exists require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met"); } _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Change the treasury address // -------------------- function startChangeTreasury(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) { treasuryAddress = _timelock_address; } // -------------------- // Change the staking address // -------------------- function startChangeStakingPool(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 3; _timelock_address = _address; } function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) { stakingAddress = _timelock_address; } // -------------------- // Change the zsToken address // -------------------- function startChangeZSToken(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 4; _timelock_address = _address; } function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) { zsTokenAddress = _timelock_address; } // -------------------- // Change the trading conditions used by the strategy // -------------------- function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _mSellAmount, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend, uint256 _pSlip) external onlyGovernance { // Changes a lot of trading parameters in one call require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000 && _pSlip <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 5; _timelock_data[0] = _pTradeTrigger; _timelock_data[1] = _pSellPercent; _timelock_data[2] = _minSplit; _timelock_data[3] = _maxStipend; _timelock_data[4] = _pMaxStipend; _timelock_data[5] = _pSlip; _timelock_data[6] = _mSellAmount; } function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) { percentTradeTrigger = _timelock_data[0]; maxPercentSell = _timelock_data[1]; minTradeSplit = _timelock_data[2]; gasStipend = _timelock_data[3]; maxPercentStipend = _timelock_data[4]; maxSlippage = _timelock_data[5]; maxAmountSell = _timelock_data[6]; } // -------------------- // Change the strategy allocations between the parties // -------------------- function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers, uint256 _maxPool) external onlyGovernance { // Changes strategy allocations in one call require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 6; _timelock_data[0] = _pDepositors; _timelock_data[1] = _pExecutor; _timelock_data[2] = _pStakers; _timelock_data[3] = _maxPool; } function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) { percentDepositor = _timelock_data[0]; percentExecutor = _timelock_data[1]; percentStakers = _timelock_data[2]; maxPoolSize = _timelock_data[3]; } // -------------------- }
Will call Aave Call the flash loan Convert part to WETH
function performFlashLoan(uint256 point1, uint256 point2, uint256 _amount) internal returns (uint256) { uint256 flashGain = tokenList[1].token.balanceOf(address(this)); flashParams[1] = point1; flashParams[2] = point2; address[] memory assets = new address[](1); assets[0] = address(tokenList[1].token); uint256[] memory amounts = new uint256[](1); uint256[] memory modes = new uint256[](1); bytes memory params = ""; lender.flashLoan(address(this), assets, amounts, modes, address(this), params, 0); uint256 newBal = tokenList[1].token.balanceOf(address(this)); require(newBal > flashGain, "Flash loan failed to increase balance"); flashGain = newBal.sub(flashGain); uint256 payout = flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR); if(payout > 0){ exchange(address(tokenList[1].token), WETH_ADDRESS, payout, true); } return flashGain; }
6,320,779
[ 1, 13670, 745, 432, 836, 3049, 326, 9563, 28183, 4037, 1087, 358, 678, 1584, 44, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3073, 11353, 1504, 304, 12, 11890, 5034, 1634, 21, 16, 2254, 5034, 1634, 22, 16, 2254, 5034, 389, 8949, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 9563, 43, 530, 273, 1147, 682, 63, 21, 8009, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 540, 203, 3639, 9563, 1370, 63, 21, 65, 273, 1634, 21, 31, 7010, 3639, 9563, 1370, 63, 22, 65, 273, 1634, 22, 31, 203, 540, 203, 540, 203, 3639, 1758, 8526, 3778, 7176, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 7176, 63, 20, 65, 273, 1758, 12, 2316, 682, 63, 21, 8009, 2316, 1769, 3639, 203, 540, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 540, 203, 3639, 2254, 5034, 8526, 3778, 12382, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 540, 203, 3639, 1731, 3778, 859, 273, 1408, 31, 203, 3639, 328, 2345, 18, 13440, 1504, 304, 12, 2867, 12, 2211, 3631, 7176, 16, 30980, 16, 12382, 16, 1758, 12, 2211, 3631, 859, 16, 374, 1769, 203, 540, 203, 3639, 2254, 5034, 394, 38, 287, 273, 1147, 682, 63, 21, 8009, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 2704, 38, 287, 405, 9563, 43, 530, 16, 315, 11353, 28183, 2535, 358, 10929, 11013, 8863, 203, 3639, 9563, 43, 530, 273, 394, 38, 287, 18, 1717, 12, 13440, 43, 530, 1769, 203, 3639, 2254, 5034, 293, 2012, 273, 9563, 43, 530, 18, 16411, 12, 11890, 2 ]
/** * @authors: [@mtsalenc] * @reviewers: [@clesaege] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity 0.5.17; /** * @title CappedMath * @dev Math operations with caps for under and overflow. */ library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(uint _a, uint _b) internal pure returns (uint) { // 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; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } /** * @authors: [@hbarcelos] * @reviewers: [@fnanni-0] * @auditors: [] * @bounties: [] * @deployments: [] */ /** * @title CappedMath * @dev Math operations with caps for under and overflow. */ library CappedMath128 { uint128 private constant UINT128_MAX = 2**128 - 1; /** * @dev Adds two unsigned integers, returns 2^128 - 1 on overflow. */ function addCap(uint128 _a, uint128 _b) internal pure returns (uint128) { uint128 c = _a + _b; return c >= _a ? c : UINT128_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint128 _a, uint128 _b) internal pure returns (uint128) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^128 - 1 on overflow. */ function mulCap(uint128 _a, uint128 _b) internal pure returns (uint128) { if (_a == 0) return 0; uint128 c = _a * _b; return c / _a == _b ? c : UINT128_MAX; } } /** * @authors: [@ferittuncer] * @reviewers: [@remedcu] * @auditors: [] * @bounties: [] * @deployments: [] */ /** @title IArbitrable * Arbitrable interface. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. * -Allow dispute creation. For this a function must call arbitrator.createDispute.value(_fee)(_choices,_extraData); */ interface IArbitrable { /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external; } /** * @authors: [@ferittuncer] * @reviewers: [@remedcu] * @auditors: [] * @bounties: [] * @deployments: [] */ /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). */ interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID); /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns(uint cost); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes calldata _extraData) external payable; /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint _disputeID) external view returns(uint start, uint end); /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) external view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) external view returns(uint ruling); } /** @title IEvidence * ERC-1497: Evidence Standard */ interface IEvidence { /** @dev To be emitted when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(IArbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); /** @dev To be emitted when a dispute is created to link the correct meta-evidence to the disputeID. * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); } /** * @authors: [@unknownunknown1*, @mtsalenc*, @hbarcelos*] * @reviewers: [@fnanni-0*, @greenlucid, @shalzz] * @auditors: [] * @bounties: [] * @deployments: [] */ /** * @title LightGeneralizedTCR * This contract is a curated registry for any types of items. Just like a TCR contract it features the request-challenge protocol and appeal fees crowdfunding. * The difference between LightGeneralizedTCR and GeneralizedTCR is that instead of storing item data in storage and event logs, LightCurate only stores the URI of item in the logs. This makes it considerably cheaper to use and allows more flexibility with the item columns. */ contract LightGeneralizedTCR is IArbitrable, IEvidence { using CappedMath for uint256; using CappedMath128 for uint128; /* Enums */ enum Status { Absent, // The item is not in the registry. Registered, // The item is in the registry. RegistrationRequested, // The item has a request to be added to the registry. ClearingRequested // The item has a request to be removed from the registry. } enum Party { None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling. Requester, // Party that made the request to change a status. Challenger // Party that challenges the request to change a status. } enum RequestType { Registration, // Identifies a request to register an item to the registry. Clearing // Identifies a request to remove an item from the registry. } enum DisputeStatus { None, // No dispute was created. AwaitingRuling, // Dispute was created, but the final ruling was not given yet. Resolved // Dispute was ruled. } /* Structs */ struct Item { Status status; // The current status of the item. uint128 sumDeposit; // The total deposit made by the requester and the challenger (if any). uint120 requestCount; // The number of requests. mapping(uint256 => Request) requests; // List of status change requests made for the item in the form requests[requestID]. } // Arrays with 3 elements map with the Party enum for better readability: // - 0: is unused, matches `Party.None`. // - 1: for `Party.Requester`. // - 2: for `Party.Challenger`. struct Request { RequestType requestType; uint64 submissionTime; // Time when the request was made. Used to track when the challenge period ends. uint24 arbitrationParamsIndex; // The index for the arbitration params for the request. address payable requester; // Address of the requester. // Pack the requester together with the other parameters, as they are written in the same request. address payable challenger; // Address of the challenger, if any. } struct DisputeData { uint256 disputeID; // The ID of the dispute on the arbitrator. DisputeStatus status; // The current status of the dispute. Party ruling; // The ruling given to a dispute. Only set after it has been resolved. uint240 roundCount; // The number of rounds. mapping(uint256 => Round) rounds; // Data of the different dispute rounds. rounds[roundId]. } struct Round { Party sideFunded; // Stores the side that successfully paid the appeal fees in the latest round. Note that if both sides have paid a new round is created. uint256 feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. uint256[3] amountPaid; // Tracks the sum paid for each Party in this round. mapping(address => uint256[3]) contributions; // Maps contributors to their contributions for each side in the form contributions[address][party]. } struct ArbitrationParams { IArbitrator arbitrator; // The arbitrator trusted to solve disputes for this request. bytes arbitratorExtraData; // The extra data for the trusted arbitrator of this request. } /* Constants */ uint256 public constant RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give. uint256 private constant RESERVED_ROUND_ID = 0; // For compatibility with GeneralizedTCR consider the request/challenge cycle the first round (index 0). /* Storage */ bool private initialized; address public relayerContract; // The contract that is used to add or remove items directly to speed up the interchain communication. address public governor; // The address that can make changes to the parameters of the contract. uint256 public submissionBaseDeposit; // The base deposit to submit an item. uint256 public removalBaseDeposit; // The base deposit to remove an item. uint256 public submissionChallengeBaseDeposit; // The base deposit to challenge a submission. uint256 public removalChallengeBaseDeposit; // The base deposit to challenge a removal request. uint256 public challengePeriodDuration; // The time after which a request becomes executable if not challenged. // Multipliers are in basis points. uint256 public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint256 public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint256 public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where arbitrator refused to arbitrate. uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. mapping(bytes32 => Item) public items; // Maps the item ID to its data in the form items[_itemID]. mapping(address => mapping(uint256 => bytes32)) public arbitratorDisputeIDToItemID; // Maps a dispute ID to the ID of the item with the disputed request in the form arbitratorDisputeIDToItemID[arbitrator][disputeID]. mapping(bytes32 => mapping(uint256 => DisputeData)) public requestsDisputeData; // Maps an item and a request to the data of the dispute related to them. requestsDisputeData[itemID][requestIndex] ArbitrationParams[] public arbitrationParamsChanges; /* Modifiers */ modifier onlyGovernor() { require(msg.sender == governor, "The caller must be the governor."); _; } modifier onlyRelayer() { require(msg.sender == relayerContract, "The caller must be the relay."); _; } /* Events */ /** * @dev Emitted when a party makes a request, raises a dispute or when a request is resolved. * @param _itemID The ID of the affected item. * @param _updatedDirectly Whether this was emitted in either `addItemDirectly` or `removeItemDirectly`. This is used in the subgraph. */ event ItemStatusChange(bytes32 indexed _itemID, bool _updatedDirectly); /** * @dev Emitted when someone submits an item for the first time. * @param _itemID The ID of the new item. * @param _data The item data URI. * @param _addedDirectly Whether the item was added via `addItemDirectly`. */ event NewItem(bytes32 indexed _itemID, string _data, bool _addedDirectly); /** * @dev Emitted when someone submits a request. * @param _itemID The ID of the affected item. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. */ event RequestSubmitted(bytes32 indexed _itemID, uint256 _evidenceGroupID); /** * @dev Emitted when a party contributes to an appeal. The roundID assumes the initial request and challenge deposits are the first round. This is done so indexers can know more information about the contribution without using call handlers. * @param _itemID The ID of the item. * @param _requestID The index of the request that received the contribution. * @param _roundID The index of the round that received the contribution. * @param _contributor The address making the contribution. * @param _contribution How much of the contribution was accepted. * @param _side The party receiving the contribution. */ event Contribution( bytes32 indexed _itemID, uint256 _requestID, uint256 _roundID, address indexed _contributor, uint256 _contribution, Party _side ); /** * @dev Emitted when the address of the connected TCR is set. The connected TCR is an instance of the Generalized TCR contract where each item is the address of a TCR related to this one. * @param _connectedTCR The address of the connected TCR. */ event ConnectedTCRSet(address indexed _connectedTCR); /** * @dev Emitted when someone withdraws more than 0 rewards. * @param _beneficiary The address that made contributions to a request. * @param _itemID The ID of the item submission to withdraw from. * @param _request The request from which to withdraw. * @param _round The round from which to withdraw. * @param _reward The amount withdrawn. */ event RewardWithdrawn( address indexed _beneficiary, bytes32 indexed _itemID, uint256 _request, uint256 _round, uint256 _reward ); /** * @dev Initialize the arbitrable curated registry. * @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _connectedTCR The address of the TCR that stores related TCR addresses. This parameter can be left empty. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. * @param _governor The trusted governor of this contract. * @param _baseDeposits The base deposits for requests/challenges as follows: * - The base deposit to submit an item. * - The base deposit to remove an item. * - The base deposit to challenge a submission. * - The base deposit to challenge a removal request. * @param _challengePeriodDuration The time in seconds parties have to challenge a request. * @param _stakeMultipliers Multipliers of the arbitration cost in basis points (see MULTIPLIER_DIVISOR) as follows: * - The multiplier applied to each party's fee stake for a round when there is no winner/loser in the previous round (e.g. when the arbitrator refused to arbitrate). * - The multiplier applied to the winner's fee stake for the subsequent round. * - The multiplier applied to the loser's fee stake for the subsequent round. * @param _relayerContract The address of the relay contract to add/remove items directly. */ function initialize( IArbitrator _arbitrator, bytes calldata _arbitratorExtraData, address _connectedTCR, string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence, address _governor, uint256[4] calldata _baseDeposits, uint256 _challengePeriodDuration, uint256[3] calldata _stakeMultipliers, address _relayerContract ) external { require(!initialized, "Already initialized."); emit ConnectedTCRSet(_connectedTCR); governor = _governor; submissionBaseDeposit = _baseDeposits[0]; removalBaseDeposit = _baseDeposits[1]; submissionChallengeBaseDeposit = _baseDeposits[2]; removalChallengeBaseDeposit = _baseDeposits[3]; challengePeriodDuration = _challengePeriodDuration; sharedStakeMultiplier = _stakeMultipliers[0]; winnerStakeMultiplier = _stakeMultipliers[1]; loserStakeMultiplier = _stakeMultipliers[2]; relayerContract = _relayerContract; _doChangeArbitrationParams(_arbitrator, _arbitratorExtraData, _registrationMetaEvidence, _clearingMetaEvidence); initialized = true; } /* External and Public */ // ************************ // // * Requests * // // ************************ // /** * @dev Directly add an item to the list bypassing request-challenge. Can only be used by the relay contract. * @param _item The URI to the item data. */ function addItemDirectly(string calldata _item) external onlyRelayer { bytes32 itemID = keccak256(abi.encodePacked(_item)); Item storage item = items[itemID]; require(item.status == Status.Absent, "Item must be absent to be added."); // Note that if the item is added directly once, the next time it is added it will emit this event again. if (item.requestCount == 0) { emit NewItem(itemID, _item, true); } item.status = Status.Registered; emit ItemStatusChange(itemID, true); } /** * @dev Directly remove an item from the list bypassing request-challenge. Can only be used by the relay contract. * @param _itemID The ID of the item to remove. */ function removeItemDirectly(bytes32 _itemID) external onlyRelayer { Item storage item = items[_itemID]; require(item.status == Status.Registered, "Item must be registered to be removed."); item.status = Status.Absent; emit ItemStatusChange(_itemID, true); } /** * @dev Submit a request to register an item. Accepts enough ETH to cover the deposit, reimburses the rest. * @param _item The URI to the item data. */ function addItem(string calldata _item) external payable { bytes32 itemID = keccak256(abi.encodePacked(_item)); Item storage item = items[itemID]; // Extremely unlikely, but we check that for correctness sake. require(item.requestCount < uint120(-1), "Too many requests for item."); require(item.status == Status.Absent, "Item must be absent to be added."); // Note that if the item was added previously using `addItemDirectly`, the event will be emitted again here. if (item.requestCount == 0) { emit NewItem(itemID, _item, false); } Request storage request = item.requests[item.requestCount++]; uint256 arbitrationParamsIndex = arbitrationParamsChanges.length - 1; IArbitrator arbitrator = arbitrationParamsChanges[arbitrationParamsIndex].arbitrator; bytes storage arbitratorExtraData = arbitrationParamsChanges[arbitrationParamsIndex].arbitratorExtraData; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 totalCost = arbitrationCost.addCap(submissionBaseDeposit); require(msg.value >= totalCost, "You must fully fund the request."); // Casting is safe here because this line will never be executed in case // totalCost > type(uint128).max, since it would be an unpayable value. item.sumDeposit = uint128(totalCost); item.status = Status.RegistrationRequested; request.requestType = RequestType.Registration; request.submissionTime = uint64(block.timestamp); request.arbitrationParamsIndex = uint24(arbitrationParamsIndex); request.requester = msg.sender; emit RequestSubmitted(itemID, getEvidenceGroupID(itemID, item.requestCount - 1)); emit Contribution(itemID, item.requestCount - 1, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Requester); if (msg.value > totalCost) { msg.sender.send(msg.value - totalCost); } } /** * @dev Submit a request to remove an item from the list. Accepts enough ETH to cover the deposit, reimburses the rest. * @param _itemID The ID of the item to remove. * @param _evidence A link to an evidence using its URI. Ignored if not provided. */ function removeItem(bytes32 _itemID, string calldata _evidence) external payable { Item storage item = items[_itemID]; // Extremely unlikely, but we check that for correctness sake. require(item.requestCount < uint120(-1), "Too many requests for item."); require(item.status == Status.Registered, "Item must be registered to be removed."); Request storage request = item.requests[item.requestCount++]; uint256 arbitrationParamsIndex = arbitrationParamsChanges.length - 1; IArbitrator arbitrator = arbitrationParamsChanges[arbitrationParamsIndex].arbitrator; bytes storage arbitratorExtraData = arbitrationParamsChanges[arbitrationParamsIndex].arbitratorExtraData; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 totalCost = arbitrationCost.addCap(removalBaseDeposit); require(msg.value >= totalCost, "You must fully fund the request."); // Casting is safe here because this line will never be executed in case // totalCost > type(uint128).max, since it would be an unpayable value. item.sumDeposit = uint128(totalCost); item.status = Status.ClearingRequested; request.submissionTime = uint64(block.timestamp); request.arbitrationParamsIndex = uint24(arbitrationParamsIndex); request.requester = msg.sender; request.requestType = RequestType.Clearing; uint256 evidenceGroupID = getEvidenceGroupID(_itemID, item.requestCount - 1); emit RequestSubmitted(_itemID, evidenceGroupID); emit Contribution(_itemID, item.requestCount - 1, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Requester); // Emit evidence if it was provided. if (bytes(_evidence).length > 0) { emit Evidence(arbitrator, evidenceGroupID, msg.sender, _evidence); } if (msg.value > totalCost) { msg.sender.send(msg.value - totalCost); } } /** * @dev Challenges the request of the item. Accepts enough ETH to cover the deposit, reimburses the rest. * @param _itemID The ID of the item which request to challenge. * @param _evidence A link to an evidence using its URI. Ignored if not provided. */ function challengeRequest(bytes32 _itemID, string calldata _evidence) external payable { Item storage item = items[_itemID]; require(item.status > Status.Registered, "The item must have a pending request."); uint256 lastRequestIndex = item.requestCount - 1; Request storage request = item.requests[lastRequestIndex]; require( block.timestamp - request.submissionTime <= challengePeriodDuration, "Challenges must occur during the challenge period." ); DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex]; require(disputeData.status == DisputeStatus.None, "The request should not have already been disputed."); ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex]; IArbitrator arbitrator = arbitrationParams.arbitrator; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitrationParams.arbitratorExtraData); uint256 totalCost; { uint256 challengerBaseDeposit = item.status == Status.RegistrationRequested ? submissionChallengeBaseDeposit : removalChallengeBaseDeposit; totalCost = arbitrationCost.addCap(challengerBaseDeposit); } require(msg.value >= totalCost, "You must fully fund the challenge."); emit Contribution(_itemID, lastRequestIndex, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Challenger); // Casting is safe here because this line will never be executed in case // totalCost > type(uint128).max, since it would be an unpayable value. item.sumDeposit = item.sumDeposit.addCap(uint128(totalCost)).subCap(uint128(arbitrationCost)); request.challenger = msg.sender; // Raise a dispute. disputeData.disputeID = arbitrator.createDispute.value(arbitrationCost)( RULING_OPTIONS, arbitrationParams.arbitratorExtraData ); disputeData.status = DisputeStatus.AwaitingRuling; // For compatibility with GeneralizedTCR consider the request/challenge cycle // the first round (index 0), so we need to make the next round index 1. disputeData.roundCount = 2; arbitratorDisputeIDToItemID[address(arbitrator)][disputeData.disputeID] = _itemID; uint256 metaEvidenceID = 2 * request.arbitrationParamsIndex + uint256(request.requestType); uint256 evidenceGroupID = getEvidenceGroupID(_itemID, lastRequestIndex); emit Dispute(arbitrator, disputeData.disputeID, metaEvidenceID, evidenceGroupID); if (bytes(_evidence).length > 0) { emit Evidence(arbitrator, evidenceGroupID, msg.sender, _evidence); } if (msg.value > totalCost) { msg.sender.send(msg.value - totalCost); } } /** * @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. * @param _itemID The ID of the item which request to fund. * @param _side The recipient of the contribution. */ function fundAppeal(bytes32 _itemID, Party _side) external payable { require(_side > Party.None, "Invalid side."); Item storage item = items[_itemID]; require(item.status > Status.Registered, "The item must have a pending request."); uint256 lastRequestIndex = item.requestCount - 1; Request storage request = item.requests[lastRequestIndex]; DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex]; require( disputeData.status == DisputeStatus.AwaitingRuling, "A dispute must have been raised to fund an appeal." ); ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex]; IArbitrator arbitrator = arbitrationParams.arbitrator; uint256 lastRoundIndex = disputeData.roundCount - 1; Round storage round = disputeData.rounds[lastRoundIndex]; require(round.sideFunded != _side, "Side already fully funded."); uint256 multiplier; { (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeData.disputeID); require( block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Contributions must be made within the appeal period." ); Party winner = Party(arbitrator.currentRuling(disputeData.disputeID)); if (winner == Party.None) { multiplier = sharedStakeMultiplier; } else if (_side == winner) { multiplier = winnerStakeMultiplier; } else { multiplier = loserStakeMultiplier; require( block.timestamp < (appealPeriodStart + appealPeriodEnd) / 2, "The loser must contribute during the first half of the appeal period." ); } } uint256 appealCost = arbitrator.appealCost(disputeData.disputeID, arbitrationParams.arbitratorExtraData); uint256 totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR); contribute(_itemID, lastRequestIndex, lastRoundIndex, uint256(_side), msg.sender, msg.value, totalCost); if (round.amountPaid[uint256(_side)] >= totalCost) { if (round.sideFunded == Party.None) { round.sideFunded = _side; } else { // Resets the value because both sides are funded. round.sideFunded = Party.None; // Raise appeal if both sides are fully funded. arbitrator.appeal.value(appealCost)(disputeData.disputeID, arbitrationParams.arbitratorExtraData); disputeData.roundCount++; round.feeRewards = round.feeRewards.subCap(appealCost); } } } /** * @dev If a dispute was raised, sends the fee stake rewards and reimbursements proportionally to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions to a request. * @param _itemID The ID of the item submission to withdraw from. * @param _requestID The request from which to withdraw from. * @param _roundID The round from which to withdraw from. */ function withdrawFeesAndRewards( address payable _beneficiary, bytes32 _itemID, uint256 _requestID, uint256 _roundID ) external { DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID]; require(disputeData.status == DisputeStatus.Resolved, "Request must be resolved."); Round storage round = disputeData.rounds[_roundID]; uint256 reward; if (_roundID == disputeData.roundCount - 1) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint256(Party.Requester)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; } else if (disputeData.ruling == Party.None) { uint256 totalFeesInRound = round.amountPaid[uint256(Party.Challenger)] + round.amountPaid[uint256(Party.Requester)]; uint256 claimableFees = round.contributions[_beneficiary][uint256(Party.Challenger)] + round.contributions[_beneficiary][uint256(Party.Requester)]; reward = totalFeesInRound > 0 ? (claimableFees * round.feeRewards) / totalFeesInRound : 0; } else { // Reward the winner. reward = round.amountPaid[uint256(disputeData.ruling)] > 0 ? (round.contributions[_beneficiary][uint256(disputeData.ruling)] * round.feeRewards) / round.amountPaid[uint256(disputeData.ruling)] : 0; } round.contributions[_beneficiary][uint256(Party.Requester)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; if (reward > 0) { _beneficiary.send(reward); emit RewardWithdrawn(_beneficiary, _itemID, _requestID, _roundID, reward); } } /** * @dev Executes an unchallenged request if the challenge period has passed. * @param _itemID The ID of the item to execute. */ function executeRequest(bytes32 _itemID) external { Item storage item = items[_itemID]; uint256 lastRequestIndex = items[_itemID].requestCount - 1; Request storage request = item.requests[lastRequestIndex]; require( block.timestamp - request.submissionTime > challengePeriodDuration, "Time to challenge the request must pass." ); DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex]; require(disputeData.status == DisputeStatus.None, "The request should not be disputed."); if (item.status == Status.RegistrationRequested) { item.status = Status.Registered; } else if (item.status == Status.ClearingRequested) { item.status = Status.Absent; } else { revert("There must be a request."); } emit ItemStatusChange(_itemID, false); uint256 sumDeposit = item.sumDeposit; item.sumDeposit = 0; if (sumDeposit > 0) { // reimburse the requester request.requester.send(sumDeposit); } } /** * @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Accounts for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refused to arbitrate". */ function rule(uint256 _disputeID, uint256 _ruling) external { require(_ruling <= RULING_OPTIONS, "Invalid ruling option"); bytes32 itemID = arbitratorDisputeIDToItemID[msg.sender][_disputeID]; Item storage item = items[itemID]; uint256 lastRequestIndex = items[itemID].requestCount - 1; Request storage request = item.requests[lastRequestIndex]; DisputeData storage disputeData = requestsDisputeData[itemID][lastRequestIndex]; require(disputeData.status == DisputeStatus.AwaitingRuling, "The request must not be resolved."); ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex]; require(address(arbitrationParams.arbitrator) == msg.sender, "Only the arbitrator can give a ruling"); uint256 finalRuling; Round storage round = disputeData.rounds[disputeData.roundCount - 1]; // If one side paid its fees, the ruling is in its favor. // Note that if the other side had also paid, sideFudned would have been reset // and an appeal would have been created. if (round.sideFunded == Party.Requester) { finalRuling = uint256(Party.Requester); } else if (round.sideFunded == Party.Challenger) { finalRuling = uint256(Party.Challenger); } else { finalRuling = _ruling; } emit Ruling(IArbitrator(msg.sender), _disputeID, finalRuling); Party winner = Party(finalRuling); disputeData.status = DisputeStatus.Resolved; disputeData.ruling = winner; uint256 sumDeposit = item.sumDeposit; item.sumDeposit = 0; if (winner == Party.None) { // If the arbitrator refuse to rule, then the item status should be the same it was before the request. // Regarding item.status this is equivalent to the challenger winning the dispute. item.status = item.status == Status.RegistrationRequested ? Status.Absent : Status.Registered; // Since nobody has won, then we reimburse both parties equally. // If item.sumDeposit is odd, 1 wei will remain in the contract balance. uint256 halfSumDeposit = sumDeposit / 2; request.requester.send(halfSumDeposit); request.challenger.send(halfSumDeposit); } else if (winner == Party.Requester) { item.status = item.status == Status.RegistrationRequested ? Status.Registered : Status.Absent; request.requester.send(sumDeposit); } else { item.status = item.status == Status.RegistrationRequested ? Status.Absent : Status.Registered; request.challenger.send(sumDeposit); } emit ItemStatusChange(itemID, false); } /** * @dev Submit a reference to evidence. EVENT. * @param _itemID The ID of the item which the evidence is related to. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(bytes32 _itemID, string calldata _evidence) external { Item storage item = items[_itemID]; uint256 lastRequestIndex = item.requestCount - 1; Request storage request = item.requests[lastRequestIndex]; ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex]; emit Evidence( arbitrationParams.arbitrator, getEvidenceGroupID(_itemID, lastRequestIndex), msg.sender, _evidence ); } // ************************ // // * Governance * // // ************************ // /** * @dev Change the duration of the challenge period. * @param _challengePeriodDuration The new duration of the challenge period. */ function changeChallengePeriodDuration(uint256 _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; } /** * @dev Change the base amount required as a deposit to submit an item. * @param _submissionBaseDeposit The new base amount of wei required to submit an item. */ function changeSubmissionBaseDeposit(uint256 _submissionBaseDeposit) external onlyGovernor { submissionBaseDeposit = _submissionBaseDeposit; } /** * @dev Change the base amount required as a deposit to remove an item. * @param _removalBaseDeposit The new base amount of wei required to remove an item. */ function changeRemovalBaseDeposit(uint256 _removalBaseDeposit) external onlyGovernor { removalBaseDeposit = _removalBaseDeposit; } /** * @dev Change the base amount required as a deposit to challenge a submission. * @param _submissionChallengeBaseDeposit The new base amount of wei required to challenge a submission. */ function changeSubmissionChallengeBaseDeposit(uint256 _submissionChallengeBaseDeposit) external onlyGovernor { submissionChallengeBaseDeposit = _submissionChallengeBaseDeposit; } /** * @dev Change the base amount required as a deposit to challenge a removal request. * @param _removalChallengeBaseDeposit The new base amount of wei required to challenge a removal request. */ function changeRemovalChallengeBaseDeposit(uint256 _removalChallengeBaseDeposit) external onlyGovernor { removalChallengeBaseDeposit = _removalChallengeBaseDeposit; } /** * @dev Change the governor of the curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** * @dev Change the proportion of arbitration fees that must be paid as fee stake by parties when there is no winner or loser. * @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) external onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** * @dev Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round. * @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) external onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** * @dev Change the proportion of arbitration fees that must be paid as fee stake by the party that lost the previous round. * @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } /** * @dev Change the address of connectedTCR, the Generalized TCR instance that stores addresses of TCRs related to this one. * @param _connectedTCR The address of the connectedTCR contract to use. */ function changeConnectedTCR(address _connectedTCR) external onlyGovernor { emit ConnectedTCRSet(_connectedTCR); } /** * @dev Change the address of the relay contract. * @param _relayerContract The new address of the relay contract. */ function changeRelayerContract(address _relayerContract) external onlyGovernor { relayerContract = _relayerContract; } /** * @notice Changes the params related to arbitration. * @dev Effectively makes all new items use the new set of params. * @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. */ function changeArbitrationParams( IArbitrator _arbitrator, bytes calldata _arbitratorExtraData, string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence ) external onlyGovernor { _doChangeArbitrationParams(_arbitrator, _arbitratorExtraData, _registrationMetaEvidence, _clearingMetaEvidence); } /* Internal */ /** * @dev Effectively makes all new items use the new set of params. * @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. */ function _doChangeArbitrationParams( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, string memory _registrationMetaEvidence, string memory _clearingMetaEvidence ) internal { emit MetaEvidence(2 * arbitrationParamsChanges.length, _registrationMetaEvidence); emit MetaEvidence(2 * arbitrationParamsChanges.length + 1, _clearingMetaEvidence); arbitrationParamsChanges.push( ArbitrationParams({arbitrator: _arbitrator, arbitratorExtraData: _arbitratorExtraData}) ); } /** * @notice Make a fee contribution. * @dev It cannot be inlined in fundAppeal because of the stack limit. * @param _itemID The item receiving the contribution. * @param _requestID The request to contribute. * @param _roundID The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. * @return The amount of appeal fees contributed. */ function contribute( bytes32 _itemID, uint256 _requestID, uint256 _roundID, uint256 _side, address payable _contributor, uint256 _amount, uint256 _totalRequired ) internal { Round storage round = requestsDisputeData[_itemID][_requestID].rounds[_roundID]; uint256 pendingAmount = _totalRequired.subCap(round.amountPaid[_side]); // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; // Amount contributed. uint256 remainingETH; // Remaining ETH to send back. if (pendingAmount > _amount) { contribution = _amount; } else { contribution = pendingAmount; remainingETH = _amount - pendingAmount; } round.contributions[_contributor][_side] += contribution; round.amountPaid[_side] += contribution; round.feeRewards += contribution; // Reimburse leftover ETH. if (remainingETH > 0) { // Deliberate use of send in order to not block the contract in case of reverting fallback. _contributor.send(remainingETH); } if (contribution > 0) { emit Contribution(_itemID, _requestID, _roundID, msg.sender, contribution, Party(_side)); } } // ************************ // // * Getters * // // ************************ // /** * @dev Gets the evidengeGroupID for a given item and request. * @param _itemID The ID of the item. * @param _requestID The ID of the request. * @return The evidenceGroupID */ function getEvidenceGroupID(bytes32 _itemID, uint256 _requestID) public pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_itemID, _requestID))); } /** * @notice Gets the arbitrator for new requests. * @dev Gets the latest value in arbitrationParamsChanges. * @return The arbitrator address. */ function arbitrator() external view returns (IArbitrator) { return arbitrationParamsChanges[arbitrationParamsChanges.length - 1].arbitrator; } /** * @notice Gets the arbitratorExtraData for new requests. * @dev Gets the latest value in arbitrationParamsChanges. * @return The arbitrator extra data. */ function arbitratorExtraData() external view returns (bytes memory) { return arbitrationParamsChanges[arbitrationParamsChanges.length - 1].arbitratorExtraData; } /** * @dev Gets the number of times MetaEvidence was updated. * @return The number of times MetaEvidence was updated. */ function metaEvidenceUpdates() external view returns (uint256) { return arbitrationParamsChanges.length; } /** * @dev Gets the contributions made by a party for a given round of a request. * @param _itemID The ID of the item. * @param _requestID The request to query. * @param _roundID The round to query. * @param _contributor The address of the contributor. * @return contributions The contributions. */ function getContributions( bytes32 _itemID, uint256 _requestID, uint256 _roundID, address _contributor ) external view returns (uint256[3] memory contributions) { DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID]; Round storage round = disputeData.rounds[_roundID]; contributions = round.contributions[_contributor]; } /** * @dev Returns item's information. Includes the total number of requests for the item * @param _itemID The ID of the queried item. * @return status The current status of the item. * @return numberOfRequests Total number of requests for the item. * @return sumDeposit The total deposit made by the requester and the challenger (if any) */ function getItemInfo(bytes32 _itemID) external view returns ( Status status, uint256 numberOfRequests, uint256 sumDeposit ) { Item storage item = items[_itemID]; return (item.status, item.requestCount, item.sumDeposit); } /** * @dev Gets information on a request made for the item. * @param _itemID The ID of the queried item. * @param _requestID The request to be queried. * @return disputed True if a dispute was raised. * @return disputeID ID of the dispute, if any. * @return submissionTime Time when the request was made. * @return resolved True if the request was executed and/or any raised disputes were resolved. * @return parties Address of requester and challenger, if any. * @return numberOfRounds Number of rounds of dispute. * @return ruling The final ruling given, if any. * @return arbitrator The arbitrator trusted to solve disputes for this request. * @return arbitratorExtraData The extra data for the trusted arbitrator of this request. * @return metaEvidenceID The meta evidence to be used in a dispute for this case. */ function getRequestInfo(bytes32 _itemID, uint256 _requestID) external view returns ( bool disputed, uint256 disputeID, uint256 submissionTime, bool resolved, address payable[3] memory parties, uint256 numberOfRounds, Party ruling, IArbitrator requestArbitrator, bytes memory requestArbitratorExtraData, uint256 metaEvidenceID ) { Item storage item = items[_itemID]; require(item.requestCount > _requestID, "Request does not exist."); Request storage request = items[_itemID].requests[_requestID]; submissionTime = request.submissionTime; parties[uint256(Party.Requester)] = request.requester; parties[uint256(Party.Challenger)] = request.challenger; (disputed, disputeID, numberOfRounds, ruling) = getRequestDisputeData(_itemID, _requestID); (requestArbitrator, requestArbitratorExtraData, metaEvidenceID) = getRequestArbitrationParams( _itemID, _requestID ); resolved = getRequestResolvedStatus(_itemID, _requestID); } /** * @dev Gets the dispute data relative to a given item request. * @param _itemID The ID of the queried item. * @param _requestID The request to be queried. * @return disputed True if a dispute was raised. * @return disputeID ID of the dispute, if any. * @return ruling The final ruling given, if any. * @return numberOfRounds Number of rounds of dispute. */ function getRequestDisputeData(bytes32 _itemID, uint256 _requestID) internal view returns ( bool disputed, uint256 disputeID, uint256 numberOfRounds, Party ruling ) { DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID]; return ( disputeData.status >= DisputeStatus.AwaitingRuling, disputeData.disputeID, disputeData.roundCount, disputeData.ruling ); } /** * @dev Gets the arbitration params relative to a given item request. * @param _itemID The ID of the queried item. * @param _requestID The request to be queried. * @return arbitrator The arbitrator trusted to solve disputes for this request. * @return arbitratorExtraData The extra data for the trusted arbitrator of this request. * @return metaEvidenceID The meta evidence to be used in a dispute for this case. */ function getRequestArbitrationParams(bytes32 _itemID, uint256 _requestID) internal view returns ( IArbitrator arbitrator, bytes memory arbitratorExtraData, uint256 metaEvidenceID ) { Request storage request = items[_itemID].requests[_requestID]; ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex]; return ( arbitrationParams.arbitrator, arbitrationParams.arbitratorExtraData, 2 * request.arbitrationParamsIndex + uint256(request.requestType) ); } /** * @dev Gets the resovled status of a given item request. * @param _itemID The ID of the queried item. * @param _requestID The request to be queried. * @return resolved True if the request was executed and/or any raised disputes were resolved. */ function getRequestResolvedStatus(bytes32 _itemID, uint256 _requestID) internal view returns (bool resolved) { Item storage item = items[_itemID]; if (item.requestCount == 0) { return false; } if (_requestID < item.requestCount - 1) { // It was resolved because it is not the last request. return true; } return item.sumDeposit == 0; } /** * @dev Gets the information of a round of a request. * @param _itemID The ID of the queried item. * @param _requestID The request to be queried. * @param _roundID The round to be queried. * @return appealed Whether appealed or not. * @return amountPaid Tracks the sum paid for each Party in this round. * @return hasPaid True if the Party has fully paid its fee in this round. * @return feeRewards Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. */ function getRoundInfo( bytes32 _itemID, uint256 _requestID, uint256 _roundID ) external view returns ( bool appealed, uint256[3] memory amountPaid, bool[3] memory hasPaid, uint256 feeRewards ) { Item storage item = items[_itemID]; require(item.requestCount > _requestID, "Request does not exist."); DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID]; require(disputeData.roundCount > _roundID, "Round does not exist"); Round storage round = disputeData.rounds[_roundID]; appealed = _roundID < disputeData.roundCount - 1; hasPaid[uint256(Party.Requester)] = appealed || round.sideFunded == Party.Requester; hasPaid[uint256(Party.Challenger)] = appealed || round.sideFunded == Party.Challenger; return (appealed, round.amountPaid, hasPaid, round.feeRewards); } } /** * @title LightGTCRFactory * This contract acts as a registry for LightGeneralizedTCR instances. */ contract LightGTCRFactory { /** * @dev Emitted when a new Generalized TCR contract is deployed using this factory. * @param _address The address of the newly deployed Generalized TCR. */ event NewGTCR(LightGeneralizedTCR indexed _address); LightGeneralizedTCR[] public instances; address public GTCR; /** * @dev Constructor. * @param _GTCR Address of the generalized TCR contract that is going to be used for each new deployment. */ constructor(address _GTCR) public { GTCR = _GTCR; } /** * @dev Deploy the arbitrable curated registry. * @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _connectedTCR The address of the TCR that stores related TCR addresses. This parameter can be left empty. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. * @param _governor The trusted governor of this contract. * @param _baseDeposits The base deposits for requests/challenges as follows: * - The base deposit to submit an item. * - The base deposit to remove an item. * - The base deposit to challenge a submission. * - The base deposit to challenge a removal request. * @param _challengePeriodDuration The time in seconds parties have to challenge a request. * @param _stakeMultipliers Multipliers of the arbitration cost in basis points (see LightGeneralizedTCR MULTIPLIER_DIVISOR) as follows: * - The multiplier applied to each party's fee stake for a round when there is no winner/loser in the previous round. * - The multiplier applied to the winner's fee stake for an appeal round. * - The multiplier applied to the loser's fee stake for an appeal round. * @param _relayContract The address of the relay contract to add/remove items directly. */ function deploy( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, address _connectedTCR, string memory _registrationMetaEvidence, string memory _clearingMetaEvidence, address _governor, uint256[4] memory _baseDeposits, uint256 _challengePeriodDuration, uint256[3] memory _stakeMultipliers, address _relayContract ) public { LightGeneralizedTCR instance = clone(GTCR); instance.initialize( _arbitrator, _arbitratorExtraData, _connectedTCR, _registrationMetaEvidence, _clearingMetaEvidence, _governor, _baseDeposits, _challengePeriodDuration, _stakeMultipliers, _relayContract ); instances.push(instance); emit NewGTCR(instance); } /** * @notice Adaptation of @openzeppelin/contracts/proxy/Clones.sol. * @dev Deploys and returns the address of a clone that mimics the behaviour of `GTCR`. * @param _implementation Address of the contract to clone. * This function uses the create opcode, which should never revert. */ function clone(address _implementation) internal returns (LightGeneralizedTCR instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, _implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != LightGeneralizedTCR(0), "ERC1167: create failed"); } /** * @return The number of deployed tcrs using this factory. */ function count() external view returns (uint256) { return instances.length; } }
* @dev Gets the dispute data relative to a given item request. @param _itemID The ID of the queried item. @param _requestID The request to be queried. @return disputed True if a dispute was raised. @return disputeID ID of the dispute, if any. @return ruling The final ruling given, if any. @return numberOfRounds Number of rounds of dispute./
function getRequestDisputeData(bytes32 _itemID, uint256 _requestID) internal view returns ( bool disputed, uint256 disputeID, uint256 numberOfRounds, Party ruling ) { DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID]; return ( disputeData.status >= DisputeStatus.AwaitingRuling, disputeData.disputeID, disputeData.roundCount, disputeData.ruling ); }
631,811
[ 1, 3002, 326, 1015, 2507, 501, 3632, 358, 279, 864, 761, 590, 18, 225, 389, 1726, 734, 1021, 1599, 434, 326, 23264, 761, 18, 225, 389, 2293, 734, 1021, 590, 358, 506, 23264, 18, 327, 1015, 458, 329, 1053, 309, 279, 1015, 2507, 1703, 11531, 18, 327, 1015, 2507, 734, 1599, 434, 326, 1015, 2507, 16, 309, 1281, 18, 327, 436, 332, 310, 1021, 727, 436, 332, 310, 864, 16, 309, 1281, 18, 327, 7922, 54, 9284, 3588, 434, 21196, 434, 1015, 2507, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4328, 1669, 2507, 751, 12, 3890, 1578, 389, 1726, 734, 16, 2254, 5034, 389, 2293, 734, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 1426, 1015, 458, 329, 16, 203, 5411, 2254, 5034, 1015, 2507, 734, 16, 203, 5411, 2254, 5034, 7922, 54, 9284, 16, 203, 5411, 6393, 93, 436, 332, 310, 203, 3639, 262, 203, 565, 288, 203, 3639, 3035, 2507, 751, 2502, 1015, 2507, 751, 273, 3285, 1669, 2507, 751, 63, 67, 1726, 734, 6362, 67, 2293, 734, 15533, 203, 203, 3639, 327, 261, 203, 5411, 1015, 2507, 751, 18, 2327, 1545, 3035, 2507, 1482, 18, 37, 20241, 54, 332, 310, 16, 203, 5411, 1015, 2507, 751, 18, 2251, 2507, 734, 16, 203, 5411, 1015, 2507, 751, 18, 2260, 1380, 16, 203, 5411, 1015, 2507, 751, 18, 86, 332, 310, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.8; pragma experimental ABIEncoderV2; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library AssetRegistry { struct Storage { mapping(address => Structs.Asset) assetsByAddress; // Mapping value is array since the same symbol can be re-used for a different address // (usually as a result of a token swap or upgrade) mapping(string => Structs.Asset[]) assetsBySymbol; } function registerToken( Storage storage self, IERC20 tokenAddress, string memory symbol, uint8 decimals ) internal { require(decimals <= 32, 'Token cannot have more than 32 decimals'); require( tokenAddress != IERC20(0x0) && Address.isContract(address(tokenAddress)), 'Invalid token address' ); // The string type does not have a length property so cast to bytes to check for empty string require(bytes(symbol).length > 0, 'Invalid token symbol'); require( !self.assetsByAddress[address(tokenAddress)].isConfirmed, 'Token already finalized' ); self.assetsByAddress[address(tokenAddress)] = Structs.Asset({ exists: true, assetAddress: address(tokenAddress), symbol: symbol, decimals: decimals, isConfirmed: false, confirmedTimestampInMs: 0 }); } function confirmTokenRegistration( Storage storage self, IERC20 tokenAddress, string memory symbol, uint8 decimals ) internal { Structs.Asset memory asset = self.assetsByAddress[address(tokenAddress)]; require(asset.exists, 'Unknown token'); require(!asset.isConfirmed, 'Token already finalized'); require(isStringEqual(asset.symbol, symbol), 'Symbols do not match'); require(asset.decimals == decimals, 'Decimals do not match'); asset.isConfirmed = true; asset.confirmedTimestampInMs = uint64(block.timestamp * 1000); // Block timestamp is in seconds, store ms self.assetsByAddress[address(tokenAddress)] = asset; self.assetsBySymbol[symbol].push(asset); } function addTokenSymbol( Storage storage self, IERC20 tokenAddress, string memory symbol ) internal { Structs.Asset memory asset = self.assetsByAddress[address(tokenAddress)]; require( asset.exists && asset.isConfirmed, 'Registration of token not finalized' ); require(!isStringEqual(symbol, 'ETH'), 'ETH symbol reserved for Ether'); // This will prevent swapping assets for previously existing orders uint64 msInOneSecond = 1000; asset.confirmedTimestampInMs = uint64(block.timestamp * msInOneSecond); self.assetsBySymbol[symbol].push(asset); } /** * @dev Resolves an asset address into corresponding Asset struct * * @param assetAddress Ethereum address of asset */ function loadAssetByAddress(Storage storage self, address assetAddress) internal view returns (Structs.Asset memory) { if (assetAddress == address(0x0)) { return getEthAsset(); } Structs.Asset memory asset = self.assetsByAddress[assetAddress]; require( asset.exists && asset.isConfirmed, 'No confirmed asset found for address' ); return asset; } /** * @dev Resolves a asset symbol into corresponding Asset struct * * @param symbol Asset symbol, e.g. 'IDEX' * @param timestampInMs Milliseconds since Unix epoch, usually parsed from a UUID v1 order nonce. * Constrains symbol resolution to the asset most recently confirmed prior to timestampInMs. Reverts * if no such asset exists */ function loadAssetBySymbol( Storage storage self, string memory symbol, uint64 timestampInMs ) internal view returns (Structs.Asset memory) { if (isStringEqual('ETH', symbol)) { return getEthAsset(); } Structs.Asset memory asset; if (self.assetsBySymbol[symbol].length > 0) { for (uint8 i = 0; i < self.assetsBySymbol[symbol].length; i++) { if ( self.assetsBySymbol[symbol][i].confirmedTimestampInMs <= timestampInMs ) { asset = self.assetsBySymbol[symbol][i]; } } } require( asset.exists && asset.isConfirmed, 'No confirmed asset found for symbol' ); return asset; } /** * @dev ETH is modeled as an always-confirmed Asset struct for programmatic consistency */ function getEthAsset() private pure returns (Structs.Asset memory) { return Structs.Asset(true, address(0x0), 'ETH', 18, true, 0); } // See https://solidity.readthedocs.io/en/latest/types.html#bytes-and-strings-as-arrays function isStringEqual(string memory a, string memory b) private pure returns (bool) { return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); } } library AssetTransfers { using SafeMath256 for uint256; /** * @dev Transfers tokens from a wallet into a contract during deposits. `wallet` must already * have called `approve` on the token contract for at least `tokenQuantity`. Note this only * applies to tokens since ETH is sent in the deposit transaction via `msg.value` */ function transferFrom( address wallet, IERC20 tokenAddress, uint256 quantityInAssetUnits ) internal { uint256 balanceBefore = tokenAddress.balanceOf(address(this)); // Because we check for the expected balance change we can safely ignore the return value of transferFrom tokenAddress.transferFrom(wallet, address(this), quantityInAssetUnits); uint256 balanceAfter = tokenAddress.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) == quantityInAssetUnits, 'Token contract returned transferFrom success without expected balance change' ); } /** * @dev Transfers ETH or token assets from a contract to 1) another contract, when `Exchange` * forwards funds to `Custodian` during deposit or 2) a wallet, when withdrawing */ function transferTo( address payable walletOrContract, address asset, uint256 quantityInAssetUnits ) internal { if (asset == address(0x0)) { require( walletOrContract.send(quantityInAssetUnits), 'ETH transfer failed' ); } else { uint256 balanceBefore = IERC20(asset).balanceOf(walletOrContract); // Because we check for the expected balance change we can safely ignore the return value of transfer IERC20(asset).transfer(walletOrContract, quantityInAssetUnits); uint256 balanceAfter = IERC20(asset).balanceOf(walletOrContract); require( balanceAfter.sub(balanceBefore) == quantityInAssetUnits, 'Token contract returned transfer success without expected balance change' ); } } } library AssetUnitConversions { using SafeMath256 for uint256; function pipsToAssetUnits(uint64 quantityInPips, uint8 assetDecimals) internal pure returns (uint256) { require(assetDecimals <= 32, 'Asset cannot have more than 32 decimals'); // Exponents cannot be negative, so divide or multiply based on exponent signedness if (assetDecimals > 8) { return uint256(quantityInPips).mul(uint256(10)**(assetDecimals - 8)); } return uint256(quantityInPips).div(uint256(10)**(8 - assetDecimals)); } function assetUnitsToPips(uint256 quantityInAssetUnits, uint8 assetDecimals) internal pure returns (uint64) { require(assetDecimals <= 32, 'Asset cannot have more than 32 decimals'); uint256 quantityInPips; // Exponents cannot be negative, so divide or multiply based on exponent signedness if (assetDecimals > 8) { quantityInPips = quantityInAssetUnits.div( uint256(10)**(assetDecimals - 8) ); } else { quantityInPips = quantityInAssetUnits.mul( uint256(10)**(8 - assetDecimals) ); } require(quantityInPips < 2**64, 'Pip quantity overflows uint64'); return uint64(quantityInPips); } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } contract Enums { enum OrderSelfTradePrevention { // Decrement and cancel dc, // Cancel oldest co, // Cancel newest cn, // Cancel both cb } enum OrderSide { Buy, Sell } enum OrderTimeInForce { // Good until cancelled gtc, // Good until time gtt, // Immediate or cancel ioc, // Fill or kill fok } enum OrderType { Market, Limit, LimitMaker, StopLoss, StopLossLimit, TakeProfit, TakeProfitLimit } enum WithdrawalType { BySymbol, ByAddress } } contract Structs { /** * @notice Argument type for `Exchange.executeTrade` and `Signatures.getOrderWalletHash` */ struct Order { // Not currently used but reserved for future use. Must be 1 uint8 signatureHashVersion; // UUIDv1 unique to wallet uint128 nonce; // Wallet address that placed order and signed hash address walletAddress; // Type of order Enums.OrderType orderType; // Order side wallet is on Enums.OrderSide side; // Order quantity in base or quote asset terms depending on isQuantityInQuote flag uint64 quantityInPips; // Is quantityInPips in quote terms bool isQuantityInQuote; // For limit orders, price in decimal pips * 10^8 in quote terms uint64 limitPriceInPips; // For stop orders, stop loss or take profit price in decimal pips * 10^8 in quote terms uint64 stopPriceInPips; // Optional custom client order ID string clientOrderId; // TIF option specified by wallet for order Enums.OrderTimeInForce timeInForce; // STP behavior specified by wallet for order Enums.OrderSelfTradePrevention selfTradePrevention; // Cancellation time specified by wallet for GTT TIF order uint64 cancelAfter; // The ECDSA signature of the order hash as produced by Signatures.getOrderWalletHash bytes walletSignature; } /** * @notice Return type for `Exchange.loadAssetBySymbol`, and `Exchange.loadAssetByAddress`; also * used internally by `AssetRegistry` */ struct Asset { // Flag to distinguish from empty struct bool exists; // The asset's address address assetAddress; // The asset's symbol string symbol; // The asset's decimal precision uint8 decimals; // Flag set when asset registration confirmed. Asset deposits, trades, or withdrawals only allowed if true bool isConfirmed; // Timestamp as ms since Unix epoch when isConfirmed was asserted uint64 confirmedTimestampInMs; } /** * @notice Argument type for `Exchange.executeTrade` specifying execution parameters for matching orders */ struct Trade { // Base asset symbol string baseAssetSymbol; // Quote asset symbol string quoteAssetSymbol; // Base asset address address baseAssetAddress; // Quote asset address address quoteAssetAddress; // Gross amount including fees of base asset executed uint64 grossBaseQuantityInPips; // Gross amount including fees of quote asset executed uint64 grossQuoteQuantityInPips; // Net amount of base asset received by buy side wallet after fees uint64 netBaseQuantityInPips; // Net amount of quote asset received by sell side wallet after fees uint64 netQuoteQuantityInPips; // Asset address for liquidity maker's fee address makerFeeAssetAddress; // Asset address for liquidity taker's fee address takerFeeAssetAddress; // Fee paid by liquidity maker uint64 makerFeeQuantityInPips; // Fee paid by liquidity taker uint64 takerFeeQuantityInPips; // Execution price of trade in decimal pips * 10^8 in quote terms uint64 priceInPips; // Which side of the order (buy or sell) the liquidity maker was on Enums.OrderSide makerSide; } /** * @notice Argument type for `Exchange.withdraw` and `Signatures.getWithdrawalWalletHash` */ struct Withdrawal { // Distinguishes between withdrawals by asset symbol or address Enums.WithdrawalType withdrawalType; // UUIDv1 unique to wallet uint128 nonce; // Address of wallet to which funds will be returned address payable walletAddress; // Asset symbol string assetSymbol; // Asset address address assetAddress; // Used when assetSymbol not specified // Withdrawal quantity uint64 quantityInPips; // Gas fee deducted from withdrawn quantity to cover dispatcher tx costs uint64 gasFeeInPips; // Not currently used but reserved for future use. Must be true bool autoDispatchEnabled; // The ECDSA signature of the withdrawal hash as produced by Signatures.getWithdrawalWalletHash bytes walletSignature; } } interface IERC20 { /** * @notice Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @notice Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @notice Moves `amount` tokens from the caller's account to `recipient`. * * Most implementing contracts return a boolean value indicating whether the operation succeeded, but * we ignore this and rely on asserting balance changes instead * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external; /** * @notice 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); /** * @notice 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); /** * @notice Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Most implementing contracts return a boolean value indicating whether the operation succeeded, but * we ignore this and rely on asserting balance changes instead * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external; /** * @notice 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); /** * @notice 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); } interface ICustodian { /** * @notice ETH can only be sent by the Exchange */ receive() external payable; /** * @notice Withdraw any asset and amount to a target wallet * * @dev No balance checking performed * * @param wallet The wallet to which assets will be returned * @param asset The address of the asset to withdraw (ETH or ERC-20 contract) * @param quantityInAssetUnits The quantity in asset units to withdraw */ function withdraw( address payable wallet, address asset, uint256 quantityInAssetUnits ) external; /** * @notice Load address of the currently whitelisted Exchange contract * * @return The address of the currently whitelisted Exchange contract */ function loadExchange() external view returns (address); /** * @notice Sets a new Exchange contract address * * @param newExchange The address of the new whitelisted Exchange contract */ function setExchange(address newExchange) external; /** * @notice Load address of the currently whitelisted Governance contract * * @return The address of the currently whitelisted Governance contract */ function loadGovernance() external view returns (address); /** * @notice Sets a new Governance contract address * * @param newGovernance The address of the new whitelisted Governance contract */ function setGovernance(address newGovernance) external; } interface IExchange { /** * @notice Settles a trade between two orders submitted and matched off-chain * * @param buy A `Structs.Order` struct encoding the parameters of the buy-side order (receiving base, giving quote) * @param sell A `Structs.Order` struct encoding the parameters of the sell-side order (giving base, receiving quote) * @param trade A `Structs.Trade` struct encoding the parameters of this trade execution of the counterparty orders */ function executeTrade( Structs.Order calldata buy, Structs.Order calldata sell, Structs.Trade calldata trade ) external; /** * @notice Settles a user withdrawal submitted off-chain. Calls restricted to currently whitelisted Dispatcher wallet * * @param withdrawal A `Structs.Withdrawal` struct encoding the parameters of the withdrawal */ function withdraw(Structs.Withdrawal calldata withdrawal) external; } abstract contract Owned { address immutable _owner; address _admin; modifier onlyOwner { require(msg.sender == _owner, 'Caller must be owner'); _; } modifier onlyAdmin { require(msg.sender == _admin, 'Caller must be admin'); _; } /** * @notice Sets both the owner and admin roles to the contract creator */ constructor() public { _owner = msg.sender; _admin = msg.sender; } /** * @notice Sets a new whitelisted admin wallet * * @param newAdmin The new whitelisted admin wallet. Must be different from the current one */ function setAdmin(address newAdmin) external onlyOwner { require(newAdmin != address(0x0), 'Invalid wallet address'); require(newAdmin != _admin, 'Must be different from current admin'); _admin = newAdmin; } /** * @notice Clears the currently whitelisted admin wallet, effectively disabling any functions requiring * the admin role */ function removeAdmin() external onlyOwner { _admin = address(0x0); } } 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; } } library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint64 a, uint64 b, string memory errorMessage ) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint64 a, uint64 b, string memory errorMessage ) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint64 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } library Signatures { function isSignatureValid( bytes32 hash, bytes memory signature, address signer ) internal pure returns (bool) { return ECDSA.recover(ECDSA.toEthSignedMessageHash(hash), signature) == signer; } function getOrderWalletHash( Structs.Order memory order, string memory baseSymbol, string memory quoteSymbol ) internal pure returns (bytes32) { require( order.signatureHashVersion == 1, 'Signature hash version must be 1' ); return keccak256( // Placing all the fields in a single `abi.encodePacked` call causes a `stack too deep` error abi.encodePacked( abi.encodePacked( order.signatureHashVersion, order.nonce, order.walletAddress, getMarketSymbol(baseSymbol, quoteSymbol), uint8(order.orderType), uint8(order.side), // Ledger qtys and prices are in pip, but order was signed by wallet owner with decimal values pipToDecimal(order.quantityInPips) ), abi.encodePacked( order.isQuantityInQuote, order.limitPriceInPips > 0 ? pipToDecimal(order.limitPriceInPips) : '', order.stopPriceInPips > 0 ? pipToDecimal(order.stopPriceInPips) : '', order.clientOrderId, uint8(order.timeInForce), uint8(order.selfTradePrevention), order.cancelAfter ) ) ); } function getWithdrawalWalletHash(Structs.Withdrawal memory withdrawal) internal pure returns (bytes32) { return keccak256( abi.encodePacked( withdrawal.nonce, withdrawal.walletAddress, // Ternary branches must resolve to the same type, so wrap in idempotent encodePacked withdrawal.withdrawalType == Enums.WithdrawalType.BySymbol ? abi.encodePacked(withdrawal.assetSymbol) : abi.encodePacked(withdrawal.assetAddress), pipToDecimal(withdrawal.quantityInPips), withdrawal.autoDispatchEnabled ) ); } /** * @dev Combines base and quote asset symbols into the market symbol originally signed by the * wallet. For example if base is 'IDEX' and quote is 'ETH', the resulting market symbol is * 'IDEX-ETH'. This approach is used rather than passing in the market symbol and splitting it * since the latter incurs a higher gas cost */ function getMarketSymbol(string memory baseSymbol, string memory quoteSymbol) private pure returns (string memory) { bytes memory baseSymbolBytes = bytes(baseSymbol); bytes memory hyphenBytes = bytes('-'); bytes memory quoteSymbolBytes = bytes(quoteSymbol); bytes memory marketSymbolBytes = bytes( new string( baseSymbolBytes.length + quoteSymbolBytes.length + hyphenBytes.length ) ); uint256 i; uint256 j; for (i = 0; i < baseSymbolBytes.length; i++) { marketSymbolBytes[j++] = baseSymbolBytes[i]; } // Hyphen is one byte marketSymbolBytes[j++] = hyphenBytes[0]; for (i = 0; i < quoteSymbolBytes.length; i++) { marketSymbolBytes[j++] = quoteSymbolBytes[i]; } return string(marketSymbolBytes); } /** * @dev Converts an integer pip quantity back into the fixed-precision decimal pip string * originally signed by the wallet. For example, 1234567890 becomes '12.34567890' */ function pipToDecimal(uint256 pips) private pure returns (string memory) { // Inspired by https://github.com/provable-things/ethereum-api/blob/831f4123816f7a3e57ebea171a3cdcf3b528e475/oraclizeAPI_0.5.sol#L1045-L1062 uint256 copy = pips; uint256 length; while (copy != 0) { length++; copy /= 10; } if (length < 9) { length = 9; // a zero before the decimal point plus 8 decimals } length++; // for the decimal point bytes memory decimal = new bytes(length); for (uint256 i = length; i > 0; i--) { if (length - i == 8) { decimal[i - 1] = bytes1(uint8(46)); // period } else { decimal[i - 1] = bytes1(uint8(48 + (pips % 10))); pips /= 10; } } return string(decimal); } } library UUID { using SafeMath64 for uint64; /** * Extracts the timestamp component of a Version 1 UUID. Used to make time-based assertions * against a wallet-privided nonce */ function getTimestampInMsFromUuidV1(uint128 uuid) internal pure returns (uint64 msSinceUnixEpoch) { // https://tools.ietf.org/html/rfc4122#section-4.1.2 uint128 version = (uuid >> 76) & 0x0000000000000000000000000000000F; require(version == 1, 'Must be v1 UUID'); // Time components are in reverse order so shift+mask each to reassemble uint128 timeHigh = (uuid >> 16) & 0x00000000000000000FFF000000000000; uint128 timeMid = (uuid >> 48) & 0x00000000000000000000FFFF00000000; uint128 timeLow = (uuid >> 96) & 0x000000000000000000000000FFFFFFFF; uint128 nsSinceGregorianEpoch = (timeHigh | timeMid | timeLow); // Gregorian offset given in seconds by https://www.wolframalpha.com/input/?i=convert+1582-10-15+UTC+to+unix+time msSinceUnixEpoch = uint64(nsSinceGregorianEpoch / 10000).sub( 12219292800000 ); return msSinceUnixEpoch; } } contract Exchange is IExchange, Owned { using SafeMath64 for uint64; using SafeMath256 for uint256; using AssetRegistry for AssetRegistry.Storage; // Events // /** * @notice Emitted when an admin changes the Chain Propagation Period tunable parameter with `setChainPropagationPeriod` */ event ChainPropagationPeriodChanged(uint256 previousValue, uint256 newValue); /** * @notice Emitted when a user deposits ETH with `depositEther` or a token with `depositAsset` or `depositAssetBySymbol` */ event Deposited( uint64 index, address indexed wallet, address indexed assetAddress, string indexed assetSymbolIndex, string assetSymbol, uint64 quantityInPips, uint64 newExchangeBalanceInPips, uint256 newExchangeBalanceInAssetUnits ); /** * @notice Emitted when an admin changes the Dispatch Wallet tunable parameter with `setDispatcher` */ event DispatcherChanged(address previousValue, address newValue); /** * @notice Emitted when an admin changes the Fee Wallet tunable parameter with `setFeeWallet` */ event FeeWalletChanged(address previousValue, address newValue); /** * @notice Emitted when a user invalidates an order nonce with `invalidateOrderNonce` */ event OrderNonceInvalidated( address indexed wallet, uint128 nonce, uint128 timestampInMs, uint256 effectiveBlockNumber ); /** * @notice Emitted when an admin initiates the token registration process with `registerToken` */ event TokenRegistered( IERC20 indexed assetAddress, string assetSymbol, uint8 decimals ); /** * @notice Emitted when an admin finalizes the token registration process with `confirmAssetRegistration`, after * which it can be deposited, traded, or withdrawn */ event TokenRegistrationConfirmed( IERC20 indexed assetAddress, string assetSymbol, uint8 decimals ); /** * @notice Emitted when an admin adds a symbol to a previously registered and confirmed token * via `addTokenSymbol` */ event TokenSymbolAdded(IERC20 indexed assetAddress, string assetSymbol); /** * @notice Emitted when the Dispatcher Wallet submits a trade for execution with `executeTrade` */ event TradeExecuted( address buyWallet, address sellWallet, string indexed baseAssetSymbolIndex, string indexed quoteAssetSymbolIndex, string baseAssetSymbol, string quoteAssetSymbol, uint64 baseQuantityInPips, uint64 quoteQuantityInPips, uint64 tradePriceInPips, bytes32 buyOrderHash, bytes32 sellOrderHash ); /** * @notice Emitted when a user invokes the Exit Wallet mechanism with `exitWallet` */ event WalletExited(address indexed wallet, uint256 effectiveBlockNumber); /** * @notice Emitted when a user withdraws an asset balance through the Exit Wallet mechanism with `withdrawExit` */ event WalletExitWithdrawn( address indexed wallet, address indexed assetAddress, string assetSymbol, uint64 quantityInPips, uint64 newExchangeBalanceInPips, uint256 newExchangeBalanceInAssetUnits ); /** * @notice Emitted when a user clears the exited status of a wallet previously exited with `exitWallet` */ event WalletExitCleared(address indexed wallet); /** * @notice Emitted when the Dispatcher Wallet submits a withdrawal with `withdraw` */ event Withdrawn( address indexed wallet, address indexed assetAddress, string assetSymbol, uint64 quantityInPips, uint64 newExchangeBalanceInPips, uint256 newExchangeBalanceInAssetUnits ); // Internally used structs // struct NonceInvalidation { bool exists; uint64 timestampInMs; uint256 effectiveBlockNumber; } struct WalletExit { bool exists; uint256 effectiveBlockNumber; } // Storage // // Asset registry data AssetRegistry.Storage _assetRegistry; // Mapping of order wallet hash => isComplete mapping(bytes32 => bool) _completedOrderHashes; // Mapping of withdrawal wallet hash => isComplete mapping(bytes32 => bool) _completedWithdrawalHashes; address payable _custodian; uint64 _depositIndex; // Mapping of wallet => asset => balance mapping(address => mapping(address => uint64)) _balancesInPips; // Mapping of wallet => last invalidated timestampInMs mapping(address => NonceInvalidation) _nonceInvalidations; // Mapping of order hash => filled quantity in pips mapping(bytes32 => uint64) _partiallyFilledOrderQuantitiesInPips; mapping(address => WalletExit) _walletExits; // Tunable parameters uint256 _chainPropagationPeriod; address _dispatcherWallet; address _feeWallet; // Constant values // uint256 constant _maxChainPropagationPeriod = (7 * 24 * 60 * 60) / 15; // 1 week at 15s/block uint64 constant _maxTradeFeeBasisPoints = 20 * 100; // 20%; uint64 constant _maxWithdrawalFeeBasisPoints = 20 * 100; // 20%; /** * @notice Instantiate a new `Exchange` contract * * @dev Sets `_owner` and `_admin` to `msg.sender` */ constructor() public Owned() {} /** * @notice Sets the address of the `Custodian` contract * * @dev The `Custodian` accepts `Exchange` and `Governance` addresses in its constructor, after * which they can only be changed by the `Governance` contract itself. Therefore the `Custodian` * must be deployed last and its address set here on an existing `Exchange` contract. This value * is immutable once set and cannot be changed again * * @param newCustodian The address of the `Custodian` contract deployed against this `Exchange` * contract's address */ function setCustodian(address payable newCustodian) external onlyAdmin { require(_custodian == address(0x0), 'Custodian can only be set once'); require(Address.isContract(newCustodian), 'Invalid address'); _custodian = newCustodian; } /*** Tunable parameters ***/ /** * @notice Sets a new Chain Propagation Period - the block delay after which order nonce invalidations * are respected by `executeTrade` and wallet exits are respected by `executeTrade` and `withdraw` * * @param newChainPropagationPeriod The new Chain Propagation Period expressed as a number of blocks. Must * be less than `_maxChainPropagationPeriod` */ function setChainPropagationPeriod(uint256 newChainPropagationPeriod) external onlyAdmin { require( newChainPropagationPeriod < _maxChainPropagationPeriod, 'Must be less than 1 week' ); uint256 oldChainPropagationPeriod = _chainPropagationPeriod; _chainPropagationPeriod = newChainPropagationPeriod; emit ChainPropagationPeriodChanged( oldChainPropagationPeriod, newChainPropagationPeriod ); } /** * @notice Sets the address of the Fee wallet * * @dev Trade and Withdraw fees will accrue in the `_balancesInPips` mappings for this wallet * * @param newFeeWallet The new Fee wallet. Must be different from the current one */ function setFeeWallet(address newFeeWallet) external onlyAdmin { require(newFeeWallet != address(0x0), 'Invalid wallet address'); require( newFeeWallet != _feeWallet, 'Must be different from current fee wallet' ); address oldFeeWallet = _feeWallet; _feeWallet = newFeeWallet; emit FeeWalletChanged(oldFeeWallet, newFeeWallet); } // Accessors // /** * @notice Load a wallet's balance by asset address, in asset units * * @param wallet The wallet address to load the balance for. Can be different from `msg.sender` * @param assetAddress The asset address to load the wallet's balance for * * @return The quantity denominated in asset units of asset at `assetAddress` currently * deposited by `wallet` */ function loadBalanceInAssetUnitsByAddress( address wallet, address assetAddress ) external view returns (uint256) { require(wallet != address(0x0), 'Invalid wallet address'); Structs.Asset memory asset = _assetRegistry.loadAssetByAddress( assetAddress ); return AssetUnitConversions.pipsToAssetUnits( _balancesInPips[wallet][assetAddress], asset.decimals ); } /** * @notice Load a wallet's balance by asset address, in asset units * * @param wallet The wallet address to load the balance for. Can be different from `msg.sender` * @param assetSymbol The asset symbol to load the wallet's balance for * * @return The quantity denominated in asset units of asset `assetSymbol` currently deposited * by `wallet` */ function loadBalanceInAssetUnitsBySymbol( address wallet, string calldata assetSymbol ) external view returns (uint256) { require(wallet != address(0x0), 'Invalid wallet address'); Structs.Asset memory asset = _assetRegistry.loadAssetBySymbol( assetSymbol, getCurrentTimestampInMs() ); return AssetUnitConversions.pipsToAssetUnits( _balancesInPips[wallet][asset.assetAddress], asset.decimals ); } /** * @notice Load a wallet's balance by asset address, in pips * * @param wallet The wallet address to load the balance for. Can be different from `msg.sender` * @param assetAddress The asset address to load the wallet's balance for * * @return The quantity denominated in pips of asset at `assetAddress` currently deposited by `wallet` */ function loadBalanceInPipsByAddress(address wallet, address assetAddress) external view returns (uint64) { require(wallet != address(0x0), 'Invalid wallet address'); return _balancesInPips[wallet][assetAddress]; } /** * @notice Load a wallet's balance by asset symbol, in pips * * @param wallet The wallet address to load the balance for. Can be different from `msg.sender` * @param assetSymbol The asset symbol to load the wallet's balance for * * @return The quantity denominated in pips of asset with `assetSymbol` currently deposited by `wallet` */ function loadBalanceInPipsBySymbol( address wallet, string calldata assetSymbol ) external view returns (uint64) { require(wallet != address(0x0), 'Invalid wallet address'); address assetAddress = _assetRegistry .loadAssetBySymbol(assetSymbol, getCurrentTimestampInMs()) .assetAddress; return _balancesInPips[wallet][assetAddress]; } /** * @notice Load the address of the Fee wallet * * @return The address of the Fee wallet */ function loadFeeWallet() external view returns (address) { return _feeWallet; } /** * @notice Load the quantity filled so far for a partially filled orders * @dev Invalidating an order nonce will not clear partial fill quantities for earlier orders because * the gas cost would potentially be unbound * * @param orderHash The order hash as originally signed by placing wallet that uniquely identifies an order * * @return For partially filled orders, the amount filled so far in pips. For orders in all other states, 0 */ function loadPartiallyFilledOrderQuantityInPips(bytes32 orderHash) external view returns (uint64) { return _partiallyFilledOrderQuantitiesInPips[orderHash]; } // Depositing // /** * @notice Deposit ETH */ function depositEther() external payable { deposit(msg.sender, address(0x0), msg.value); } /** * @notice Deposit `IERC20` compliant tokens * * @param tokenAddress The token contract address * @param quantityInAssetUnits The quantity to deposit. The sending wallet must first call the `approve` method on * the token contract for at least this quantity first */ function depositTokenByAddress( IERC20 tokenAddress, uint256 quantityInAssetUnits ) external { require( address(tokenAddress) != address(0x0), 'Use depositEther to deposit Ether' ); deposit(msg.sender, address(tokenAddress), quantityInAssetUnits); } /** * @notice Deposit `IERC20` compliant tokens * * @param assetSymbol The case-sensitive symbol string for the token * @param quantityInAssetUnits The quantity to deposit. The sending wallet must first call the `approve` method on * the token contract for at least this quantity first */ function depositTokenBySymbol( string calldata assetSymbol, uint256 quantityInAssetUnits ) external { IERC20 tokenAddress = IERC20( _assetRegistry .loadAssetBySymbol(assetSymbol, getCurrentTimestampInMs()) .assetAddress ); require( address(tokenAddress) != address(0x0), 'Use depositEther to deposit ETH' ); deposit(msg.sender, address(tokenAddress), quantityInAssetUnits); } function deposit( address payable wallet, address assetAddress, uint256 quantityInAssetUnits ) private { // Calling exitWallet disables deposits immediately on mining, in contrast to withdrawals and // trades which respect the Chain Propagation Period given by `effectiveBlockNumber` via // `isWalletExitFinalized` require(!_walletExits[wallet].exists, 'Wallet exited'); Structs.Asset memory asset = _assetRegistry.loadAssetByAddress( assetAddress ); uint64 quantityInPips = AssetUnitConversions.assetUnitsToPips( quantityInAssetUnits, asset.decimals ); require(quantityInPips > 0, 'Quantity is too low'); // Convert from pips back into asset units to remove any fractional amount that is too small // to express in pips. If the asset is ETH, this leftover fractional amount accumulates as dust // in the `Exchange` contract. If the asset is a token the `Exchange` will call `transferFrom` // without this fractional amount and there will be no dust uint256 quantityInAssetUnitsWithoutFractionalPips = AssetUnitConversions .pipsToAssetUnits(quantityInPips, asset.decimals); // If the asset is ETH then the funds were already assigned to this contract via msg.value. If // the asset is a token, additionally call the transferFrom function on the token contract for // the pre-approved asset quantity if (assetAddress != address(0x0)) { AssetTransfers.transferFrom( wallet, IERC20(assetAddress), quantityInAssetUnitsWithoutFractionalPips ); } // Forward the funds to the `Custodian` AssetTransfers.transferTo( _custodian, assetAddress, quantityInAssetUnitsWithoutFractionalPips ); uint64 newExchangeBalanceInPips = _balancesInPips[wallet][assetAddress].add( quantityInPips ); uint256 newExchangeBalanceInAssetUnits = AssetUnitConversions .pipsToAssetUnits(newExchangeBalanceInPips, asset.decimals); // Update balance with actual transferred quantity _balancesInPips[wallet][assetAddress] = newExchangeBalanceInPips; _depositIndex++; emit Deposited( _depositIndex, wallet, assetAddress, asset.symbol, asset.symbol, quantityInPips, newExchangeBalanceInPips, newExchangeBalanceInAssetUnits ); } // Invalidation // /** * @notice Invalidate all order nonces with a timestampInMs lower than the one provided * * @param nonce A Version 1 UUID. After calling and once the Chain Propagation Period has elapsed, * `executeTrade` will reject order nonces from this wallet with a timestampInMs component lower than * the one provided */ function invalidateOrderNonce(uint128 nonce) external { uint64 timestampInMs = UUID.getTimestampInMsFromUuidV1(nonce); // Enforce a maximum skew for invalidating nonce timestamps in the future so the user doesn't // lock their wallet from trades indefinitely require( timestampInMs < getOneDayFromNowInMs(), 'Nonce timestamp too far in future' ); if (_nonceInvalidations[msg.sender].exists) { require( _nonceInvalidations[msg.sender].timestampInMs < timestampInMs, 'Nonce timestamp already invalidated' ); require( _nonceInvalidations[msg.sender].effectiveBlockNumber <= block.number, 'Previous invalidation awaiting chain propagation' ); } // Changing the Chain Propagation Period will not affect the effectiveBlockNumber for this invalidation uint256 effectiveBlockNumber = block.number + _chainPropagationPeriod; _nonceInvalidations[msg.sender] = NonceInvalidation( true, timestampInMs, effectiveBlockNumber ); emit OrderNonceInvalidated( msg.sender, nonce, timestampInMs, effectiveBlockNumber ); } // Withdrawing // /** * @notice Settles a user withdrawal submitted off-chain. Calls restricted to currently whitelisted Dispatcher wallet * * @param withdrawal A `Structs.Withdrawal` struct encoding the parameters of the withdrawal */ function withdraw(Structs.Withdrawal memory withdrawal) public override onlyDispatcher { // Validations require(!isWalletExitFinalized(withdrawal.walletAddress), 'Wallet exited'); require( getFeeBasisPoints(withdrawal.gasFeeInPips, withdrawal.quantityInPips) <= _maxWithdrawalFeeBasisPoints, 'Excessive withdrawal fee' ); bytes32 withdrawalHash = validateWithdrawalSignature(withdrawal); require( !_completedWithdrawalHashes[withdrawalHash], 'Hash already withdrawn' ); // If withdrawal is by asset symbol (most common) then resolve to asset address Structs.Asset memory asset = withdrawal.withdrawalType == Enums.WithdrawalType.BySymbol ? _assetRegistry.loadAssetBySymbol( withdrawal.assetSymbol, UUID.getTimestampInMsFromUuidV1(withdrawal.nonce) ) : _assetRegistry.loadAssetByAddress(withdrawal.assetAddress); // SafeMath reverts if balance is overdrawn uint64 netAssetQuantityInPips = withdrawal.quantityInPips.sub( withdrawal.gasFeeInPips ); uint256 netAssetQuantityInAssetUnits = AssetUnitConversions .pipsToAssetUnits(netAssetQuantityInPips, asset.decimals); uint64 newExchangeBalanceInPips = _balancesInPips[withdrawal .walletAddress][asset.assetAddress] .sub(withdrawal.quantityInPips); uint256 newExchangeBalanceInAssetUnits = AssetUnitConversions .pipsToAssetUnits(newExchangeBalanceInPips, asset.decimals); _balancesInPips[withdrawal.walletAddress][asset .assetAddress] = newExchangeBalanceInPips; _balancesInPips[_feeWallet][asset .assetAddress] = _balancesInPips[_feeWallet][asset.assetAddress].add( withdrawal.gasFeeInPips ); ICustodian(_custodian).withdraw( withdrawal.walletAddress, asset.assetAddress, netAssetQuantityInAssetUnits ); _completedWithdrawalHashes[withdrawalHash] = true; emit Withdrawn( withdrawal.walletAddress, asset.assetAddress, asset.symbol, withdrawal.quantityInPips, newExchangeBalanceInPips, newExchangeBalanceInAssetUnits ); } // Wallet exits // /** * @notice Flags the sending wallet as exited, immediately disabling deposits upon mining. * After the Chain Propagation Period passes trades and withdrawals are also disabled for the wallet, * and assets may then be withdrawn one at a time via `withdrawExit` */ function exitWallet() external { require(!_walletExits[msg.sender].exists, 'Wallet already exited'); _walletExits[msg.sender] = WalletExit( true, block.number + _chainPropagationPeriod ); emit WalletExited(msg.sender, block.number + _chainPropagationPeriod); } /** * @notice Withdraw the entire balance of an asset for an exited wallet. The Chain Propagation Period must * have already passed since calling `exitWallet` on `assetAddress` * * @param assetAddress The address of the asset to withdraw */ function withdrawExit(address assetAddress) external { require(isWalletExitFinalized(msg.sender), 'Wallet exit not finalized'); Structs.Asset memory asset = _assetRegistry.loadAssetByAddress( assetAddress ); uint64 balanceInPips = _balancesInPips[msg.sender][assetAddress]; uint256 balanceInAssetUnits = AssetUnitConversions.pipsToAssetUnits( balanceInPips, asset.decimals ); require(balanceInAssetUnits > 0, 'No balance for asset'); _balancesInPips[msg.sender][assetAddress] = 0; ICustodian(_custodian).withdraw( msg.sender, assetAddress, balanceInAssetUnits ); emit WalletExitWithdrawn( msg.sender, assetAddress, asset.symbol, balanceInPips, 0, 0 ); } /** * @notice Clears exited status of sending wallet. Upon mining immediately enables * deposits, trades, and withdrawals by sending wallet */ function clearWalletExit() external { require(_walletExits[msg.sender].exists, 'Wallet not exited'); delete _walletExits[msg.sender]; emit WalletExitCleared(msg.sender); } function isWalletExitFinalized(address wallet) internal view returns (bool) { WalletExit storage exit = _walletExits[wallet]; return exit.exists && exit.effectiveBlockNumber <= block.number; } // Trades // /** * @notice Settles a trade between two orders submitted and matched off-chain * * @dev As a gas optimization, base and quote symbols are passed in separately and combined to verify * the wallet hash, since this is cheaper than splitting the market symbol into its two constituent asset symbols * @dev Stack level too deep if declared external * * @param buy A `Structs.Order` struct encoding the parameters of the buy-side order (receiving base, giving quote) * @param sell A `Structs.Order` struct encoding the parameters of the sell-side order (giving base, receiving quote) * @param trade A `Structs.Trade` struct encoding the parameters of this trade execution of the counterparty orders */ function executeTrade( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) public override onlyDispatcher { require( !isWalletExitFinalized(buy.walletAddress), 'Buy wallet exit finalized' ); require( !isWalletExitFinalized(sell.walletAddress), 'Sell wallet exit finalized' ); require( buy.walletAddress != sell.walletAddress, 'Self-trading not allowed' ); validateAssetPair(buy, sell, trade); validateLimitPrices(buy, sell, trade); validateOrderNonces(buy, sell); (bytes32 buyHash, bytes32 sellHash) = validateOrderSignatures( buy, sell, trade ); validateTradeFees(trade); updateOrderFilledQuantities(buy, buyHash, sell, sellHash, trade); updateBalancesForTrade(buy, sell, trade); emit TradeExecuted( buy.walletAddress, sell.walletAddress, trade.baseAssetSymbol, trade.quoteAssetSymbol, trade.baseAssetSymbol, trade.quoteAssetSymbol, trade.grossBaseQuantityInPips, trade.grossQuoteQuantityInPips, trade.priceInPips, buyHash, sellHash ); } // Updates buyer, seller, and fee wallet balances for both assets in trade pair according to trade parameters function updateBalancesForTrade( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) private { // Seller gives base asset including fees _balancesInPips[sell.walletAddress][trade .baseAssetAddress] = _balancesInPips[sell.walletAddress][trade .baseAssetAddress] .sub(trade.grossBaseQuantityInPips); // Buyer receives base asset minus fees _balancesInPips[buy.walletAddress][trade .baseAssetAddress] = _balancesInPips[buy.walletAddress][trade .baseAssetAddress] .add(trade.netBaseQuantityInPips); // Buyer gives quote asset including fees _balancesInPips[buy.walletAddress][trade .quoteAssetAddress] = _balancesInPips[buy.walletAddress][trade .quoteAssetAddress] .sub(trade.grossQuoteQuantityInPips); // Seller receives quote asset minus fees _balancesInPips[sell.walletAddress][trade .quoteAssetAddress] = _balancesInPips[sell.walletAddress][trade .quoteAssetAddress] .add(trade.netQuoteQuantityInPips); // Maker and taker fees to fee wallet _balancesInPips[_feeWallet][trade .makerFeeAssetAddress] = _balancesInPips[_feeWallet][trade .makerFeeAssetAddress] .add(trade.makerFeeQuantityInPips); _balancesInPips[_feeWallet][trade .takerFeeAssetAddress] = _balancesInPips[_feeWallet][trade .takerFeeAssetAddress] .add(trade.takerFeeQuantityInPips); } function updateOrderFilledQuantities( Structs.Order memory buyOrder, bytes32 buyOrderHash, Structs.Order memory sellOrder, bytes32 sellOrderHash, Structs.Trade memory trade ) private { updateOrderFilledQuantity(buyOrder, buyOrderHash, trade); updateOrderFilledQuantity(sellOrder, sellOrderHash, trade); } // Update filled quantities tracking for order to prevent over- or double-filling orders function updateOrderFilledQuantity( Structs.Order memory order, bytes32 orderHash, Structs.Trade memory trade ) private { require(!_completedOrderHashes[orderHash], 'Order double filled'); // Total quantity of above filled as a result of all trade executions, including this one uint64 newFilledQuantityInPips; // Market orders can express quantity in quote terms, and can be partially filled by multiple // limit maker orders necessitating tracking partially filled amounts in quote terms to // determine completion if (order.isQuantityInQuote) { require( isMarketOrderType(order.orderType), 'Order quote quantity only valid for market orders' ); newFilledQuantityInPips = trade.grossQuoteQuantityInPips.add( _partiallyFilledOrderQuantitiesInPips[orderHash] ); } else { // All other orders track partially filled quantities in base terms newFilledQuantityInPips = trade.grossBaseQuantityInPips.add( _partiallyFilledOrderQuantitiesInPips[orderHash] ); } require( newFilledQuantityInPips <= order.quantityInPips, 'Order overfilled' ); if (newFilledQuantityInPips < order.quantityInPips) { // If the order was partially filled, track the new filled quantity _partiallyFilledOrderQuantitiesInPips[orderHash] = newFilledQuantityInPips; } else { // If the order was completed, delete any partial fill tracking and instead track its completion // to prevent future double fills delete _partiallyFilledOrderQuantitiesInPips[orderHash]; _completedOrderHashes[orderHash] = true; } } // Validations // function validateAssetPair( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) private view { require( trade.baseAssetAddress != trade.quoteAssetAddress, 'Base and quote assets must be different' ); // Buy order market pair Structs.Asset memory buyBaseAsset = _assetRegistry.loadAssetBySymbol( trade.baseAssetSymbol, UUID.getTimestampInMsFromUuidV1(buy.nonce) ); Structs.Asset memory buyQuoteAsset = _assetRegistry.loadAssetBySymbol( trade.quoteAssetSymbol, UUID.getTimestampInMsFromUuidV1(buy.nonce) ); require( buyBaseAsset.assetAddress == trade.baseAssetAddress && buyQuoteAsset.assetAddress == trade.quoteAssetAddress, 'Buy order market symbol address resolution mismatch' ); // Sell order market pair Structs.Asset memory sellBaseAsset = _assetRegistry.loadAssetBySymbol( trade.baseAssetSymbol, UUID.getTimestampInMsFromUuidV1(sell.nonce) ); Structs.Asset memory sellQuoteAsset = _assetRegistry.loadAssetBySymbol( trade.quoteAssetSymbol, UUID.getTimestampInMsFromUuidV1(sell.nonce) ); require( sellBaseAsset.assetAddress == trade.baseAssetAddress && sellQuoteAsset.assetAddress == trade.quoteAssetAddress, 'Sell order market symbol address resolution mismatch' ); // Fee asset validation require( trade.makerFeeAssetAddress == trade.baseAssetAddress || trade.makerFeeAssetAddress == trade.quoteAssetAddress, 'Maker fee asset is not in trade pair' ); require( trade.takerFeeAssetAddress == trade.baseAssetAddress || trade.takerFeeAssetAddress == trade.quoteAssetAddress, 'Taker fee asset is not in trade pair' ); require( trade.makerFeeAssetAddress != trade.takerFeeAssetAddress, 'Maker and taker fee assets must be different' ); } function validateLimitPrices( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) private pure { require( trade.grossBaseQuantityInPips > 0, 'Base quantity must be greater than zero' ); require( trade.grossQuoteQuantityInPips > 0, 'Quote quantity must be greater than zero' ); if (isLimitOrderType(buy.orderType)) { require( getImpliedQuoteQuantityInPips( trade.grossBaseQuantityInPips, buy.limitPriceInPips ) >= trade.grossQuoteQuantityInPips, 'Buy order limit price exceeded' ); } if (isLimitOrderType(sell.orderType)) { require( getImpliedQuoteQuantityInPips( trade.grossBaseQuantityInPips, sell.limitPriceInPips ) <= trade.grossQuoteQuantityInPips, 'Sell order limit price exceeded' ); } } function validateTradeFees(Structs.Trade memory trade) private pure { uint64 makerTotalQuantityInPips = trade.makerFeeAssetAddress == trade.baseAssetAddress ? trade.grossBaseQuantityInPips : trade.grossQuoteQuantityInPips; require( getFeeBasisPoints( trade.makerFeeQuantityInPips, makerTotalQuantityInPips ) <= _maxTradeFeeBasisPoints, 'Excessive maker fee' ); uint64 takerTotalQuantityInPips = trade.takerFeeAssetAddress == trade.baseAssetAddress ? trade.grossBaseQuantityInPips : trade.grossQuoteQuantityInPips; require( getFeeBasisPoints( trade.takerFeeQuantityInPips, takerTotalQuantityInPips ) <= _maxTradeFeeBasisPoints, 'Excessive taker fee' ); require( trade.netBaseQuantityInPips.add( trade.makerFeeAssetAddress == trade.baseAssetAddress ? trade.makerFeeQuantityInPips : trade.takerFeeQuantityInPips ) == trade.grossBaseQuantityInPips, 'Net base plus fee is not equal to gross' ); require( trade.netQuoteQuantityInPips.add( trade.makerFeeAssetAddress == trade.quoteAssetAddress ? trade.makerFeeQuantityInPips : trade.takerFeeQuantityInPips ) == trade.grossQuoteQuantityInPips, 'Net quote plus fee is not equal to gross' ); } function validateOrderSignatures( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) private pure returns (bytes32, bytes32) { bytes32 buyOrderHash = validateOrderSignature(buy, trade); bytes32 sellOrderHash = validateOrderSignature(sell, trade); return (buyOrderHash, sellOrderHash); } function validateOrderSignature( Structs.Order memory order, Structs.Trade memory trade ) private pure returns (bytes32) { bytes32 orderHash = Signatures.getOrderWalletHash( order, trade.baseAssetSymbol, trade.quoteAssetSymbol ); require( Signatures.isSignatureValid( orderHash, order.walletSignature, order.walletAddress ), order.side == Enums.OrderSide.Buy ? 'Invalid wallet signature for buy order' : 'Invalid wallet signature for sell order' ); return orderHash; } function validateOrderNonces( Structs.Order memory buy, Structs.Order memory sell ) private view { require( UUID.getTimestampInMsFromUuidV1(buy.nonce) > getLastInvalidatedTimestamp(buy.walletAddress), 'Buy order nonce timestamp too low' ); require( UUID.getTimestampInMsFromUuidV1(sell.nonce) > getLastInvalidatedTimestamp(sell.walletAddress), 'Sell order nonce timestamp too low' ); } function validateWithdrawalSignature(Structs.Withdrawal memory withdrawal) private pure returns (bytes32) { bytes32 withdrawalHash = Signatures.getWithdrawalWalletHash(withdrawal); require( Signatures.isSignatureValid( withdrawalHash, withdrawal.walletSignature, withdrawal.walletAddress ), 'Invalid wallet signature' ); return withdrawalHash; } // Asset registry // /** * @notice Initiate registration process for a token asset. Only `IERC20` compliant tokens can be * added - ETH is hardcoded in the registry * * @param tokenAddress The address of the `IERC20` compliant token contract to add * @param symbol The symbol identifying the token asset * @param decimals The decimal precision of the token */ function registerToken( IERC20 tokenAddress, string calldata symbol, uint8 decimals ) external onlyAdmin { _assetRegistry.registerToken(tokenAddress, symbol, decimals); emit TokenRegistered(tokenAddress, symbol, decimals); } /** * @notice Finalize registration process for a token asset. All parameters must exactly match a previous * call to `registerToken` * * @param tokenAddress The address of the `IERC20` compliant token contract to add * @param symbol The symbol identifying the token asset * @param decimals The decimal precision of the token */ function confirmTokenRegistration( IERC20 tokenAddress, string calldata symbol, uint8 decimals ) external onlyAdmin { _assetRegistry.confirmTokenRegistration(tokenAddress, symbol, decimals); emit TokenRegistrationConfirmed(tokenAddress, symbol, decimals); } /** * @notice Add a symbol to a token that has already been registered and confirmed * * @param tokenAddress The address of the `IERC20` compliant token contract the symbol will identify * @param symbol The symbol identifying the token asset */ function addTokenSymbol(IERC20 tokenAddress, string calldata symbol) external onlyAdmin { _assetRegistry.addTokenSymbol(tokenAddress, symbol); emit TokenSymbolAdded(tokenAddress, symbol); } /** * @notice Loads an asset descriptor struct by its symbol and timestamp * * @dev Since multiple token addresses can potentially share the same symbol (in case of a token * swap/contract upgrade) the provided `timestampInMs` is compared against each asset's * `confirmedTimestampInMs` to uniquely determine the newest asset for the symbol at that point in time * * @param assetSymbol The asset's symbol * @param timestampInMs Point in time used to disambiguate multiple tokens with same symbol * * @return A `Structs.Asset` record describing the asset */ function loadAssetBySymbol(string calldata assetSymbol, uint64 timestampInMs) external view returns (Structs.Asset memory) { return _assetRegistry.loadAssetBySymbol(assetSymbol, timestampInMs); } // Dispatcher whitelisting // /** * @notice Sets the wallet whitelisted to dispatch transactions calling the `executeTrade` and `withdraw` functions * * @param newDispatcherWallet The new whitelisted dispatcher wallet. Must be different from the current one */ function setDispatcher(address newDispatcherWallet) external onlyAdmin { require(newDispatcherWallet != address(0x0), 'Invalid wallet address'); require( newDispatcherWallet != _dispatcherWallet, 'Must be different from current dispatcher' ); address oldDispatcherWallet = _dispatcherWallet; _dispatcherWallet = newDispatcherWallet; emit DispatcherChanged(oldDispatcherWallet, newDispatcherWallet); } /** * @notice Clears the currently set whitelisted dispatcher wallet, effectively disabling calling the * `executeTrade` and `withdraw` functions until a new wallet is set with `setDispatcher` */ function removeDispatcher() external onlyAdmin { emit DispatcherChanged(_dispatcherWallet, address(0x0)); _dispatcherWallet = address(0x0); } modifier onlyDispatcher() { require(msg.sender == _dispatcherWallet, 'Caller is not dispatcher'); _; } // Utils // function isLimitOrderType(Enums.OrderType orderType) private pure returns (bool) { return orderType == Enums.OrderType.Limit || orderType == Enums.OrderType.LimitMaker || orderType == Enums.OrderType.StopLossLimit || orderType == Enums.OrderType.TakeProfitLimit; } function isMarketOrderType(Enums.OrderType orderType) private pure returns (bool) { return orderType == Enums.OrderType.Market || orderType == Enums.OrderType.StopLoss || orderType == Enums.OrderType.TakeProfit; } function getCurrentTimestampInMs() private view returns (uint64) { uint64 msInOneSecond = 1000; return uint64(block.timestamp) * msInOneSecond; } function getFeeBasisPoints(uint64 fee, uint64 total) private pure returns (uint64) { uint64 basisPointsInTotal = 100 * 100; // 100 basis points/percent * 100 percent/total return fee.mul(basisPointsInTotal).div(total); } function getImpliedQuoteQuantityInPips( uint64 baseQuantityInPips, uint64 limitPriceInPips ) private pure returns (uint64) { // To convert a fractional price to integer pips, shift right by the pip precision of 8 decimals uint256 pipsMultiplier = 10**8; uint256 impliedQuoteQuantityInPips = uint256(baseQuantityInPips) .mul(uint256(limitPriceInPips)) .div(pipsMultiplier); require( impliedQuoteQuantityInPips < 2**64, 'Implied quote pip quantity overflows uint64' ); return uint64(impliedQuoteQuantityInPips); } function getLastInvalidatedTimestamp(address walletAddress) private view returns (uint64) { if ( _nonceInvalidations[walletAddress].exists && _nonceInvalidations[walletAddress].effectiveBlockNumber <= block.number ) { return _nonceInvalidations[walletAddress].timestampInMs; } return 0; } function getOneDayFromNowInMs() private view returns (uint64) { uint64 secondsInOneDay = 24 * 60 * 60; // 24 hours/day * 60 min/hour * 60 seconds/min uint64 msInOneSecond = 1000; return (uint64(block.timestamp) + secondsInOneDay) * msInOneSecond; } }
Distinguishes between withdrawals by asset symbol or address UUIDv1 unique to wallet Address of wallet to which funds will be returned Asset symbol Asset address Withdrawal quantity Gas fee deducted from withdrawn quantity to cover dispatcher tx costs Not currently used but reserved for future use. Must be true The ECDSA signature of the withdrawal hash as produced by Signatures.getWithdrawalWalletHash
struct Withdrawal { Enums.WithdrawalType withdrawalType; uint128 nonce; address payable walletAddress; string assetSymbol; uint64 quantityInPips; uint64 gasFeeInPips; bool autoDispatchEnabled; bytes walletSignature; }
7,513,026
[ 1, 5133, 14344, 1468, 281, 3086, 598, 9446, 1031, 635, 3310, 3273, 578, 1758, 5866, 90, 21, 3089, 358, 9230, 5267, 434, 9230, 358, 1492, 284, 19156, 903, 506, 2106, 10494, 3273, 10494, 1758, 3423, 9446, 287, 10457, 31849, 14036, 11140, 853, 329, 628, 598, 9446, 82, 10457, 358, 5590, 7393, 2229, 22793, 2288, 4551, 1399, 1496, 8735, 364, 3563, 999, 18, 6753, 506, 638, 1021, 7773, 19748, 3372, 434, 326, 598, 9446, 287, 1651, 487, 14929, 635, 4383, 2790, 18, 588, 1190, 9446, 287, 16936, 2310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 3423, 9446, 287, 288, 203, 203, 203, 565, 6057, 87, 18, 1190, 9446, 287, 559, 598, 9446, 287, 559, 31, 203, 203, 203, 565, 2254, 10392, 7448, 31, 203, 203, 203, 565, 1758, 8843, 429, 9230, 1887, 31, 203, 203, 203, 565, 533, 3310, 5335, 31, 203, 203, 203, 203, 203, 565, 2254, 1105, 10457, 382, 52, 7146, 31, 203, 203, 203, 565, 2254, 1105, 16189, 14667, 382, 52, 7146, 31, 203, 203, 203, 565, 1426, 3656, 5325, 1526, 31, 203, 203, 203, 565, 1731, 9230, 5374, 31, 203, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.6; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "./interfaces/IVaultConfig.sol"; import "./interfaces/IWorkerConfig.sol"; import "./interfaces/InterestModel.sol"; contract ConfigurableInterestVaultConfig is IVaultConfig, OwnableUpgradeSafe { /// The minimum debt size per position. uint256 public override minDebtSize; /// The portion of interests allocated to the reserve pool. uint256 public override getReservePoolBps; /// The reward for successfully killing a position. uint256 public override getKillBps; /// Mapping for worker address to its configuration. mapping(address => IWorkerConfig) public workers; /// Interest rate model InterestModel public interestModel; // address for wrapped native eg WBNB, WETH address public wrappedNative; // address for wNtive Relayer address public wNativeRelayer; // address of fairLaunch contract address public fairLaunch; function initialize( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel, address _wrappedNative, address _wNativeRelayer, address _fairLaunch ) public initializer { OwnableUpgradeSafe.__Ownable_init(); setParams( _minDebtSize, _reservePoolBps, _killBps, _interestModel, _wrappedNative, _wNativeRelayer, _fairLaunch); } /// @dev Set all the basic parameters. Must only be called by the owner. /// @param _minDebtSize The new minimum debt size value. /// @param _reservePoolBps The new interests allocated to the reserve pool value. /// @param _killBps The new reward for killing a position value. /// @param _interestModel The new interest rate model contract. function setParams( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel, address _wrappedNative, address _wNativeRelayer, address _fairLaunch ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; wrappedNative = _wrappedNative; wNativeRelayer = _wNativeRelayer; fairLaunch = _fairLaunch; } /// @dev Set the configuration for the given workers. Must only be called by the owner. function setWorkers(address[] calldata addrs, IWorkerConfig[] calldata configs) external onlyOwner { require(addrs.length == configs.length, "ConfigurableInterestVaultConfig::setWorkers:: bad length"); for (uint256 idx = 0; idx < addrs.length; idx++) { workers[addrs[idx]] = configs[idx]; } } /// @dev Return the address of wrapped native token function getWrappedNativeAddr() external view override returns (address) { return wrappedNative; } function getWNativeRelayer() external view override returns (address) { return wNativeRelayer; } /// @dev Return the address of fair launch contract function getFairLaunchAddr() external view override returns (address) { return fairLaunch; } /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view override returns (uint256) { return interestModel.getInterestRate(debt, floating); } /// @dev Return whether the given address is a worker. function isWorker(address worker) external view override returns (bool) { return address(workers[worker]) != address(0); } /// @dev Return whether the given worker accepts more debt. Revert on non-worker. function acceptDebt(address worker) external view override returns (bool) { return workers[worker].acceptDebt(worker); } /// @dev Return the work factor for the worker + debt, using 1e4 as denom. Revert on non-worker. function workFactor(address worker, uint256 debt) external view override returns (uint256) { return workers[worker].workFactor(worker, debt); } /// @dev Return the kill factor for the worker + debt, using 1e4 as denom. Revert on non-worker. function killFactor(address worker, uint256 debt) external view override returns (uint256) { return workers[worker].killFactor(worker, debt); } }
@dev Set all the basic parameters. Must only be called by the owner. @param _minDebtSize The new minimum debt size value. @param _reservePoolBps The new interests allocated to the reserve pool value. @param _killBps The new reward for killing a position value. @param _interestModel The new interest rate model contract.
function setParams( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel, address _wrappedNative, address _wNativeRelayer, address _fairLaunch ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; wrappedNative = _wrappedNative; wNativeRelayer = _wNativeRelayer; fairLaunch = _fairLaunch; }
5,358,099
[ 1, 694, 777, 326, 5337, 1472, 18, 6753, 1338, 506, 2566, 635, 326, 3410, 18, 225, 389, 1154, 758, 23602, 1225, 1021, 394, 5224, 18202, 88, 963, 460, 18, 225, 389, 455, 6527, 2864, 38, 1121, 1021, 394, 16513, 87, 11977, 358, 326, 20501, 2845, 460, 18, 225, 389, 16418, 38, 1121, 1021, 394, 19890, 364, 417, 5789, 279, 1754, 460, 18, 225, 389, 2761, 395, 1488, 1021, 394, 16513, 4993, 938, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 31705, 12, 203, 565, 2254, 5034, 389, 1154, 758, 23602, 1225, 16, 203, 565, 2254, 5034, 389, 455, 6527, 2864, 38, 1121, 16, 203, 565, 2254, 5034, 389, 16418, 38, 1121, 16, 203, 565, 5294, 395, 1488, 389, 2761, 395, 1488, 16, 203, 565, 1758, 389, 18704, 9220, 16, 203, 565, 1758, 389, 91, 9220, 1971, 1773, 16, 203, 565, 1758, 389, 507, 481, 9569, 203, 225, 262, 1071, 1338, 5541, 288, 203, 565, 1131, 758, 23602, 1225, 273, 389, 1154, 758, 23602, 1225, 31, 203, 565, 31792, 6527, 2864, 38, 1121, 273, 389, 455, 6527, 2864, 38, 1121, 31, 203, 565, 16566, 737, 38, 1121, 273, 389, 16418, 38, 1121, 31, 203, 565, 16513, 1488, 273, 389, 2761, 395, 1488, 31, 203, 565, 5805, 9220, 273, 389, 18704, 9220, 31, 203, 565, 341, 9220, 1971, 1773, 273, 389, 91, 9220, 1971, 1773, 31, 203, 565, 284, 1826, 9569, 273, 389, 507, 481, 9569, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; // 'interface': // this is expected from another contract, // where tokens (ERC20) are managed contract Erc20TokensContract { function transfer(address _to, uint256 _value); // returns (bool success); // not in CoinOffering Corporation.sol function balanceOf(address acc) returns (uint); } contract ICO { Erc20TokensContract erc20TokensContract; address public erc20TokensContractAddress; bool erc20TokensContractSet = false; // address public erc20TokensContractAddress; // bool erc20TokensContractAddressSet = false; uint public priceToBuyInFinney; // price in finney (0.001 ETH) uint priceToBuyInWei; // --> to reduce gas in buyTokens address public owner; mapping (address => bool) public isManager; // holds managers // for price chart: mapping (uint => uint[3]) public priceChange; // number of change => [priceToBuyInFinney, block.number, block.timestamp] uint public currentPriceChangeNumber = 0; // for deals chart: mapping (uint => uint[4]) public deals; // number of change => [priceInFinney, quantity, block.number, block.timestamp] uint public dealsNumber = 0; /* ---- Creates contract */ function ICO() {// - truffle compiles only no args Constructor owner = msg.sender; isManager[msg.sender] = true; priceToBuyInFinney = 0; // with price 0 tokens sale stopped priceToBuyInWei = finneyToWei(priceToBuyInFinney); priceChange[0] = [priceToBuyInFinney, block.number, block.timestamp]; } function setErc20TokensContract(address _erc20TokensContractAddress) returns (bool){ if (msg.sender != owner) {throw;} if (erc20TokensContractSet) {throw;} erc20TokensContract = Erc20TokensContract(_erc20TokensContractAddress); erc20TokensContractAddress = _erc20TokensContractAddress; erc20TokensContractSet = true; TokensContractAddressSet(_erc20TokensContractAddress, msg.sender); return true; } event TokensContractAddressSet(address tokensContractAddress, address setBy); /* ------- Utilities: */ // function weiToEther(uint _wei) internal returns (uint){ // return _wei / 1000000000000000000; // } // // function etherToWei(uint _ether) internal returns (uint){ // return _ether * 1000000000000000000; // } function weiToFinney(uint _wei) internal returns (uint){ return _wei / (1000000000000000000 * 1000); } function finneyToWei(uint _finney) internal returns (uint){ return _finney * (1000000000000000000 / 1000); } /* --- universal Event */ event Result(address transactionInitiatedBy, string message); /* administrative functions */ // change owner: function changeOwner(address _newOwner) returns (bool){ if (msg.sender != owner) {throw;} owner = _newOwner; isManager[_newOwner] = true; OwnerChanged(msg.sender, owner); return true; } event OwnerChanged(address oldOwner, address newOwner); // --- set managers function setManager(address _newManager) returns (bool){ if (msg.sender == owner) { isManager[_newManager] = true; ManagersChanged("manager added", _newManager); return true; } else throw; } // remove managers function removeManager(address _manager) returns (bool){ if (msg.sender == owner) { isManager[_manager] = false; ManagersChanged("manager removed", _manager); return true; } else throw; } event ManagersChanged(string change, address manager); // set new price for tokens: function setNewPriceInFinney(uint _priceToBuyInFinney) returns (bool){ if (msg.sender != owner || !isManager[msg.sender]) {throw;} priceToBuyInFinney = _priceToBuyInFinney; priceToBuyInWei = finneyToWei(priceToBuyInFinney); currentPriceChangeNumber++; priceChange[currentPriceChangeNumber] = [priceToBuyInFinney, block.number, block.timestamp]; PriceChanged(priceToBuyInFinney, msg.sender); return true; } event PriceChanged(uint newPriceToBuyInFinney, address changedBy); function getPriceChange(uint _index) constant returns (uint[3]){ return priceChange[_index]; // array } // ---- buy tokens: // if you get message: // "It seems this transaction will fail. If you submit it, it may consume // all the gas you send", // or // "The contract won't allow this transaction to be executed" // that may be means that price has changed, just wait a few minutes // and repeat transaction function buyTokens(uint _quantity, uint _priceToBuyInFinney) payable returns (bool){ if (priceToBuyInFinney <= 0) {throw;} // if priceToBuy == 0 selling stops; // if (_priceToBuyInFinney <= 0) {throw;} // if (_quantity <= 0) {throw;} if (priceToBuyInFinney != _priceToBuyInFinney) { // Result(msg.sender, "transaction failed: price already changed"); throw; } if ( (msg.value / priceToBuyInWei) != _quantity ) { // Result(msg.sender, "provided sum is not correct for this amount of tokens"); throw; } // if everything is O.K. make transfer (~ 37046 gas): // check balance in token contract: uint currentBalance = erc20TokensContract.balanceOf(this); if (erc20TokensContract.balanceOf(this) < _quantity) {throw;} else { // make transfer erc20TokensContract.transfer(msg.sender, _quantity); // check if tx changed erc20TokensContract: if (currentBalance == erc20TokensContract.balanceOf(this)) { throw; } // record this : dealsNumber = dealsNumber + 1; deals[dealsNumber] = [_priceToBuyInFinney, _quantity, block.number, block.timestamp]; // event Deal(msg.sender, _priceToBuyInFinney, _quantity); return true; } } // event BuyTokensError(address transactionFrom, string error); // if throw - no events event Deal(address to, uint priceInFinney, uint quantity); function transferTokensTo(address _to, uint _quantity) returns (bool) { if (msg.sender != owner) {throw;} if (_quantity <= 0) {throw;} // check balance in token contract: if (erc20TokensContract.balanceOf(this) < _quantity) { throw; } else { // make transfer erc20TokensContract.transfer(_to, _quantity); // event: TokensTransfer(msg.sender, _to, _quantity); return true; } } function transferAllTokensToOwner() returns (bool) { return transferTokensTo(owner, erc20TokensContract.balanceOf(this)); } event TokensTransfer (address from, address to, uint quantity); function transferTokensToContractOwner(uint _quantity) returns (bool) { return transferTokensTo(msg.sender, _quantity); } /* --- functions for ETH */ function withdraw(uint _sumToWithdrawInFinney) returns (bool) { if (msg.sender != owner) {throw;} if (_sumToWithdrawInFinney <= 0) {throw;} if (this.balance < finneyToWei(_sumToWithdrawInFinney)) { throw; } if (msg.sender == owner) {// double check if (!msg.sender.send(finneyToWei(_sumToWithdrawInFinney))) {// makes withdrawal and returns true or false // Withdrawal(msg.sender, _sumToWithdrawInFinney, "withdrawal: failed"); return false; } else { Withdrawal(msg.sender, _sumToWithdrawInFinney, "withdrawal: success"); return true; } } } function withdrawAllToOwner() returns (bool) { return withdraw(this.balance); } event Withdrawal(address to, uint sumToWithdrawInFinney, string message); }
address public erc20TokensContractAddress; bool erc20TokensContractAddressSet = false; for price chart: number of change => [priceToBuyInFinney, block.number, block.timestamp] for deals chart: number of change => [priceInFinney, quantity, block.number, block.timestamp] with price 0 tokens sale stopped
contract ICO { Erc20TokensContract erc20TokensContract; address public erc20TokensContractAddress; bool erc20TokensContractSet = false; address public owner; mapping (uint => uint[3]) public priceChange; uint public currentPriceChangeNumber = 0; mapping (uint => uint[4]) public deals; uint public dealsNumber = 0; owner = msg.sender; isManager[msg.sender] = true; priceToBuyInFinney = 0; priceToBuyInWei = finneyToWei(priceToBuyInFinney); priceChange[0] = [priceToBuyInFinney, block.number, block.timestamp]; }
12,738,907
[ 1, 2867, 1071, 6445, 71, 3462, 5157, 8924, 1887, 31, 1426, 6445, 71, 3462, 5157, 8924, 1887, 694, 273, 629, 31, 364, 6205, 4980, 30, 1300, 434, 2549, 516, 306, 8694, 774, 38, 9835, 382, 6187, 82, 402, 16, 1203, 18, 2696, 16, 1203, 18, 5508, 65, 364, 443, 1031, 4980, 30, 1300, 434, 2549, 516, 306, 8694, 382, 6187, 82, 402, 16, 10457, 16, 1203, 18, 2696, 16, 1203, 18, 5508, 65, 598, 6205, 374, 2430, 272, 5349, 9627, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 3865, 288, 203, 203, 565, 512, 1310, 3462, 5157, 8924, 6445, 71, 3462, 5157, 8924, 31, 203, 203, 565, 1758, 1071, 6445, 71, 3462, 5157, 8924, 1887, 31, 203, 203, 565, 1426, 6445, 71, 3462, 5157, 8924, 694, 273, 629, 31, 203, 203, 203, 203, 565, 1758, 1071, 3410, 31, 203, 203, 203, 565, 2874, 261, 11890, 516, 2254, 63, 23, 5717, 1071, 6205, 3043, 31, 203, 565, 2254, 1071, 783, 5147, 3043, 1854, 273, 374, 31, 203, 203, 565, 2874, 261, 11890, 516, 2254, 63, 24, 5717, 1071, 443, 1031, 31, 203, 565, 2254, 1071, 443, 1031, 1854, 273, 374, 31, 203, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 353, 1318, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 6205, 774, 38, 9835, 382, 6187, 82, 402, 273, 374, 31, 203, 3639, 6205, 774, 38, 9835, 382, 3218, 77, 273, 574, 82, 402, 774, 3218, 77, 12, 8694, 774, 38, 9835, 382, 6187, 82, 402, 1769, 203, 3639, 6205, 3043, 63, 20, 65, 273, 306, 8694, 774, 38, 9835, 382, 6187, 82, 402, 16, 1203, 18, 2696, 16, 1203, 18, 5508, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // 'FRT' Staking smart contract // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // SafeMath library // ---------------------------------------------------------------------------- /** * @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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); function burnTokens(uint256 _amount) external; event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract FairyStake is Owned { using SafeMath for uint256; address public FRT = 0x35DfdAD99DD022adbB63754aEbc9365f66B29807; uint256 public totalStakes = 0; uint256 stakingFee = 25; // 2.5% uint256 unstakingFee = 25; // 2.5% uint256 public totalDividends = 0; uint256 private scaledRemainder = 0; uint256 private scaling = uint256(10) ** 12; uint public round = 1; struct USER{ uint256 stakedTokens; uint256 lastDividends; uint256 fromTotalDividend; uint round; uint256 remainder; } mapping(address => USER) stakers; mapping (uint => uint256) public payouts; // keeps record of each payout event STAKED(address staker, uint256 tokens, uint256 stakingFee); event UNSTAKED(address staker, uint256 tokens, uint256 unstakingFee); event PAYOUT(uint256 round, uint256 tokens, address sender); event CLAIMEDREWARD(address staker, uint256 reward); // ------------------------------------------------------------------------ // Token holders can stake their tokens using this function // @param tokens number of tokens to stake // ------------------------------------------------------------------------ function STAKE(uint256 tokens) external { require(IERC20(FRT).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user account"); uint256 _stakingFee = 0; if(totalStakes > 0) _stakingFee= (onePercent(tokens).mul(stakingFee)).div(10); if(totalStakes > 0) // distribute the staking fee accumulated before updating the user's stake _addPayout(_stakingFee); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = (tokens.sub(_stakingFee)).add(stakers[msg.sender].stakedTokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; totalStakes = totalStakes.add(tokens.sub(_stakingFee)); emit STAKED(msg.sender, tokens.sub(_stakingFee), _stakingFee); } // ------------------------------------------------------------------------ // Owners can send the funds to be distributed to stakers using this function // @param tokens number of tokens to distribute // ------------------------------------------------------------------------ function ADDFUNDS(uint256 tokens) external { require(IERC20(FRT).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account"); _addPayout(tokens); } // ------------------------------------------------------------------------ // Private function to register payouts // ------------------------------------------------------------------------ function _addPayout(uint256 tokens) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 available = (tokens.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalStakes); scaledRemainder = available.mod(totalStakes); totalDividends = totalDividends.add(dividendPerToken); payouts[round] = payouts[round-1].add(dividendPerToken); emit PAYOUT(round, tokens, msg.sender); round++; } // ------------------------------------------------------------------------ // Stakers can claim their pending rewards using this function // ------------------------------------------------------------------------ function CLAIMREWARD() public { if(totalDividends > stakers[msg.sender].fromTotalDividend){ uint256 owing = pendingReward(msg.sender); owing = owing.add(stakers[msg.sender].remainder); stakers[msg.sender].remainder = 0; require(IERC20(FRT).transfer(msg.sender,owing), "ERROR: error in sending reward from contract"); emit CLAIMEDREWARD(msg.sender, owing); stakers[msg.sender].lastDividends = owing; // unscaled stakers[msg.sender].round = round; // update the round stakers[msg.sender].fromTotalDividend = totalDividends; // scaled } } // ------------------------------------------------------------------------ // Get the pending rewards of the staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function pendingReward(address staker) private returns (uint256) { uint256 amount = ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)).div(scaling); stakers[staker].remainder += ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return amount; } function getPendingReward(address staker) public view returns(uint256 _pendingReward) { uint256 amount = ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)).div(scaling); amount += ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return (amount + stakers[staker].remainder); } // ------------------------------------------------------------------------ // Stakers can un stake the staked tokens using this function // @param tokens the number of tokens to withdraw // ------------------------------------------------------------------------ function WITHDRAW(uint256 tokens) external { require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; require(IERC20(FRT).transfer(msg.sender, tokens.sub(_unstakingFee)), "Error in un-staking tokens"); stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; totalStakes = totalStakes.sub(tokens); if(totalStakes > 0) // distribute the un staking fee accumulated after updating the user's stake _addPayout(_unstakingFee); emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee); } // ------------------------------------------------------------------------ // Private function to calculate 1% percentage // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) private pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } // ------------------------------------------------------------------------ // Get the number of tokens staked by a staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function yourStakedFRT(address staker) external view returns(uint256 stakedFRT){ return stakers[staker].stakedTokens; } // ------------------------------------------------------------------------ // Get the FRT balance of the token holder // @param user the address of the token holder // ------------------------------------------------------------------------ function yourFRTBalance(address user) external view returns(uint256 FRTBalance){ return IERC20(FRT).balanceOf(user); } }
------------------------------------------------------------------------ Stakers can un stake the staked tokens using this function @param tokens the number of tokens to withdraw ------------------------------------------------------------------------ add pending rewards to remainder to be claimed by user later, if there is any existing stake distribute the un staking fee accumulated after updating the user's stake
function WITHDRAW(uint256 tokens) external { require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10); uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; require(IERC20(FRT).transfer(msg.sender, tokens.sub(_unstakingFee)), "Error in un-staking tokens"); stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; totalStakes = totalStakes.sub(tokens); if(totalStakes > 0) _addPayout(_unstakingFee); emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee); }
2,342,932
[ 1, 29461, 934, 581, 414, 848, 640, 384, 911, 326, 384, 9477, 2430, 1450, 333, 445, 225, 2430, 326, 1300, 434, 2430, 358, 598, 9446, 8879, 17082, 527, 4634, 283, 6397, 358, 10022, 358, 506, 7516, 329, 635, 729, 5137, 16, 309, 1915, 353, 1281, 2062, 384, 911, 25722, 326, 640, 384, 6159, 14036, 24893, 1839, 9702, 326, 729, 1807, 384, 911, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13601, 40, 10821, 12, 11890, 5034, 2430, 13, 3903, 288, 203, 540, 203, 3639, 2583, 12, 334, 581, 414, 63, 3576, 18, 15330, 8009, 334, 9477, 5157, 1545, 2430, 597, 2430, 405, 374, 16, 315, 1941, 1147, 3844, 358, 598, 9446, 8863, 203, 540, 203, 3639, 2254, 5034, 389, 23412, 6159, 14667, 273, 261, 476, 8410, 12, 7860, 2934, 16411, 12, 23412, 6159, 14667, 13, 2934, 2892, 12, 2163, 1769, 203, 540, 203, 3639, 2254, 5034, 2523, 310, 273, 4634, 17631, 1060, 12, 3576, 18, 15330, 1769, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 2764, 25407, 1011, 2523, 310, 31, 203, 1171, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 9981, 56, 2934, 13866, 12, 3576, 18, 15330, 16, 2430, 18, 1717, 24899, 23412, 6159, 14667, 13, 3631, 315, 668, 316, 640, 17, 334, 6159, 2430, 8863, 203, 540, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 334, 9477, 5157, 273, 384, 581, 414, 63, 3576, 18, 15330, 8009, 334, 9477, 5157, 18, 1717, 12, 7860, 1769, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 2722, 7244, 350, 5839, 273, 2523, 310, 31, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 2080, 5269, 7244, 26746, 33, 2078, 7244, 350, 5839, 31, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 2260, 273, 225, 3643, 31, 203, 540, 203, 3639, 2078, 510, 3223, 273, 2078, 510, 3223, 18, 1717, 12, 7860, 1769, 203, 540, 203, 3639, 309, 12, 4963, 510, 3223, 405, 2 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; contract Sample { uint public stateInt; bool public stateBool; uint public counter; constructor() public { stateInt = 1; stateBool = false; } function setStateVar(uint _stateInt, bool _stateBool) public { stateInt = _stateInt; stateBool = _stateBool; } // Used in unit tests to simulate graceful deploy and compute receipt handling of callbacks that fail due to // out of gas errors. This function contains a very large loop, that eventually fails due to out of gas. function setStateVarGasFail(uint _stateInt, bool _stateBool) public { stateInt = _stateInt; stateBool = _stateBool; for (uint i = 0; i < 1000000; i++) { stateInt = i; stateBool = (i % 2 == 0); } } function setStateVarRevert(uint _stateInt, bool _stateBool) public { stateInt = _stateInt; stateBool = _stateBool; require(false, "Failed in eth call"); } function incrementCounter() public { counter++; } }
Used in unit tests to simulate graceful deploy and compute receipt handling of callbacks that fail due to out of gas errors. This function contains a very large loop, that eventually fails due to out of gas.
function setStateVarGasFail(uint _stateInt, bool _stateBool) public { stateInt = _stateInt; stateBool = _stateBool; for (uint i = 0; i < 1000000; i++) { stateInt = i; stateBool = (i % 2 == 0); } }
14,084,404
[ 1, 6668, 316, 2836, 7434, 358, 20089, 24279, 7286, 471, 3671, 16030, 5057, 434, 6689, 716, 2321, 6541, 358, 596, 434, 16189, 1334, 18, 1220, 445, 1914, 279, 8572, 7876, 2798, 16, 716, 18011, 6684, 6541, 358, 596, 434, 16189, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12947, 1537, 27998, 3754, 12, 11890, 389, 2019, 1702, 16, 1426, 389, 2019, 7464, 13, 1071, 288, 203, 3639, 919, 1702, 273, 389, 2019, 1702, 31, 203, 3639, 919, 7464, 273, 389, 2019, 7464, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 15088, 31, 277, 27245, 288, 203, 5411, 919, 1702, 273, 277, 31, 203, 5411, 919, 7464, 273, 261, 77, 738, 576, 422, 374, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import "./IBEP20.sol"; import "./SafeMath.sol"; import "./IERC900.sol"; contract Staking is IERC900 { using SafeMath for uint256; // Token used for staking IBEP20 stakingToken; uint256 public index; mapping(uint256 => Stake) private stakes; mapping(address => uint256) private stakingFor; // Set node info mapping(address => P2PInfo) private nodes; struct Stake { uint256 expiry; uint256 amount; address stakedFor; } struct P2PInfo { bytes32 pubkey; bytes32 rewardAddress; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, address(this), _amount), "Stake required" ); _; } /** * @dev Constructor function * @param _stakingToken ERC20/BEP20 The address of the token contract used for staking */ constructor(IBEP20 _stakingToken) public { stakingToken = _stakingToken; index = 0; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes memory _data) public { _stake(msg.sender, _amount, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor( address _user, uint256 _amount, bytes memory _data ) public { _stake(_user, _amount, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes memory _data) public { _unstake(msg.sender, _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakingFor[_address]; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(address(this)); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return address(stakingToken); } function supportsHistory() public pure returns (bool) { return false; } /** @TODO: add getter for each stakes like function getStake(uint256 stakeID) */ /** * @param _addr The address of validator set */ function getNodeInfo(address _addr) public view returns (bytes32, bytes32) { P2PInfo memory info = nodes[_addr]; return (info.pubkey, info.rewardAddress); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _data bytes optional data to include in the Stake event. We are using for locktime period for each stake. */ function _stake( address _address, uint256 _amount, bytes memory _data ) internal canStake(_address, _amount) { (uint256 expiry, bytes32 pubkey, bytes32 rewardAddress) = decodeBytes( _data ); // TODO: validate timestamp stakes[index] = Stake(expiry, _amount, _address); stakingFor[_address] = stakingFor[_address].add(_amount); // Update node info nodes[_address] = P2PInfo(pubkey, rewardAddress); // Staked event. the logger needs to decode event to time on client side. // Data == 0x + index + _data emit Staked( _address, _amount, totalStakedFor(_address), joinLogData(index, _data) ); index++; } function _unstake( address _address, uint256 _amount, bytes memory _data ) internal { (uint256 stakeID, , ) = decodeBytes(_data); Stake memory target = stakes[stakeID]; // The target amount should be same as input amount. require( target.amount == _amount, "The unstake amount does not match the target amount" ); require( target.stakedFor == _address, "The address does not match the target address" ); require( block.timestamp >= target.expiry, "The target stake is not expired" ); require( stakingToken.transfer(target.stakedFor, _amount), "Unable to withdraw stake" ); // Reduced staking amount of current staker. stakingFor[target.stakedFor] = stakingFor[target.stakedFor].sub( _amount ); // Removed a stake and gas is refunded. delete (stakes[stakeID]); // Unstaked event. the logger needs to decode event to time on client side. // Data == 0x + stakeID emit Unstaked( target.stakedFor, _amount, totalStakedFor(target.stakedFor), _data ); } function joinLogData(uint256 stakeID, bytes memory data) internal pure returns (bytes memory) { return abi.encodePacked(stakeID, data); } function decodeBytes(bytes memory _data) internal pure returns ( uint256, bytes32, bytes32 ) { require(_data.length.mod(32) == 0, "slicing out of range"); uint256 expiry; bytes32 pubkey; bytes32 rewardAddress; assembly { expiry := mload(add(_data, 32)) pubkey := mload(add(_data, 64)) rewardAddress := mload(add(_data, 96)) } return (expiry, pubkey, rewardAddress); } }
* @dev Constructor function @param _stakingToken ERC20/BEP20 The address of the token contract used for staking/
constructor(IBEP20 _stakingToken) public { stakingToken = _stakingToken; index = 0; }
5,435,510
[ 1, 6293, 445, 225, 389, 334, 6159, 1345, 4232, 39, 3462, 19, 5948, 52, 3462, 1021, 1758, 434, 326, 1147, 6835, 1399, 364, 384, 6159, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 45, 5948, 52, 3462, 389, 334, 6159, 1345, 13, 1071, 288, 203, 3639, 384, 6159, 1345, 273, 389, 334, 6159, 1345, 31, 203, 3639, 770, 273, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; address public ICOAddress; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the ico. */ modifier onlyICO() { require(msg.sender == ICOAddress); _; } modifier onlyOwnerOrICO() { require(msg.sender == ICOAddress || msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function setICOAddress(address _icoAddress) public onlyOwner { require(_icoAddress != address(0)); ICOAddress = _icoAddress; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = true; /** * @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() onlyOwnerOrICO whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); 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); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, Pausable{ using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { return _transfer(_to, _value); } function ownerTransfer(address _to, uint256 _value) onlyOwnerOrICO public returns (bool) { return _transfer(_to, _value); } function _transfer(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @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) whenNotPaused public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenNotPaused public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) whenNotPaused public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) whenNotPaused public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) whenNotPaused public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract OPKToken is StandardToken { address public teamAddress; address public advisorsAddress; address public reserveAddress; string public constant name = "OPK"; // solium-disable-line uppercase string public constant symbol = "OPK"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 50000000 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } }
* @dev Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval(address _spender, uint256 _subtractedValue) whenNotPaused public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
47,938
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1717, 1575, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1717, 1575, 329, 620, 13, 1347, 1248, 28590, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 11144, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 15533, 203, 3639, 309, 261, 67, 1717, 1575, 329, 620, 405, 11144, 13, 288, 203, 5411, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 31, 203, 5411, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 11144, 18, 1717, 24899, 1717, 1575, 329, 620, 1769, 203, 3639, 289, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.12; import "chainlink/v0.5/contracts/Oracle.sol"; import "../contracts/UniswapExchangeInterface.sol"; import "../contracts/AaveLendingInterface.sol"; import "../contracts/ATokenInterface.sol"; /// @title Flannel Internal Contract /// @author hill399 (github.com/hill399) /// @notice Internal and helper functions for main Flannel contract (Flannel.sol) contract IFlannel is Ownable { using SafeMath for uint256; Oracle internal oracle; UniswapExchangeInterface internal linkExchangeInterface; LendingPool internal lendingPool; LinkTokenInterface internal stdLinkTokenInterface; LinkTokenInterface internal aaveLinkTokenInterface; AToken internal aLinkTokenInterface; uint256 constant FINNEY = 1 * 10 ** 15; uint256 constant ETHER = 1 * 10 ** 18; /* Address of user node */ address internal linkNode; /* Lending pool approval address */ address internal lendingPoolApproval; address[2] internal whitelistAddresses; /* Struct to customise and store allowances */ struct thresholds { string paramsName; uint256 pcUntouched; uint256 pcAave; uint256 pcTopUp; uint256 linkThreshold; uint256 ethThreshold; uint256 aaveThreshold; uint256 ethTopUp; } /* Mapping to hold customised allowances */ thresholds public userStoredParams; uint256 public storeBalance; uint256 public aaveBalance; uint256 public topUpBalance; modifier whitelistedAddresses() { require(msg.sender == whitelistAddresses[0] || msg.sender == whitelistAddresses[1], "Invalid caller"); _; } /// @notice Withdraw earned LINK balance from deployed oracle contract. /// @dev Only node address can call this. /// @dev Function selector : 0x61ff4fac function _withdrawFromOracle(uint256 _amount) internal whitelistedAddresses { oracle.withdraw(address(this), _amount); storeBalance = storeBalance.add(_percentHelper(_amount, userStoredParams.pcUntouched)); aaveBalance = aaveBalance.add(_percentHelper(_amount, userStoredParams.pcAave)); topUpBalance = topUpBalance.add(_percentHelper(_amount, userStoredParams.pcTopUp)); } /// @notice Deposit withdrawn LINK into Aave Protocol /// @dev On testnet, Aave utilise their own LINK token. On test launch, a given amount is send to Flannel so that "representative" /// transactions can be made. /// @dev Only node address can call this. /// @dev Function selector : 0x06197c1c function _depositToAave(uint256 _amount) internal whitelistedAddresses { require(_amount <= aaveBalance, "Not enough allocated Aave Deposit funds"); // Approve for aaveLINK tokens to be moved by the lending interface. aaveLinkTokenInterface.approve(lendingPoolApproval, _amount + 100); // Deposit aaveLINK into interest bearing contract. lendingPool.deposit(address(aaveLinkTokenInterface), _amount, 0); aaveBalance = aaveBalance.sub(_amount); } /// @notice Withdraw deposited LINK into Aave Protocol /// @dev Only node address can call this. function _withdrawFromAave(uint256 _amount) internal whitelistedAddresses { // Catch that _amount is greater thzan contract aLINK balance. require(_amount <= getALinkBalance(), "Not enough aLINK in contract"); // Redeem LINK using aLINK redeem function. aLinkTokenInterface.redeem(_amount); // Return LINK to Aave balance store aaveBalance = aaveBalance.add(_amount); } /// @notice Convert LINK balance to ETH via Uniswap and send to node. /// @dev Only node address can call this. function _linkToEthTopUp(uint256 _amount, bool _auto) internal whitelistedAddresses { require(_amount <= topUpBalance, "Not enough LINK to top-up"); // Catch if topUpBalance is less than ethTopUp uint256 topBalance; if(_amount >= userStoredParams.ethTopUp && _auto) { topBalance = userStoredParams.ethTopUp; } else { topBalance = _amount; } // Get current LINK -> ETH conversion rate uint256 exchangeRate = getLinkToEthPrice(topBalance); // Approve uniswap for transfer stdLinkTokenInterface.approve(address(linkExchangeInterface), topBalance); // Send to node address linkExchangeInterface.tokenToEthTransferOutput(exchangeRate, topBalance, (now + 1 hours), linkNode); // Reset topUpBalance topUpBalance = topUpBalance.sub(topBalance); } function getLinkToEthPrice(uint256 _amount) public view returns (uint256) { return linkExchangeInterface.getTokenToEthInputPrice(_amount); } function getOracleWithdrawable() public view returns (uint256) { return oracle.withdrawable(); } function getALinkBalance() public view returns (uint256) { return aLinkTokenInterface.balanceOf(address(this)); } /// @notice Helper function to generate percentage of value /// @dev (_value/100) * _percentage function _percentHelper(uint256 _value, uint256 _percentage) internal pure returns (uint256) { uint256 tmpPer = _value.div(100); tmpPer = tmpPer.mul(_percentage); return tmpPer; } }
Address of user node */ Lending pool approval address */ Struct to customise and store allowances */
struct thresholds { string paramsName; uint256 pcUntouched; uint256 pcAave; uint256 pcTopUp; uint256 linkThreshold; uint256 ethThreshold; uint256 aaveThreshold; uint256 ethTopUp; } uint256 public storeBalance; uint256 public aaveBalance; uint256 public topUpBalance; modifier whitelistedAddresses()
5,536,257
[ 1, 1887, 434, 729, 756, 342, 511, 2846, 2845, 23556, 1758, 342, 7362, 358, 1679, 784, 471, 1707, 1699, 6872, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 19983, 288, 203, 3639, 533, 859, 461, 31, 203, 3639, 2254, 5034, 6125, 57, 496, 1395, 2049, 31, 203, 3639, 2254, 5034, 6125, 37, 836, 31, 203, 3639, 2254, 5034, 6125, 3401, 1211, 31, 203, 3639, 2254, 5034, 1692, 7614, 31, 203, 3639, 2254, 5034, 13750, 7614, 31, 203, 3639, 2254, 5034, 279, 836, 7614, 31, 203, 3639, 2254, 5034, 13750, 3401, 1211, 31, 203, 565, 289, 203, 203, 203, 565, 2254, 5034, 1071, 1707, 13937, 31, 203, 565, 2254, 5034, 1071, 279, 836, 13937, 31, 203, 565, 2254, 5034, 1071, 1760, 1211, 13937, 31, 203, 203, 565, 9606, 26944, 7148, 1435, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-02 */ // File: @openzeppelin/contracts/math/SafeMath.sol // 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/utils/Address.sol 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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.7.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)); } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.7.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: localhost/contracts/BTCPriceBet.sol pragma solidity 0.7.6; /** * @dev Players make bets for future BTC price. ETH and own Token can be used for staking */ contract BTCPriceBet is AccessControl { using SafeMath for uint256; bool paused; uint8 constant public PRIZE_PERCENTAGE = 30; uint64 constant private PRICE_MAX = 10e9; // < 1M uint256 constant private INITIAL_BET_DURATION = 10 minutes; uint256 constant private BET_ALLOWED_DURATION = 50 minutes; bytes32 constant private PRICE_FEED_ROLE = "PRICE_FEED_ROLE"; bytes32 constant private OWNER_ROLE = "OWNER"; uint256 public betEth; uint256 public betTokens; uint256 public ongoingRound; uint256 public roundStartedAt; uint256 public roundDuration; address public token; struct Bet { address account; uint256 timestamp; uint64 price; } struct HistoryBet { bool isEth; uint256 timestamp; uint64 price; } mapping(address => mapping(address => HistoryBet[])) private betHistory; // token => (address => HistoryBet[]) mapping(address => uint64[]) public pricesUsed; // token => price[], 0x0 - ETH mapping(address => mapping(uint256 => mapping(uint256 => Bet[]))) private betsForRound; // token => (round => (price => Bet)), 0x0 - ETH mapping(address => mapping(address => uint256)) private lastRoundWithBetMade; // token => (address => round), 0x0 - ETH mapping(address => uint256) public betsNumber; // token => bets, 0x0 - ETH mapping(address => mapping(address => uint256)) private prizeWithdrawn; // token => (address => amount), 0x0 - ETH mapping(address => mapping(address => uint256)) private prizeToWithdraw; // token => (address => amount), 0x0 - ETH mapping(address => mapping(uint256 => uint64[4])) private priceAndWinningPricesForRound; // token => uint64[], 0x0 - ETH mapping(address => uint256) private devFee; // token => fee event BetMade(); event RoundFinished(); /*** * @notice Starts betting round. * @dev Contract constructor. * @param _token Token address. * @param _priceFeed Address, that should be used as price feed. */ constructor(address _token, address _priceFeed) { require(_token != address(0), "Wrong token"); require(_priceFeed != address(0), "Wrong PRICE_FEED_ROLE"); token = _token; betEth = 2e16; // 0.02 ETH betTokens = 10e2; // 1000 roundDuration = 1 hours; roundStartedAt = block.timestamp; ongoingRound = 1; _setupRole(PRICE_FEED_ROLE, _priceFeed); _setupRole(OWNER_ROLE, msg.sender); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /*** * @dev Makes bet. * @param _token Token address. * @param _price Price value. */ function makeBet(address _token, uint64[] calldata _prices) external payable { require(!paused, "Paused"); require(_token == address(0) || _token == token, "Wrong token"); uint256 pricesNumber = _prices.length; require(pricesNumber > 0, "Wrong prices num"); require(block.timestamp < roundStartedAt.add(BET_ALLOWED_DURATION), "No more bets"); if (block.timestamp <= roundStartedAt.add(INITIAL_BET_DURATION)) { if (lastRoundWithBetMade[_token][msg.sender] != ongoingRound) { lastRoundWithBetMade[_token][msg.sender] = ongoingRound; } } else { require(lastRoundWithBetMade[_token][msg.sender] == ongoingRound, "Not allowed to bet"); } if (_token == address(0)) { require(msg.value == betEth.mul(pricesNumber), "Wrong betEth"); } else { require(msg.value == 0, "Remove eth value"); IERC20(token).transferFrom(msg.sender, address(this), betTokens.mul(pricesNumber)); } for(uint256 i = 0; i < pricesNumber; i ++) { uint64 price = _prices[i]; require((price > 0) && (price < PRICE_MAX), "Wrong price"); if (betsForRound[_token][ongoingRound][price].length == 0) { pricesUsed[_token].push(price); } betsForRound[_token][ongoingRound][price].push(Bet(msg.sender, block.timestamp, price)); betHistory[_token][msg.sender].push(HistoryBet(_token == address(0), block.timestamp, price)); } betsNumber[_token] = betsNumber[_token].add(pricesNumber); emit BetMade(); } /*** * @dev Finishes ongoing round. * @param _price Price value. * @param _winnerPricesETH Prices for ETH bets. * @param _winnerPricesToken Prices for Token bets. */ function finishRound(uint64 _price, uint64[3] memory _winnerPricesETH, uint64[3] memory _winnerPricesToken) external { require(hasRole(PRICE_FEED_ROLE, msg.sender), "Not PRICE_FEED_ROLE"); require(block.timestamp > roundStartedAt.add(roundDuration), "Not finished yet"); priceAndWinningPricesForRound[address(0)][ongoingRound][0] = _price; priceAndWinningPricesForRound[token][ongoingRound][0] = _price; uint256 betsEth = betsNumber[address(0)].mul(betEth); uint256 betsToken = betsNumber[token].mul(betTokens); uint256 prizeEth = betsEth.mul(PRIZE_PERCENTAGE).div(100); uint256 prizeToken = betsToken.mul(PRIZE_PERCENTAGE).div(100); uint256 prizeUsedEth; uint256 prizeUsedToken; for (uint8 i = 0; i < _winnerPricesETH.length; i++) { if (betsForRound[address(0)][ongoingRound][_winnerPricesETH[i]].length > 0) { address winner = betsForRound[address(0)][ongoingRound][_winnerPricesETH[i]][0].account; prizeToWithdraw[address(0)][winner] = prizeToWithdraw[address(0)][winner].add(prizeEth); priceAndWinningPricesForRound[address(0)][ongoingRound][i+1] = _winnerPricesETH[i]; prizeUsedEth = prizeUsedEth.add(prizeEth); } if (betsForRound[token][ongoingRound][_winnerPricesToken[i]].length > 0) { address winner = betsForRound[token][ongoingRound][_winnerPricesToken[i]][0].account; prizeToWithdraw[token][winner] = prizeToWithdraw[token][winner].add(prizeToken); priceAndWinningPricesForRound[token][ongoingRound][i+1] = _winnerPricesToken[i]; prizeUsedToken = prizeUsedToken.add(prizeToken); } } // if only 1 player, he gets all prizes. if (betsEth > 0) { if (prizeUsedEth == prizeEth) { address winner = betsForRound[address(0)][ongoingRound][_winnerPricesETH[0]][0].account; prizeToWithdraw[address(0)][winner] = prizeToWithdraw[address(0)][winner].add(prizeEth.mul(2)); prizeUsedEth = prizeUsedEth.mul(3); } devFee[address(0)] = devFee[address(0)].add(betsEth.sub(prizeUsedEth)); } if (betsToken > 0) { if (prizeUsedToken == prizeToken) { address winner = betsForRound[token][ongoingRound][_winnerPricesToken[0]][0].account; prizeToWithdraw[token][winner] = prizeToWithdraw[token][winner].add(prizeToken.mul(2)); prizeUsedToken = prizeUsedToken.mul(3); } devFee[token] = devFee[token].add(betsToken.sub(prizeUsedToken)); } // clear, update data delete pricesUsed[address(0)]; delete pricesUsed[token]; delete betsNumber[address(0)]; delete betsNumber[token]; ongoingRound = ongoingRound.add(1); roundStartedAt = block.timestamp; emit RoundFinished(); } /*** * @dev Withdraws prize. * @param _token Token address. */ function withdrawPrize(address _token) external { uint256 prize = getPrizeToWithdraw(_token); require(prize > 0, "No prize"); if (_token == address(0)) { msg.sender.transfer(prize); } else { require(IERC20(_token).transfer(msg.sender, prize), "Transfer failed"); } delete prizeToWithdraw[_token][msg.sender]; prizeWithdrawn[_token][msg.sender] = prizeWithdrawn[_token][msg.sender].add(prize); } /*** * @dev Gets pending prize for sender. * @param _token Token address. * @return Prize amount. */ function getPrizeToWithdraw(address _token) public view returns(uint256) { require(_token == address(0) || _token == token, "Wrong token"); return prizeToWithdraw[_token][msg.sender]; } /*** * @dev Gets prize withdrawn amount. * @param _token Token address. * @return Prize withdrawn. */ function getPrizeWithdrawn(address _token) external view returns(uint256) { require(_token == address(0) || _token == token, "Wrong token"); return prizeWithdrawn[_token][msg.sender]; } /*** * @dev Withdraws dev fee. * @param _token Token address. */ function withdrawDevFee(address _token) external { uint256 fee = getDevFee(_token); require(fee > 0, "No fee"); delete devFee[_token]; if (_token == address(0)) { msg.sender.transfer(fee); } else { require(IERC20(_token).transfer(msg.sender, fee), "Transfer failed"); } } /*** * @dev Gets dev fee. * @param _token Token address. * @return dev fee. */ function getDevFee(address _token) public view returns(uint256) { require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE"); require(_token == address(0) || _token == token, "Wrong token"); return devFee[_token]; } /*** * @dev Prices used for ongoing round. * @param _token Token address. * @return Prices used. */ function getPricesUsed(address _token) external view returns (uint64[] memory) { require(_token == address(0) || _token == token, "Wrong token"); return pricesUsed[_token]; } /*** * @dev Gets BTC price and winning prices for round. * @param _token Token address. * @param _round Round index. * @return prices Prices. */ function getPriceAndWinningPricesForRound(address _token, uint256 _round) external view returns(uint64[4] memory) { require(_token == address(0) || _token == token, "Wrong token"); require(_round < ongoingRound, "Wrong round"); return priceAndWinningPricesForRound[_token][_round]; } /*** * @dev Gets BTC price and winning prices for round. * @param _token Token address. * @param _round Round index. * @param _price Price. * @return Bet properties list (accounts[], timestamps[], prices[]). */ function getBetsForRoundForPrice(address _token, uint256 _round, uint64 _price) view external returns(address[] memory, uint256[] memory, uint64[] memory) { require(_token == address(0) || _token == token, "Wrong token"); require((_price > 0) && (_price < PRICE_MAX), "Wrong price"); Bet[] storage bets = betsForRound[_token][_round][_price]; uint256 betsLength = bets.length; address[] memory accounts = new address[](betsLength); uint256[] memory timestamps = new uint256[](betsLength); uint64[] memory prices = new uint64[](betsLength); for (uint256 i = 0; i < betsLength; i ++) { accounts[i] = bets[i].account; timestamps[i] = bets[i].timestamp; prices[i] = bets[i].price; } return (accounts, timestamps, prices); } /*** * @dev Gets last round, when sender participated. * @param _token Token address. * @return Round idx. */ function getLastRoundWithBetMade(address _token) view external returns (uint256) { require(_token == address(0) || _token == token, "Wrong token"); return lastRoundWithBetMade[_token][msg.sender]; } /*** * @dev Gets bets count for sender. * @param _token Token address. * @return Bets count idx. */ function getBetHistoryCountFor(address _token) view external returns (uint256) { return betHistory[_token][msg.sender].length; } /*** * @dev Gets bet history count for sender. * @param _token Token address. * @param _idxStart Index to start. * @param _idxEnd Index to end. * @return Bet list. */ function getBetHistoryFor(address _token, uint256 _idxStart, uint256 _idxEnd) view external returns (bool[] memory, uint256[] memory, uint64[] memory) { HistoryBet[] storage bets = betHistory[_token][msg.sender]; uint256 betsLength = bets.length; if (betsLength == 0) { return(new bool[](0), new uint256[](0), new uint64[](0)); } uint256 start = 0; uint256 end = betsLength.sub(1); if (_idxEnd > 0) { require(_idxStart < _idxEnd && _idxEnd < betsLength, "Wrong idxs"); start = _idxStart; end = _idxEnd; } uint256 arrLength = end.sub(start).add(1); bool[] memory isEth = new bool[](arrLength); uint256[] memory timestamps = new uint256[](arrLength); uint64[] memory prices = new uint64[](arrLength); for (uint256 i = start; i <= end; i ++) { isEth[i] = bets[i].isEth; timestamps[i] = bets[i].timestamp; prices[i] = bets[i].price; } return (isEth, timestamps, prices); } /*** * @dev Updates bet value for eth. * @param _isToken Update bet for token or eth. * @param _value Bet value to be used. */ function updateBet(bool _isToken, uint256 _value) external { require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE"); require(_value > 0, "Wrong bet value"); (_isToken) ? betTokens = _value : betEth = _value; } /*** * @dev Updates round duration. * @param _duration Duration value to be used. */ function updateRoundDuration(uint256 _duration) external { require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE"); require(_duration > 0, "Wrong duration"); roundDuration = _duration; } /*** * @dev Pauses / unpauses betting functional. * @param _isPaused Set paused value. */ function setPaused(bool _isPaused) external { require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE"); paused = _isPaused; } /*** * @dev Kills Smart Contract. */ function kill() external { require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE"); selfdestruct(payable(msg.sender)); } }
token => (address => HistoryBet[])
mapping(address => mapping(address => HistoryBet[])) private betHistory;
1,974,020
[ 1, 2316, 516, 261, 2867, 516, 16058, 38, 278, 63, 5717, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 16058, 38, 278, 8526, 3719, 3238, 2701, 5623, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xf132f2c8F1EedE27070E0850775436A0E6e7268A/sources/src/Origamasks.sol
* @dev Tracker minted on Public/
function numberMintedPublic(address address_) external view returns (uint256) { return publicMints[address_]; }
8,430,264
[ 1, 8135, 312, 474, 329, 603, 7224, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1300, 49, 474, 329, 4782, 12, 2867, 1758, 67, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 1071, 49, 28142, 63, 2867, 67, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x242d75C9B2d79a7B5B70Ea009cDed173D38cE836/sources/contracts/treasury/interfaces/TreasuryStorageV2.sol
* @title Storage for Treasury @notice For future upgrades, do not change TreasuryStorageV2. Create a new contract which implements TreasuryStorageV2 and following the naming convention TreasuryStorageVX./
abstract contract TreasuryStorageV2 is TreasuryStorageV1 { IDonationMiner public override donationMiner; ITreasuryLpSwap public override lpSwap; mapping(address => Token) public override tokens; EnumerableSet.AddressSet internal _tokenList; IERC20 public override PACT; pragma solidity 0.8.4; }
13,250,502
[ 1, 3245, 364, 399, 266, 345, 22498, 225, 2457, 3563, 28844, 16, 741, 486, 2549, 399, 266, 345, 22498, 3245, 58, 22, 18, 1788, 279, 394, 6835, 1492, 4792, 399, 266, 345, 22498, 3245, 58, 22, 471, 3751, 326, 14634, 15797, 399, 266, 345, 22498, 3245, 58, 60, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 399, 266, 345, 22498, 3245, 58, 22, 353, 399, 266, 345, 22498, 3245, 58, 21, 288, 203, 565, 1599, 265, 367, 2930, 264, 1071, 3849, 2727, 367, 2930, 264, 31, 203, 565, 24142, 266, 345, 22498, 48, 84, 12521, 1071, 3849, 12423, 12521, 31, 203, 565, 2874, 12, 2867, 516, 3155, 13, 1071, 3849, 2430, 31, 203, 565, 6057, 25121, 694, 18, 1887, 694, 2713, 389, 2316, 682, 31, 203, 565, 467, 654, 39, 3462, 1071, 3849, 453, 6526, 31, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x28f083f2115fbE136F2c664E90DBc27429C55c9F/sources/src/Exchanger.sol
@inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == this.commitTrade.selector ^ this.resolveTrade.selector ^ this.resolveTradeWithReport.selector ^ this.getDelay.selector ^ this.setDelay.selector ^ this.getLookupURL.selector ^ this.setLookupURL.selector ^ this.getVerifierProxyAddress.selector ^ this.setVerifierProxyAddress.selector; }
7,079,574
[ 1, 36, 10093, 467, 654, 39, 28275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 3639, 3903, 203, 3639, 16618, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 1560, 548, 422, 203, 5411, 333, 18, 7371, 22583, 18, 9663, 3602, 203, 7734, 333, 18, 10828, 22583, 18, 9663, 3602, 203, 7734, 333, 18, 10828, 22583, 1190, 4820, 18, 9663, 3602, 203, 7734, 333, 18, 588, 6763, 18, 9663, 3602, 203, 7734, 333, 18, 542, 6763, 18, 9663, 3602, 203, 7734, 333, 18, 588, 6609, 1785, 18, 9663, 3602, 203, 7734, 333, 18, 542, 6609, 1785, 18, 9663, 3602, 203, 7734, 333, 18, 588, 17758, 3886, 1887, 18, 9663, 3602, 203, 7734, 333, 18, 542, 17758, 3886, 1887, 18, 9663, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./ERC721.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; contract CrypteriumWars is ERC721, Ownable { using SafeMath for uint256; //-------------------------------------------------------------------------- // Events //-------------------------------------------------------------------------- event NewCommander(string _name, address indexed _owner, uint _id); event ChangeName(string _oldName, string _newName, address indexed _owner, uint id); event HarvestCrypterium(uint _amount, address indexed _owner, uint _id); event ProduceInfantry(uint _amount, address indexed _owner, uint _id); event ProduceVehicle(uint _amount, address indexed _owner, uint _id); event ProduceAircraft(uint _amount, address indexed _owner, uint _id); event AttackerWon( address indexed _attacker, uint _attackMultiplier, address indexed _defender, uint _defenseMultiplier, uint _amount ); event DefenderWon( address indexed _attacker, uint _attackMultiplier, address indexed _defender, uint _defenseMultiplier, uint _amount ); event MissionSucceeded( uint _missionLevel, uint _difficultyMultiplier, uint _totalPowerMultiplier, uint _reward, address indexed _owner, uint _id ); event MissionFailed( uint _missionLevel, uint _difficultyMultiplier, uint _totalPowerMultiplier, address indexed _owner, uint _id ); event SpecialMissionCompleted(address indexed _owner, uint _id); //-------------------------------------------------------------------------- // Variables //-------------------------------------------------------------------------- uint constant harvestCooldownTime = 1 hours; uint constant harvestAmount = 10; uint constant crypteriumPrice = 0.001 ether; uint constant attackCooldownTime = 1 hours; uint constant defenderAdvantage = 30; uint private nonce = 0; uint constant infantryCost = 2; uint constant infantryAttackPower = 1; uint constant infantryDefensePower = 1; uint constant vehicleCost = 10; uint constant vehicleAttackPower = 4; uint constant vehicleDefensePower = 6; uint constant aircraftCost = 20; uint constant aircraftAttackPower = 12; uint constant aircraftDefensePower = 8; uint constant missionCooldownTime = 1 hours; uint constant missionDifficulty = 20; uint constant missionReward = 10; uint constant specialMissionReward = 1000; struct Commander { string name; address owner; uint crypterium; uint harvestReadyTime; uint infantryCount; uint vehicleCount; uint aircraftCount; uint attackReadyTime; uint missionLevel; uint missionReadyTime; bool completedSpecialMission; } Commander[] public commanders; mapping (address => uint) public addressToCommander; //-------------------------------------------------------------------------- // Modifiers //-------------------------------------------------------------------------- modifier hasCommander() { require(addressToCommander[msg.sender] != 0); _; } modifier canHarvest() { require(commanders[addressToCommander[msg.sender] - 1].harvestReadyTime <= now); _; } modifier hasCrypterium(uint _amount) { require(_amount <= commanders[addressToCommander[msg.sender] - 1].crypterium); _; } modifier canAttack() { require(commanders[addressToCommander[msg.sender] - 1].attackReadyTime <= now); _; } modifier canStartMission() { require(commanders[addressToCommander[msg.sender] - 1].missionReadyTime <= now); _; } //-------------------------------------------------------------------------- // Getters //-------------------------------------------------------------------------- function getCommanderName(uint _id) external view returns (string) { return commanders[_id].name; } function getCommanderDetails(uint _id) external view returns ( address, uint, uint, uint, uint, uint, uint ) { return ( commanders[_id].owner,commanders[_id].crypterium, commanders[_id].harvestReadyTime, commanders[_id].infantryCount, commanders[_id].vehicleCount, commanders[_id].aircraftCount, commanders[_id].attackReadyTime ); } function getCommanderCount() external view returns (uint) { return commanders.length; } function getCommanderId(address _address) external view returns (uint) { return addressToCommander[_address]; } function getMissionDetails(uint _id) external view returns (uint, uint) { return (commanders[_id].missionLevel, commanders[_id].missionReadyTime); } //-------------------------------------------------------------------------- // Functions to create/edit Commander //-------------------------------------------------------------------------- function createCommander(string _name) external { require(addressToCommander[msg.sender] == 0); uint id = commanders.push(Commander(_name, msg.sender, 0, now, 0, 0, 0, now, 1, now, false)); addressToCommander[msg.sender] = id; emit NewCommander(_name, msg.sender, id - 1); } function changeCommanderName(string _newName) external hasCommander { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; string memory oldName = commander.name; commander.name = _newName; emit ChangeName(oldName, _newName, msg.sender, id - 1); } //-------------------------------------------------------------------------- // Functions to harvest or buy Crypterium //-------------------------------------------------------------------------- function harvestCrypterium() external hasCommander canHarvest { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; commander.harvestReadyTime = now.add(harvestCooldownTime); commander.crypterium = commander.crypterium.add(harvestAmount); emit HarvestCrypterium(harvestAmount, commander.owner, id - 1); } function buyCrypterium(uint _amount) external payable hasCommander { require(msg.value == (_amount.mul(crypteriumPrice))); uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; commander.crypterium = commander.crypterium.add(_amount); emit HarvestCrypterium(_amount, commander.owner, id - 1); } //-------------------------------------------------------------------------- // Functions to produce units //-------------------------------------------------------------------------- function produceInfantry(uint _amount) external hasCommander hasCrypterium(infantryCost.mul(_amount)) { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; commander.crypterium = commander.crypterium.sub(infantryCost.mul(_amount)); commander.infantryCount = commander.infantryCount.add(_amount); emit ProduceInfantry(_amount, commander.owner, id - 1); } function produceVehicle(uint _amount) external hasCommander hasCrypterium(vehicleCost.mul(_amount)) { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; commander.crypterium = commander.crypterium.sub(vehicleCost.mul(_amount)); commander.vehicleCount = commander.vehicleCount.add(_amount); emit ProduceVehicle(_amount, commander.owner, id - 1); } function produceAircraft(uint _amount) external hasCommander hasCrypterium(aircraftCost.mul(_amount)) { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; commander.crypterium = commander.crypterium.sub(aircraftCost.mul(_amount)); commander.aircraftCount = commander.aircraftCount.add(_amount); emit ProduceAircraft(_amount, commander.owner, id - 1); } //-------------------------------------------------------------------------- // Function to attack other Commanders //-------------------------------------------------------------------------- function attack(address _address, uint _amount) external hasCommander canAttack hasCrypterium(_amount) { require(msg.sender != _address && addressToCommander[_address] != 0); Commander storage enemyCommander = commanders[addressToCommander[_address] - 1]; require(enemyCommander.crypterium >= _amount); uint id = addressToCommander[msg.sender] - 1; Commander storage commander = commanders[id]; // Note: this is not a secure way to generate randomness nonce++; uint attackMultiplier = (uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 100) + 1; uint defenseMultiplier = (100 - attackMultiplier) + defenderAdvantage; uint totalAttackPower = commander.infantryCount * infantryAttackPower + commander.vehicleCount * vehicleAttackPower + commander.aircraftCount * aircraftAttackPower; uint totalDefensePower = enemyCommander.infantryCount * infantryDefensePower + enemyCommander.vehicleCount * vehicleDefensePower + enemyCommander.aircraftCount * aircraftDefensePower; if ((totalAttackPower * attackMultiplier) > (totalDefensePower * defenseMultiplier)) { enemyCommander.crypterium = enemyCommander.crypterium.sub(_amount); commander.crypterium = commander.crypterium.add(_amount); commander.attackReadyTime = now.add(attackCooldownTime); emit AttackerWon(msg.sender, attackMultiplier, _address, defenseMultiplier, _amount); } else { commander.crypterium = commander.crypterium.sub(_amount); enemyCommander.crypterium = enemyCommander.crypterium.add(_amount); commander.attackReadyTime = now.add(attackCooldownTime); emit DefenderWon(msg.sender, attackMultiplier, _address, defenseMultiplier, _amount); } } //-------------------------------------------------------------------------- // Function to start a mission //-------------------------------------------------------------------------- function startMission() external hasCommander canStartMission { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; // Note: this is not a secure way to generate randomness nonce++; uint totalPowerMultiplier = (uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 100) + 1; uint difficultyMultiplier = (100 - totalPowerMultiplier); uint totalPower = commander.infantryCount * infantryAttackPower + commander.vehicleCount * vehicleAttackPower + commander.aircraftCount * aircraftAttackPower + commander.infantryCount * infantryDefensePower + commander.vehicleCount * vehicleDefensePower + commander.aircraftCount * aircraftDefensePower; uint difficulty = commander.missionLevel * missionDifficulty; if ((totalPower * totalPowerMultiplier) > (difficulty * difficultyMultiplier)) { uint reward = commander.missionLevel * missionReward; commander.crypterium = commander.crypterium.add(reward); commander.missionReadyTime = now.add(missionCooldownTime); commander.missionLevel += 1; emit MissionSucceeded( commander.missionLevel - 1, difficultyMultiplier, totalPowerMultiplier, reward, commander.owner, id - 1 ); } else { commander.missionReadyTime = now.add(missionCooldownTime); emit MissionFailed( commander.missionLevel, difficultyMultiplier, totalPowerMultiplier, commander.owner, id - 1 ); } } //-------------------------------------------------------------------------- // Function to start special mission // Note: Some stages are similar to the gates in theCyberGatekeeperTwo //-------------------------------------------------------------------------- function startSpecialMission(uint _commandOne, bytes8 _commandTwo) external { // Stage 1 require(addressToCommander[tx.origin] != 0); require(commanders[addressToCommander[tx.origin] - 1].completedSpecialMission == false); require(msg.sender != tx.origin); // Stage 2 uint secretNumber = (uint(keccak256(abi.encodePacked(now, msg.sender))) % 100) + 1; require(secretNumber == _commandOne); // Stage 3 uint callerSize; assembly { callerSize := extcodesize(caller) } require(callerSize == 0); // Stage 4 require(uint64(keccak256(abi.encodePacked(_commandOne, msg.sender))) ^ uint64(_commandTwo) == uint64(0) - 1); // Get reward after completing all stages uint id = addressToCommander[tx.origin]; Commander storage commander = commanders[id - 1]; commander.completedSpecialMission = true; commander.crypterium = commander.crypterium.add(specialMissionReward); emit SpecialMissionCompleted(commander.owner, id - 1); } //-------------------------------------------------------------------------- // ERC-721 functions //-------------------------------------------------------------------------- mapping (uint => address) approvals; function balanceOf(address _owner) external view returns (uint256 _balance) { if (addressToCommander[_owner] == 0) { return 0; } else { return 1; } } function ownerOf(uint256 _tokenId) external view returns (address _owner) { return commanders[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) private { addressToCommander[_from] = 0; addressToCommander[_to] = _tokenId.add(1); commanders[_tokenId].owner = _to; emit Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) external hasCommander { require( addressToCommander[msg.sender] == _tokenId.add(1) && msg.sender == commanders[_tokenId].owner && addressToCommander[_to] == 0 ); _transfer(msg.sender, _to, _tokenId); } function approve(address _to, uint256 _tokenId) external hasCommander { require( addressToCommander[msg.sender] == _tokenId.add(1) && msg.sender == commanders[_tokenId].owner && addressToCommander[_to] == 0 ); approvals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId) external { require(approvals[_tokenId] == msg.sender && addressToCommander[msg.sender] == 0); address owner = commanders[_tokenId].owner; _transfer(owner, msg.sender, _tokenId); } //-------------------------------------------------------------------------- // Fallback function //-------------------------------------------------------------------------- function () public payable {} //-------------------------------------------------------------------------- // Only owner functions //-------------------------------------------------------------------------- function withdraw(uint _amount) public onlyOwner { require(_amount <= address(this).balance); owner.transfer(_amount); } function withdrawAll() public onlyOwner { owner.transfer(address(this).balance); } }
-------------------------------------------------------------------------- Function to start a mission-------------------------------------------------------------------------- Note: this is not a secure way to generate randomness
function startMission() external hasCommander canStartMission { uint id = addressToCommander[msg.sender]; Commander storage commander = commanders[id - 1]; nonce++; uint totalPowerMultiplier = (uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 100) + 1; uint difficultyMultiplier = (100 - totalPowerMultiplier); uint totalPower = commander.infantryCount * infantryAttackPower + commander.vehicleCount * vehicleAttackPower + commander.aircraftCount * aircraftAttackPower + commander.infantryCount * infantryDefensePower + commander.vehicleCount * vehicleDefensePower + commander.aircraftCount * aircraftDefensePower; uint difficulty = commander.missionLevel * missionDifficulty; if ((totalPower * totalPowerMultiplier) > (difficulty * difficultyMultiplier)) { uint reward = commander.missionLevel * missionReward; commander.crypterium = commander.crypterium.add(reward); commander.missionReadyTime = now.add(missionCooldownTime); commander.missionLevel += 1; emit MissionSucceeded( commander.missionLevel - 1, difficultyMultiplier, totalPowerMultiplier, reward, commander.owner, id - 1 ); commander.missionReadyTime = now.add(missionCooldownTime); emit MissionFailed( commander.missionLevel, difficultyMultiplier, totalPowerMultiplier, commander.owner, id - 1 ); } }
15,871,144
[ 1, 5802, 15392, 4284, 358, 787, 279, 29396, 5802, 15392, 3609, 30, 333, 353, 486, 279, 8177, 4031, 358, 2103, 2744, 4496, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 49, 19710, 1435, 3903, 711, 2189, 264, 848, 1685, 49, 19710, 288, 203, 3639, 2254, 612, 273, 1758, 774, 2189, 264, 63, 3576, 18, 15330, 15533, 203, 3639, 3498, 264, 2502, 1296, 264, 273, 1296, 414, 63, 350, 300, 404, 15533, 203, 203, 3639, 7448, 9904, 31, 203, 3639, 2254, 2078, 13788, 23365, 273, 261, 11890, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3338, 16, 1234, 18, 15330, 16, 7448, 20349, 738, 2130, 13, 397, 404, 31, 203, 3639, 2254, 3122, 21934, 23365, 273, 261, 6625, 300, 2078, 13788, 23365, 1769, 203, 203, 203, 3639, 2254, 2078, 13788, 273, 1296, 264, 18, 10625, 304, 698, 1380, 380, 8286, 304, 698, 3075, 484, 13788, 203, 12900, 397, 1296, 264, 18, 537, 18870, 1380, 380, 24815, 3075, 484, 13788, 203, 12900, 397, 1296, 264, 18, 1826, 71, 5015, 1380, 380, 23350, 71, 5015, 3075, 484, 13788, 203, 12900, 397, 1296, 264, 18, 10625, 304, 698, 1380, 380, 8286, 304, 698, 3262, 3558, 13788, 203, 12900, 397, 1296, 264, 18, 537, 18870, 1380, 380, 24815, 3262, 3558, 13788, 203, 12900, 397, 1296, 264, 18, 1826, 71, 5015, 1380, 380, 23350, 71, 5015, 3262, 3558, 13788, 31, 203, 203, 3639, 2254, 3122, 21934, 273, 1296, 264, 18, 3951, 2355, 380, 29396, 5938, 21934, 31, 203, 203, 3639, 309, 14015, 4963, 13788, 380, 2078, 13788, 23365, 13, 405, 261, 5413, 21934, 380, 3122, 21934, 23365, 3719, 288, 203, 5411, 2254, 19890, 273, 1296, 264, 18, 3951, 2355, 380, 29396, 17631, 1060, 2 ]
pragma solidity ^0.5.0; import "./LightClient.sol"; import "./MPTSolidity/ProvethVerifier.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts//ownership/Ownable.sol"; contract BridgedToken is ERC20Burnable,ERC20Detailed,ERC20Mintable { constructor(string memory name, string memory symbol, uint8 decimals) ERC20Detailed(name,symbol,decimals) public{} } contract RainbowOnes is ProvethVerifier,Ownable { using RLPReader for RLPReader.RLPItem; using RLPReader for bytes; event TokenMapReq(address indexed tokenReq, uint8 indexed decimals, string name, string symbol); bytes32 TokenMapReqEventSig = keccak256("TokenMapReq(address,uint8,string,string)"); event TokenMapAck(address indexed tokenReq, address indexed tokenAck); bytes32 TokenMapAckEventSig = keccak256("TokenMapAck(address,address)"); event Locked(address indexed token, address indexed sender, uint256 amount, address recipient); bytes32 lockEventSig = keccak256("Locked(address,address,uint256,address)"); event Burn(address indexed token, address indexed sender, uint256 amount, address recipient); bytes32 burnEventSig = keccak256("Burn(address,address,uint256,address)"); address public otherSideBridge; ILightClient public lightclient; address[] public LockedTokenList; // thisSide locked ERC20 list address[] public MintTokenList; // thisSide mint ERC20 list mapping(address=>address) public ThisSideLocked; // thisSide locked => otherSide mint mapping(address=>address) public OtherSideMint; // otherSide mint => thisSide locked mapping(address=>address) public OtherSideLocked; // otherSide locked => thisSide mint mapping(address=>address) public ThisSideMint; // thisSide mint => otherSide locked mapping(bytes32=>bool) public spentReceipt; constructor() Ownable() public { lightclient = new LightClientUnsafe(); } function getRainbowSize() view public returns(uint256, uint256) { return (LockedTokenList.length, MintTokenList.length); } function changeLightClient(address newClientAddress) public onlyOwner { lightclient = ILightClient(newClientAddress); } function bandBridgeSide(address otherSide) public onlyOwner { otherSideBridge = otherSide; } function CreateRainbow(ERC20Detailed thisSideToken) public returns(address) { require(ThisSideLocked[address(thisSideToken)] == address(0), "rainbow is exists"); ERC20Detailed tokenDetail = ERC20Detailed(thisSideToken); emit TokenMapReq(address(thisSideToken), tokenDetail.decimals(), tokenDetail.name(), tokenDetail.symbol()); } function RainbowBack(BridgedToken token, address recipient, uint256 amount) public { require( recipient != address(0), "Locker/recipient is a zero address" ); require(ThisSideMint[address(token)] != address(0), "bridge isn't exist"); token.burnFrom(msg.sender, amount); emit Burn(address(token), msg.sender, amount, recipient); } function RainbowTo(IERC20 token, address recipient, uint256 amount) public { require( recipient != address(0), "Locker/recipient is a zero address" ); // the below line should be uncommented once eb.handleHmyProof(proof) succeeds in deploy.js //unable to get merkle-proofs from harmony, "hmy_getReceipt" json rpc method does not exist // note that for uni- directional eth to harmony bridge eth proofs validated on harmony bridge verifier contracts is enough. // also note that currently every time tokens are locked on eth , proofs are handled on harmony and only then tokens are minted. // the below line is really about hrc20 token creation acknowledgement that is truly mapped to erc20 token. // require(ThisSideLocked[address(token)] != address(0), "bridge isn't exist"); token.transferFrom(msg.sender, address(this), amount); emit Locked(address(token), msg.sender, amount, recipient); } function ExecProof(bytes32 blockHash, bytes32 rootHash, bytes memory mptkey, bytes memory proof) public { require(lightclient.VerifyReceiptsHash(blockHash, rootHash), "wrong receipt hash"); bytes32 receiptHash = keccak256(abi.encodePacked(blockHash, rootHash, mptkey)); require(spentReceipt[receiptHash] == false, "double spent!"); bytes memory rlpdata = MPTProof(rootHash, mptkey, proof); // double spending check spentReceipt[receiptHash] = true; uint256 events = receiptVerify(rlpdata); require(events > 0, "no valid event"); } function receiptVerify(bytes memory rlpdata) private returns(uint256 events) { RLPReader.RLPItem memory stacks = rlpdata.toRlpItem(); RLPReader.RLPItem[] memory receipt = stacks.toList(); // TODO: check txs is revert or not uint PostStateOrStatus = receipt[0].toUint(); require(PostStateOrStatus == 1, "revert receipt"); //uint CumulativeGasUsed = receipt[1].toUint(); //bytes memory Bloom = receipt[2].toBytes(); RLPReader.RLPItem[] memory Logs = receipt[3].toList(); for(uint i = 0; i < Logs.length; i++) { RLPReader.RLPItem[] memory rlpLog = Logs[i].toList(); address Address = rlpLog[0].toAddress(); if(Address != otherSideBridge) continue; RLPReader.RLPItem[] memory Topics = rlpLog[1].toList(); // TODO: if is lock event bytes32[] memory topics = new bytes32[](Topics.length); for(uint j = 0; j < Topics.length; j++) { topics[j] = bytes32(Topics[j].toUint()); } bytes memory Data = rlpLog[2].toBytes(); if(topics[0] == lockEventSig){ onLockEvent(topics, Data); events++; continue; } if(topics[0] == burnEventSig){ onBurnEvent(topics, Data); events++; continue; } if(topics[0] == TokenMapReqEventSig){ onTokenMapReqEvent(topics, Data); events++; continue; } if(topics[0] == TokenMapAckEventSig){ onTokenMapAckEvent(topics, Data); events++; continue; } } } function onBurnEvent(bytes32[] memory topics, bytes memory Data) private { address token = address(uint160(uint256(topics[1]))); //address sender = address(uint160(uint256(topics[2]))); (uint256 amount, address recipient) = abi.decode(Data, (uint256, address)); IERC20 lockedToken = IERC20(OtherSideMint[token]); lockedToken.transfer(recipient, amount); } function onLockEvent(bytes32[] memory topics, bytes memory Data) private { address token = address(uint160(uint256(topics[1]))); //address sender = address(uint160(uint256(topics[2]))); (uint256 amount, address recipient) = abi.decode(Data, (uint256, address)); address mintToken = OtherSideLocked[token]; require(mintToken != address(0)); BridgedToken(mintToken).mint(recipient, amount); } function onTokenMapReqEvent(bytes32[] memory topics, bytes memory Data) private { // event TokenMapReq(address indexed tokenReq, uint256 decimals, string name, string symbol); address tokenReq = address(uint160(uint256(topics[1]))); require(OtherSideLocked[tokenReq] == address(0), "bridge already exist"); uint8 decimals = uint8(uint256(topics[2])); (string memory name, string memory symbol) = abi.decode(Data, (string, string)); BridgedToken mintAddress = new BridgedToken(name, symbol, decimals); ThisSideMint[address(mintAddress)] = tokenReq; OtherSideLocked[tokenReq] = address(mintAddress); MintTokenList.push(address(mintAddress)); emit TokenMapAck(tokenReq, address(mintAddress)); } function onTokenMapAckEvent(bytes32[] memory topics, bytes memory Data) private { // event TokenMapAck(address indexed tokenReq, address indexed tokenAck); Data; address tokenReq = address(uint160(uint256(topics[1]))); address tokenAck = address(uint160(uint256(topics[2]))); require(ThisSideLocked[tokenReq] == address(0), "impossible ack"); // just check, shouldn't happen ThisSideLocked[tokenReq] = tokenAck; OtherSideMint[tokenAck] = tokenReq; LockedTokenList.push(tokenReq); } }
thisSide mint => otherSide locked
mapping(address=>address) public ThisSideMint;
6,448,446
[ 1, 2211, 8895, 312, 474, 516, 1308, 8895, 8586, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 9207, 2867, 13, 1071, 1220, 8895, 49, 474, 31, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-eth/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is Initializable, 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 A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is Initializable, ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-eth/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.2; contract PauserRole is Initializable { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Initializable, PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @return true if the contract is paused, 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); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } // File: openzeppelin-eth/contracts/utils/Arrays.sol pragma solidity ^0.5.2; /** * @title Arrays * @dev Utility library of inline array functions */ library Arrays { /** * @dev Upper bound search function which is kind of binary search algorithm. It searches sorted * array to find index of the element value. If element is found then returns its index otherwise * it returns index of first element which is greater than searched value. If searched element is * bigger than any array element function then returns first index after last element (i.e. all * values inside the array are smaller than the target). Complexity O(log n). * @param array The array sorted in ascending order. * @param element The element's value to be found. * @return The calculated index value. Returns 0 for empty array. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // File: openzeppelin-eth/contracts/drafts/Counters.sol pragma solidity ^0.5.2; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: openzeppelin-eth/contracts/drafts/ERC20Snapshot.sol pragma solidity ^0.5.2; /** * @title ERC20 token with snapshots. * @dev Inspired by Jordi Baylina's MiniMeToken to record historical balances: * https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol * When a snapshot is made, the balances and totalSupply at the time of the snapshot are recorded for later * access. * * To make a snapshot, call the `snapshot` function, which will emit the `Snapshot` event and return a snapshot id. * To get the total supply from a snapshot, call the function `totalSupplyAt` with the snapshot id. * To get the balance of an account from a snapshot, call the `balanceOfAt` function with the snapshot id and the * account address. * @author Validity Labs AG <info@validitylabs.org> */ contract ERC20Snapshot is Initializable, ERC20 { using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnaphots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; event Snapshot(uint256 id); // Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a // balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid // when required, but is also flexible enough that it allows for e.g. daily snapshots. function snapshot() public returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnaphots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0); require(snapshotId <= _currentSnapshotId.current()); uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnaphots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.2; contract MinterRole is Initializable { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(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); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.2; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @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; } uint256[50] private ______gap; } // File: contracts/CircuitsOfValue.sol // contracts/CustomERC20.sol pragma solidity ^0.5.0; contract CircuitsOfValue is Initializable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable, ERC20Snapshot, ERC20Mintable { bool private _pausableInitialized; function initialize( string memory name, string memory symbol, uint8 decimals, uint256 initialSupply, address initialHolder ) public initializer { // require(initialSupply > 0, ""); ERC20Detailed.initialize(name, symbol, decimals); ERC20Mintable.initialize(msg.sender); initializePausable(msg.sender); // _mint(initialHolder, initialSupply); } function initializePausable(address sender) public { require(!_pausableInitialized, "pausable has already been initialized"); _pausableInitialized = true; _addPauser(sender); } }
require(initialSupply > 0, ""); _mint(initialHolder, initialSupply);
public initializer { ERC20Detailed.initialize(name, symbol, decimals); ERC20Mintable.initialize(msg.sender); initializePausable(msg.sender); }
1,156,853
[ 1, 6528, 12, 6769, 3088, 1283, 405, 374, 16, 1408, 1769, 389, 81, 474, 12, 6769, 6064, 16, 2172, 3088, 1283, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 1071, 12562, 288, 203, 565, 4232, 39, 3462, 40, 6372, 18, 11160, 12, 529, 16, 3273, 16, 15105, 1769, 203, 565, 4232, 39, 3462, 49, 474, 429, 18, 11160, 12, 3576, 18, 15330, 1769, 203, 565, 4046, 16507, 16665, 12, 3576, 18, 15330, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import "installed_contracts/oraclize-api/contracts/usingOraclize.sol"; contract OraclizeTest is usingOraclize { // Need the id's to identify which query invoked the callback bytes32 private ethQueryId; bytes32 private weatherQueryId; bytes32 private exchRateQueryId; address owner; event LogInfo(string description); event LogPriceUpdate(string price); event LogWeatherUpdate(string price); event LogExchRateUpdate(string price); event LogUpdate(address indexed _owner, uint indexed _balance); // Constructor function OraclizeTest() payable public { owner = msg.sender; emit LogUpdate(owner, address(this).balance); // OAR coming from ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); } // Fallback function function() public{ emit LogInfo("FallBack function invoked"); revert(); } function getBalance() public returns (uint _balance) { return address(this).balance; } function __callback(bytes32 id, string result, bytes proof) public { require(msg.sender == oraclize_cbAddress()); if(ethQueryId == id) { emit LogPriceUpdate(result); } if(weatherQueryId == id) { emit LogWeatherUpdate(result); } if(exchRateQueryId == id) { emit LogExchRateUpdate(result); } } function updateETH() payable public { // Check if we have enough remaining funds if (oraclize_getPrice("URL") > address(this).balance) { emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogInfo("Oraclize query was sent, standing by for the answer.."); // Using XPath to to fetch the right element in the JSON response ethQueryId = oraclize_query(20, "URL", "json(https://api.coinbase.com/v2/prices/ETH-USD/spot).data.amount"); } } function updateWeather() payable public { // Check if we have enough remaining funds if (oraclize_getPrice("URL") > address(this).balance) { emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogInfo("Oraclize query was sent, standing by for the answer.."); // Using XPath to to fetch the right element in the JSON response weatherQueryId = oraclize_query(20, "URL", "json(http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=WEATHERMAP_APP_ID).main"); } } function updateExchRate() payable public { // Check if we have enough remaining funds if (oraclize_getPrice("URL") > address(this).balance) { emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogInfo("Oraclize query was sent, standing by for the answer.."); // Using XPath to to fetch the right element in the JSON response exchRateQueryId = oraclize_query(20, "URL", "json(http://data.fixer.io/api/latest?access_key=FIXER_APP_ID&symbols=GBP,EUR).rates.GBP"); } } }
Check if we have enough remaining funds Using XPath to to fetch the right element in the JSON response
function updateETH() payable public { if (oraclize_getPrice("URL") > address(this).balance) { emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); emit LogInfo("Oraclize query was sent, standing by for the answer.."); } }
7,268,691
[ 1, 1564, 309, 732, 1240, 7304, 4463, 284, 19156, 11637, 10172, 358, 358, 2158, 326, 2145, 930, 316, 326, 1796, 766, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 1584, 44, 1435, 203, 565, 8843, 429, 203, 565, 1071, 288, 203, 3639, 309, 261, 280, 10150, 554, 67, 588, 5147, 2932, 1785, 7923, 405, 1758, 12, 2211, 2934, 12296, 13, 288, 203, 5411, 3626, 1827, 966, 2932, 51, 354, 830, 554, 843, 1703, 4269, 3271, 16, 9582, 527, 2690, 512, 2455, 358, 5590, 364, 326, 843, 14036, 8863, 203, 5411, 3626, 1827, 966, 2932, 51, 354, 830, 554, 843, 1703, 3271, 16, 12842, 310, 635, 364, 326, 5803, 838, 8863, 203, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/11155111/0x35f2DAaCE3E1A0B3fDC02a6d18371087009e2212/sources/contracts/PolliwogsHelper.sol
generate the true child age probabilities array intervals
uint[] memory childAgeIntervals;
3,535,677
[ 1, 7163, 326, 638, 1151, 9388, 17958, 526, 10389, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 8526, 3778, 1151, 9692, 24224, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.8.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.4.1 // 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/security/ReentrancyGuard.sol@v4.4.1 // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/Context.sol@v4.4.1 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v4.4.1 // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/cryptography/MerkleProof.sol@v4.4.1 // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // File hardhat/console.sol@v2.8.0 pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File contracts/sale-usdc.sol // SPDX-License-Identifier: Apache-2.0 /* /$$$$$$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$__ $$ |__/ | $$__ $$ /$$__ $$ /$$__ $$ | $$ \__//$$$$$$ /$$ /$$$$$$ /$$$$$$$| $$ \ $$| $$ \ $$| $$ \ $$ | $$$$ /$$__ $$| $$ /$$__ $$ /$$_____/| $$ | $$| $$$$$$$$| $$ | $$ | $$_/ | $$ \__/| $$| $$$$$$$$| $$$$$$ | $$ | $$| $$__ $$| $$ | $$ | $$ | $$ | $$| $$_____/ \____ $$| $$ | $$| $$ | $$| $$ | $$ | $$ | $$ | $$| $$$$$$$ /$$$$$$$/| $$$$$$$/| $$ | $$| $$$$$$/ |__/ |__/ |__/ \_______/|_______/ |_______/ |__/ |__/ \______/ */ pragma solidity ^0.8.7; // FRIES token interface interface IFriesDAOToken is IERC20 { function mint(uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } contract FriesDAOTokenSale is ReentrancyGuard, Ownable { IERC20 public immutable USDC; // USDC token IFriesDAOToken public immutable FRIES; // FRIES token uint256 public constant FRIES_DECIMALS = 18; // FRIES token decimals uint256 public constant USDC_DECIMALS = 6; // USDC token decimals bool public whitelistSaleActive = false; bool public publicSaleActive = false; bool public redeemActive = false; bool public refundActive = false; uint256 public salePrice; // Sale price of FRIES per USDC uint256 public baseWhitelistAmount; // Base whitelist amount of USDC available to purchase uint256 public totalCap; // Total maximum amount of USDC in sale uint256 public totalPurchased = 0; // Total amount of USDC purchased in sale mapping (address => uint256) public purchased; // Mapping of account to total purchased amount in FRIES mapping (address => uint256) public redeemed; // Mapping of account to total amount of redeemed FRIES mapping (address => bool) public vesting; // Mapping of account to vesting of purchased FRIES after redeem bytes32 public merkleRoot; // Merkle root representing tree of all whitelisted accounts address public treasury; // friesDAO treasury address uint256 public vestingPercent; // Percent tokens vested /1000 // Events event WhitelistSaleActiveChanged(bool active); event PublicSaleActiveChanged(bool active); event RedeemActiveChanged(bool active); event RefundActiveChanged(bool active); event SalePriceChanged(uint256 price); event BaseWhitelistAmountChanged(uint256 baseWhitelistAmount); event TotalCapChanged(uint256 totalCap); event Purchased(address indexed account, uint256 amount); event Redeemed(address indexed account, uint256 amount); event Refunded(address indexed account, uint256 amount); event TreasuryChanged(address treasury); event VestingPercentChanged(uint256 vestingPercent); // Initialize sale parameters constructor(address usdcAddress, address friesAddress, address treasuryAddress, bytes32 root) { USDC = IERC20(usdcAddress); // USDC token FRIES = IFriesDAOToken(friesAddress); // Set FRIES token contract salePrice = 43312503100000000000; // 43.3125031 FRIES per USDC totalCap = 9696969 * 10 ** USDC_DECIMALS; // Total 10,696,969 max USDC raised merkleRoot = root; // Merkle root for whitelisted accounts treasury = treasuryAddress; // Set friesDAO treasury address vestingPercent = 850; // 85% vesting for vested allocations } /* * ------------------ * EXTERNAL FUNCTIONS * ------------------ */ // Buy FRIES with USDC in whitelisted token sale function buyWhitelistFries(uint256 value, uint256 whitelistLimit, bool vestingEnabled, bytes32[] calldata proof) external { require(whitelistSaleActive, "FriesDAOTokenSale: whitelist token sale is not active"); require(value > 0, "FriesDAOTokenSale: amount to purchase must be larger than zero"); console.log("verifying proof:", _msgSender(), whitelistLimit, vestingEnabled); console.logBytes(abi.encodePacked(_msgSender(), whitelistLimit, vestingEnabled)); bytes32 leaf = keccak256(abi.encodePacked(_msgSender(), whitelistLimit, vestingEnabled)); // Calculate merkle leaf of whitelist parameters console.logBytes32(leaf); require(MerkleProof.verify(proof, merkleRoot, leaf), "FriesDAOTokenSale: invalid whitelist parameters"); // Verify whitelist parameters with merkle proof uint256 amount = value * salePrice / 10 ** USDC_DECIMALS; // Calculate amount of FRIES at sale price with USDC value require(purchased[_msgSender()] + amount <= whitelistLimit, "FriesDAOTokenSale: amount over whitelist limit"); // Check purchase amount is within whitelist limit vesting[_msgSender()] = vestingEnabled; // Set vesting enabled for account USDC.transferFrom(_msgSender(), treasury, value); // Transfer USDC amount to treasury purchased[_msgSender()] += amount; // Add FRIES amount to purchased amount for account totalPurchased += value; // Add USDC amount to total USDC purchased emit Purchased(_msgSender(), amount); } // Buy FRIES with USDC in public token sale function buyFries(uint256 value) external { require(publicSaleActive, "FriesDAOTokenSale: public token sale is not active"); require(value > 0, "FriesDAOTokenSale: amount to purchase must be larger than zero"); require(totalPurchased + value < totalCap, "FriesDAOTokenSale: amount over total sale limit"); USDC.transferFrom(_msgSender(), treasury, value); // Transfer USDC amount to treasury uint256 amount = value * salePrice / 10 ** USDC_DECIMALS; // Calculate amount of FRIES at sale price with USDC value purchased[_msgSender()] += amount; // Add FRIES amount to purchased amount for account totalPurchased += value; // Add USDC amount to total USDC purchased emit Purchased(_msgSender(), amount); } // Redeem purchased FRIES for tokens function redeemFries() external { require(redeemActive, "FriesDAOTokenSale: redeeming for tokens is not active"); uint256 amount = purchased[_msgSender()] - redeemed[_msgSender()]; // Calculate redeemable FRIES amount require(amount > 0, "FriesDAOTokenSale: invalid redeem amount"); redeemed[_msgSender()] += amount; // Add FRIES redeem amount to redeemed total for account if (!vesting[_msgSender()]) { FRIES.transfer(_msgSender(), amount); // Send redeemed FRIES to account } else { FRIES.transfer(_msgSender(), amount * (1000 - vestingPercent) / 1000); // Send available FRIES to account FRIES.transfer(treasury, amount * vestingPercent / 1000); // Send vested FRIES to treasury } emit Redeemed(_msgSender(), amount); } // Refund FRIES for USDC at sale price function refundFries(uint256 amount) external nonReentrant { require(refundActive, "FriesDAOTokenSale: refunding redeemed tokens is not active"); require(redeemed[_msgSender()] >= amount, "FriesDAOTokenSale: refund amount larger than tokens redeemed"); FRIES.burnFrom(_msgSender(), amount); // Remove FRIES refund amount from account purchased[_msgSender()] -= amount; // Reduce purchased amount of account by FRIES refund amount redeemed[_msgSender()] -= amount; // Reduce redeemed amount of account by FRIES refund amount USDC.transferFrom(treasury, _msgSender(), amount * 10 ** USDC_DECIMALS / salePrice); // Send refund USDC amount at sale price to account emit Refunded(_msgSender(), amount); } /* * -------------------- * RESTRICTED FUNCTIONS * -------------------- */ // Set merkle root function setRoot(bytes32 _root) external onlyOwner { merkleRoot = _root; } // Set whitelist sale enabled status function setWhitelistSaleActive(bool active) external onlyOwner { whitelistSaleActive = active; emit WhitelistSaleActiveChanged(whitelistSaleActive); } // Set public sale enabled status function setPublicSaleActive(bool active) external onlyOwner { publicSaleActive = active; emit PublicSaleActiveChanged(publicSaleActive); } // Set redeem enabled status function setRedeemActive(bool active) external onlyOwner { redeemActive = active; emit RedeemActiveChanged(redeemActive); } // Set refund enabled status function setRefundActive(bool active) external onlyOwner { refundActive = active; emit RefundActiveChanged(refundActive); } // Change sale price function setSalePrice(uint256 price) external onlyOwner { salePrice = price; emit SalePriceChanged(salePrice); } // Change sale total cap function setTotalCap(uint256 amount) external onlyOwner { totalCap = amount; emit TotalCapChanged(totalCap); } // Change friesDAO treasury address function setTreasury(address treasuryAddress) external { require(_msgSender() == treasury, "FriesDAOTokenSale: caller is not the treasury"); treasury = treasuryAddress; emit TreasuryChanged(treasury); } // Change vesting percent function setVestingPercent(uint256 percent) external onlyOwner { vestingPercent = percent; emit VestingPercentChanged(vestingPercent); } }
Calculate amount of FRIES at sale price with USDC value
uint256 amount = value * salePrice / 10 ** USDC_DECIMALS;
5,430,243
[ 1, 8695, 3844, 434, 478, 2259, 3991, 622, 272, 5349, 6205, 598, 11836, 5528, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 3844, 273, 460, 380, 272, 5349, 5147, 342, 1728, 2826, 11836, 5528, 67, 23816, 55, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x84fE05f541cee93d0B02e03cD4319c29BA0030A2/sources/src/challenge/ChallengeManager.sol
* @dev this currently sets a challenge hash of 0 - no move is possible for the next participant to progress the state. It is assumed that wherever this function is consumed, the turn is then adjusted for the opposite party to timeout. This is done as a safety measure so challenges can only be resolved by timeouts during mainnet beta./ address next = challenge.next.addr; address current = challenge.current.addr; delete challenges[challengeIndex]; resultReceiver.completeChallenge(challengeIndex, current, next); emit ChallengeEnded(challengeIndex, reason);
function _currentWin( uint64 challengeIndex, ChallengeTerminationType /* reason */ ) private { ChallengeLib.Challenge storage challenge = challenges[challengeIndex]; challenge.challengeStateHash = bytes32(0); }
8,284,743
[ 1, 2211, 4551, 1678, 279, 12948, 1651, 434, 374, 300, 1158, 3635, 353, 3323, 364, 326, 1024, 14188, 358, 4007, 326, 919, 18, 2597, 353, 12034, 716, 1625, 502, 333, 445, 353, 12393, 16, 326, 7005, 353, 1508, 13940, 364, 326, 20759, 18285, 358, 2021, 18, 1220, 353, 2731, 487, 279, 24179, 6649, 1427, 462, 7862, 2852, 848, 1338, 506, 4640, 635, 20395, 4982, 2774, 2758, 6796, 18, 19, 3639, 1758, 1024, 273, 12948, 18, 4285, 18, 4793, 31, 3639, 1758, 783, 273, 12948, 18, 2972, 18, 4793, 31, 3639, 1430, 462, 7862, 2852, 63, 25092, 1016, 15533, 3639, 563, 12952, 18, 6226, 18359, 12, 25092, 1016, 16, 783, 16, 1024, 1769, 3639, 3626, 1680, 8525, 28362, 12, 25092, 1016, 16, 3971, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2972, 18049, 12, 203, 3639, 2254, 1105, 12948, 1016, 16, 203, 3639, 1680, 8525, 16516, 559, 1748, 3971, 1195, 203, 565, 262, 3238, 288, 203, 3639, 1680, 8525, 5664, 18, 18359, 2502, 12948, 273, 462, 7862, 2852, 63, 25092, 1016, 15533, 203, 3639, 12948, 18, 25092, 1119, 2310, 273, 1731, 1578, 12, 20, 1769, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract helper { function derive_sha256(string key, uint rounds) public pure returns(bytes32 hash){ if (rounds == 0) rounds = 1; hash = sha256(key); for (uint i = 0; i < rounds-1; i++) { hash = sha256(hash); } } function blind_sha256(string key, address caller) public pure returns(bytes32 challenge){ challenge = sha256(sha256(key),caller); } function double_blind_sha256(string key, address caller, address receiver) public pure returns(bytes32 challenge){ challenge = sha256(sha256(sha256(key),caller),receiver); } } contract owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } /* Constructor */ function owned() public { owner = msg.sender; } } contract QuantumLocksmith is owned, helper { uint public m_pending; struct lock { bool alive; bool proven; uint balance; string protocol; string key; address owner; } mapping(bytes32 => lock) public locks; // challenge the original owner validity function QuantumLocksmith(bytes32 ownerChallenge) public payable { require(uint(ownerChallenge) > 0); locks[ownerChallenge].alive = true; locks[ownerChallenge].balance = msg.value; m_pending++; } function lockDeposit(bytes32 challenge, string _protocol) public payable { require(uint(challenge) > 0); require(msg.value > 0); require(!locks[challenge].alive); locks[challenge].alive = true; locks[challenge].balance = msg.value; locks[challenge].owner = msg.sender; m_pending++; if (bytes(_protocol).length > 0) locks[challenge].protocol = _protocol; } function unlockDeposit( string key, address receiver ) public { require(bytes(key).length > 0); // generate the challenge bytes32 k = sha256(sha256(key),msg.sender); address to = msg.sender; if (uint(receiver) > 0) { to = receiver; k = sha256(k,receiver); } if (locks[k].alive && !locks[k].proven) { locks[k].proven = true; locks[k].key = key; m_pending--; uint sendValue = locks[k].balance; if (sendValue > 0) { locks[k].balance = 0; require(to.send(sendValue)); } } } function depositToLock(bytes32 challenge) public payable { require(challenge != 0x0); require(msg.value > 0); require(locks[challenge].alive && !locks[challenge].proven); locks[challenge].balance += msg.value; } // do not allow this function() public payable { require(msg.value == 0); } function kill(string key) public { if (msg.sender == owner) { bytes32 k = sha256(sha256(key),msg.sender); if (locks[k].alive && !locks[k].proven) selfdestruct(owner); } } }
challenge the original owner validity
function QuantumLocksmith(bytes32 ownerChallenge) public payable { require(uint(ownerChallenge) > 0); locks[ownerChallenge].alive = true; locks[ownerChallenge].balance = msg.value; m_pending++; }
12,681,068
[ 1, 25092, 326, 2282, 3410, 13800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4783, 970, 379, 2531, 4808, 483, 12, 3890, 1578, 3410, 18359, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 11890, 12, 8443, 18359, 13, 405, 374, 1769, 203, 3639, 13046, 63, 8443, 18359, 8009, 11462, 273, 638, 31, 203, 3639, 13046, 63, 8443, 18359, 8009, 12296, 273, 1234, 18, 1132, 31, 203, 3639, 312, 67, 9561, 9904, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x1c25442C44FE5eC37af96B4137a15c823990d84D/sources/contracts/L1/tss/TssGroupManager.sol
user publicKey => Cpk
mapping(bytes => bytes) private _memberGroupKey;
11,625,097
[ 1, 1355, 12085, 516, 385, 5465, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 516, 1731, 13, 3238, 389, 5990, 1114, 653, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; import "../KioskMarketToken.sol"; import "../Product.sol"; import "../Market.sol"; import "./ENS/ENS.sol"; /** * This is an example of how to sell an ENS domain. */ contract ENSPublicProduct is Product { ENS public ens; KioskMarketToken public KMT; Market public market; struct ENSNode { string name; bytes32 node; uint256 price; bool isValid; } // DIN => ENS node mapping(uint256 => ENSNode) public nodes; modifier only_owner(uint256 DIN) { require (KMT.dinRegistry().owner(DIN) == msg.sender); _; } modifier only_market { require (market == msg.sender); _; } // Constructor function ENSPublicProduct(KioskMarketToken _KMT, ENS _ens, Market _market) { KMT = _KMT; ens = _ens; market = _market; } function addENSDomain( uint256 DIN, string name, bytes32 node, uint256 price ) only_owner(DIN) { // Store the details of the ENS node. nodes[DIN].name = name; nodes[DIN].node = node; nodes[DIN].price = price; nodes[DIN].isValid = true; } function name(uint256 DIN) constant returns (string) { return nodes[DIN].name; } function setName(uint256 DIN, string name) only_owner(DIN) { nodes[DIN].name = name; } function node(uint256 DIN) constant returns (bytes32) { return nodes[DIN].node; } function setNode(uint256 DIN, bytes32 node) only_owner(DIN) { nodes[DIN].node = node; } // Quantity is irrelevant here. We're only ever selling one ENS domain at a time function totalPrice(uint256 DIN, uint256 quantity, address buyer) constant returns (uint256) { // // Let the buyer buy back his domain (remove it from the market) for free. // if (buyer == registry.owner(DIN)) { // return 0; // } return nodes[DIN].price; } function setPrice(uint256 DIN, uint256 price) only_owner(DIN) { nodes[DIN].price = price; } function isAvailableForSale(uint256 DIN, uint256 quantity) constant returns (bool) { return nodes[DIN].isValid; } function handleOrder(uint256 orderID, uint256 DIN, uint256 quantity, address buyer) only_market { // The buyer is only getting a single domain. require(quantity == 1); // Give ownership of the node to the buyer. // Make sure to set the owner of the node to this contract first. ens.setOwner(nodes[DIN].node, buyer); } }
The buyer is only getting a single domain. Give ownership of the node to the buyer. Make sure to set the owner of the node to this contract first.
function handleOrder(uint256 orderID, uint256 DIN, uint256 quantity, address buyer) only_market { require(quantity == 1); ens.setOwner(nodes[DIN].node, buyer); }
12,743,974
[ 1, 1986, 27037, 353, 1338, 8742, 279, 2202, 2461, 18, 22374, 23178, 434, 326, 756, 358, 326, 27037, 18, 4344, 3071, 358, 444, 326, 3410, 434, 326, 756, 358, 333, 6835, 1122, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1640, 2448, 12, 11890, 5034, 1353, 734, 16, 2254, 5034, 463, 706, 16, 2254, 5034, 10457, 16, 1758, 27037, 13, 1338, 67, 27151, 288, 203, 202, 202, 6528, 12, 16172, 422, 404, 1769, 203, 203, 202, 202, 773, 18, 542, 5541, 12, 4690, 63, 21329, 8009, 2159, 16, 27037, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-10-09 */ // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @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); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _owner = newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } /** * @dev A token holder contract that will allow a beneficiary to extract the * tokens at predefined intervals. Tokens not claimed at payment epochs accumulate * Modified version of Openzeppelin's TokenTimeLock */ contract Lock is Ownable { using SafeMath for uint; enum period { second, minute, hour, day, week, month, //inaccurate, assumes 30 day month, subject to drift year, quarter,//13 weeks biannual//26 weeks } //The length in seconds for each epoch between payments uint epochLength; // ERC20 basic token contract being held IERC20 private _token; // beneficiary of tokens after they are released address private _beneficiary; uint periods; //the size of periodic payments uint paymentSize; uint paymentsRemaining =0; uint startTime =0; uint beneficiaryBalance = 0; function initialize(address tokenAddress, address beneficiary, uint duration,uint durationMultiple,uint p) public onlyOwner{ release(); require(paymentsRemaining == 0, 'cannot initialize during active vesting schedule'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(duration>0 && p>0, 'epoch parameters must be positive'); _token = IERC20(tokenAddress); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _beneficiary = beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(duration<=uint(period.biannual)){ if(duration == uint(period.second)){ epochLength = durationMultiple * 1 seconds; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC }else if(duration == uint(period.minute)){ epochLength = durationMultiple * 1 minutes; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } else if(duration == uint(period.hour)){ epochLength = durationMultiple *1 hours; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC }else if(duration == uint(period.day)){ epochLength = durationMultiple *1 days; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } else if(duration == uint(period.week)){ epochLength = durationMultiple *1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC }else if(duration == uint(period.month)){ epochLength = durationMultiple *30 days; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC }else if(duration == uint(period.year)){ epochLength = durationMultiple *52 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC }else if(duration == uint(period.quarter)){ epochLength = durationMultiple *13 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } else if(duration == uint(period.biannual)){ epochLength = 26 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } else{ epochLength = duration; //custom value //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } periods = p; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit Initialized(tokenAddress,beneficiary,epochLength,p); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function deposit (uint amount) public { //remember to ERC20.approve require (_token.transferFrom(msg.sender,address(this),amount),'transfer failed'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint balance = _token.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(paymentsRemaining==0) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC { paymentsRemaining = periods; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC startTime = block.timestamp; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } paymentSize = balance/paymentsRemaining; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit PaymentsUpdatedOnDeposit(paymentSize,startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function getElapsedReward() public view returns (uint,uint,uint){ if(epochLength == 0) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return (0, startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint elapsedEpochs = (block.timestamp - startTime)/epochLength; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(elapsedEpochs==0) return (0, startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC elapsedEpochs = elapsedEpochs>paymentsRemaining?paymentsRemaining:elapsedEpochs; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint newStartTime = block.timestamp; uint newPaymentsRemaining = paymentsRemaining.sub(elapsedEpochs); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint balance =_token.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint accumulatedFunds = paymentSize.mul(elapsedEpochs); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return (beneficiaryBalance.add(accumulatedFunds>balance?balance:accumulatedFunds),newStartTime,newPaymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function updateBeneficiaryBalance() private { (beneficiaryBalance,startTime, paymentsRemaining) = getElapsedReward(); } function changeBeneficiary (address beneficiary) public onlyOwner{ require (paymentsRemaining == 0, 'TokenTimelock: cannot change beneficiary while token balance positive'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _beneficiary = beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solhint-disable-next-line not-rely-on-time require(block.timestamp >= startTime, "TokenTimelock: current time is before release time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC updateBeneficiaryBalance(); uint amountToSend = beneficiaryBalance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC beneficiaryBalance = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(amountToSend>0) require(_token.transfer(_beneficiary,amountToSend),'release funds failed'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit FundsReleasedToBeneficiary(_beneficiary,amountToSend,block.timestamp); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } event PaymentsUpdatedOnDeposit(uint paymentSize,uint startTime, uint paymentsRemaining); event Initialized (address tokenAddress, address beneficiary, uint duration,uint periods); event FundsReleasedToBeneficiary(address beneficiary, uint value, uint timeStamp); }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
epochLength = durationMultiple *52 weeks;
12,754,191
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 7632, 1782, 273, 225, 3734, 8438, 380, 9401, 17314, 31, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); uint public constant STAGE_3_FINISH = 1535414340; function isTransferLocked() public view returns (bool) { if(now > STAGE_3_FINISH){ return false; } return true; } address public crowdsaleContract; function setCrowdsaleContract(address _address) public { require (crowdsaleContract == address(0)); crowdsaleContract = _address; balanceOf[crowdsaleContract] = 67100000 * 10 ** uint256(decimals); emit Transfer(address(this),crowdsaleContract, 67100000 * 10 ** uint256(decimals)); } address public tokenHolderAddress = 0x44066Bc24c6DcC6ABA1bDef17e447ED2dC9DE967; function TokenERC20() public { totalSupply = 110000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[tokenHolderAddress] = 42900000 * 10 ** uint256(decimals); // Give the creator all initial tokens name = "BitChord"; // Set the name for display purposes symbol = "BCD"; // Set the symbol for display purposes emit Transfer(address(this), tokenHolderAddress, 42900000 * 10 ** uint256(decimals)); } /** * 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; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { require (!isTransferLocked() || msg.sender == crowdsaleContract || msg.sender == tokenHolderAddress); _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) { require (!isTransferLocked() || _from == crowdsaleContract || _from == tokenHolderAddress); 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 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) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on 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) { require (!isTransferLocked()); tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
* Set allowance for other address and notify Allows `_spender` to spend no more than `_value` tokens on 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) { require (!isTransferLocked()); tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
10,289,342
[ 1, 694, 1699, 1359, 364, 1308, 1758, 471, 5066, 25619, 1375, 67, 87, 1302, 264, 68, 358, 17571, 1158, 1898, 2353, 1375, 67, 1132, 68, 2430, 603, 3433, 12433, 6186, 16, 471, 1508, 10087, 326, 6835, 2973, 518, 225, 389, 87, 1302, 264, 1021, 1758, 10799, 358, 17571, 225, 389, 1132, 326, 943, 3844, 2898, 848, 17571, 225, 389, 7763, 751, 2690, 2870, 1779, 358, 1366, 358, 326, 20412, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 16, 1731, 389, 7763, 751, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 16051, 291, 5912, 8966, 10663, 540, 203, 3639, 1147, 18241, 17571, 264, 273, 1147, 18241, 24899, 87, 1302, 264, 1769, 203, 3639, 309, 261, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 3719, 288, 203, 5411, 17571, 264, 18, 18149, 23461, 12, 3576, 18, 15330, 16, 389, 1132, 16, 333, 16, 389, 7763, 751, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../interfaces/IPlushFaucet.sol"; import "../interfaces/IPlushAccounts.sol"; import "../token/ERC721/LifeSpan.sol"; contract PlushFaucet is Initializable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable, IPlushFaucet { using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable public plush; LifeSpan public lifeSpan; IPlushAccounts public plushAccounts; mapping(address => uint256) private nextRequestAt; mapping(address => uint256) private alreadyReceived; uint256 public faucetDripAmount; uint256 public faucetTimeLimit; uint256 private maxReceiveAmount; bool private tokenNFTCheck; /** * @dev Roles definitions */ bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant BANKER_ROLE = keccak256("BANKER_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize(IERC20Upgradeable _plush, LifeSpan _lifeSpan, IPlushAccounts _plushAccounts) initializer public { plush = _plush; lifeSpan = _lifeSpan; plushAccounts = _plushAccounts; faucetTimeLimit = 24 hours; faucetDripAmount = 1 * 10 ** 18; maxReceiveAmount = 100 * 10 ** 18; tokenNFTCheck = true; __Pausable_init(); __AccessControl_init(); __UUPSUpgradeable_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); _grantRole(BANKER_ROLE, msg.sender); _grantRole(OPERATOR_ROLE, msg.sender); _grantRole(UPGRADER_ROLE, msg.sender); } /// @notice Pause contract function pause() public onlyRole(PAUSER_ROLE) { _pause(); } /// @notice Unpause contract function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /// @notice Get tokens from faucet function send() external { require(plush.balanceOf(address(this)) >= faucetDripAmount, "The faucet is empty"); require(nextRequestAt[msg.sender] < block.timestamp, "Try again later"); require(alreadyReceived[msg.sender] < maxReceiveAmount, "Quantity limit"); if (tokenNFTCheck) { require(lifeSpan.balanceOf(msg.sender) > 0, "Required to have LifeSpan NFT"); } // Next request from the address can be made only after faucetTime nextRequestAt[msg.sender] = block.timestamp + faucetTimeLimit; alreadyReceived[msg.sender] += faucetDripAmount; plush.approve(address(plushAccounts), faucetDripAmount); require(plush.allowance(address(this), address(plushAccounts)) >= faucetDripAmount, "Not enough allowance"); plushAccounts.deposit(msg.sender, faucetDripAmount); emit TokensSent(msg.sender, faucetDripAmount); } /** * @notice Set ERC-20 faucet token * @param newAddress contract address of new token */ function setTokenAddress(address newAddress) external onlyRole(OPERATOR_ROLE) { plush = IERC20Upgradeable(newAddress); } /** * @notice Set faucet drip amount * @param amount new faucet drip amount */ function setFaucetDripAmount(uint256 amount) external onlyRole(OPERATOR_ROLE) { faucetDripAmount = amount; } /** * @notice Set the maximum amount of tokens that a user can receive for the entire time * @param amount new maximum amount */ function setMaxReceiveAmount(uint256 amount) external onlyRole(OPERATOR_ROLE) { maxReceiveAmount = amount; } /** * @notice Set the time after which the user will be able to use the faucet * @param time new faucet time limit in seconds (timestamp) */ function setFaucetTimeLimit(uint256 time) external onlyRole(OPERATOR_ROLE) { faucetTimeLimit = time; } /// @notice Enable the LifeSpan NFT check for using the faucet function setEnableNFTCheck() external onlyRole(OPERATOR_ROLE) { require(tokenNFTCheck == false, "Already active"); tokenNFTCheck = true; } /// @notice Disable the LifeSpan NFT check for using the faucet function setDisableNFTCheck() external onlyRole(OPERATOR_ROLE) { require(tokenNFTCheck == true, "Already disabled"); tokenNFTCheck = false; } /** * @notice Withdraw the required number of tokens from the faucet * @param amount required token amount (ERC-20) * @param receiver address of the tokens recipient */ function withdraw(uint256 amount, address receiver) external onlyRole(BANKER_ROLE) { require(plush.balanceOf(address(this)) >= amount, "The faucet is empty"); require(plush.transfer(receiver, amount), "Transaction error"); emit TokensWithdrawn(msg.sender, receiver, amount); } /** * @notice Return how many tokens a user can get in total for the entire time * @return number of tokens in wei */ function getMaxReceiveAmount() public view returns (uint256) { return maxReceiveAmount; } /** * @notice Return how many tokens you can get at one time * @return number of tokens in wei */ function getFaucetDripAmount() public view returns (uint256) { return faucetDripAmount; } /** * @notice Return the faucet balance * @return number of tokens in wei */ function getFaucetBalance() public view returns (uint256) { return plush.balanceOf(address(this)); } /** * @notice Return the time limit between interaction with the faucet * @return number of seconds (timestamp) */ function getTimeLimit() public view returns (uint256) { return faucetTimeLimit; } /** * @notice Return whether the faucet checks for the presence of LifeSpan NFT * @return boolean */ function getIsTokenNFTCheck() public view returns (bool) { return tokenNFTCheck; } /** * @notice Return the time how long the user has to wait before using the faucet again * @return number of seconds (timestamp) */ function getUserTimeLimit(address receiver) external view returns (uint256) { if (nextRequestAt[receiver] <= block.timestamp || nextRequestAt[receiver] == 0) { return 0; } return nextRequestAt[receiver] - block.timestamp; } /** * @notice Check whether the user can use the faucet * @return boolean */ function getCanTheAddressReceiveReward(address receiver) external view returns (bool) { require(plush.balanceOf(address(this)) >= faucetDripAmount, "The faucet is empty"); require(nextRequestAt[receiver] < block.timestamp, "Try again later"); require(alreadyReceived[receiver] < maxReceiveAmount, "Quantity limit"); if (tokenNFTCheck) { require(lifeSpan.balanceOf(receiver) > 0, "Required to have LifeSpan NFT"); } return true; } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER_ROLE) override {} }
* @notice Return whether the faucet checks for the presence of LifeSpan NFT @return boolean/
function getIsTokenNFTCheck() public view returns (bool) { return tokenNFTCheck; }
13,121,754
[ 1, 990, 2856, 326, 11087, 5286, 278, 4271, 364, 326, 9805, 434, 28128, 6952, 423, 4464, 327, 1250, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14279, 1345, 50, 4464, 1564, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1147, 50, 4464, 1564, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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 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) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract UsdcRepayment is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; event Claim(address from, address to, address token, uint256 amount); event TokenSeized(address token, uint256 amount); event Paused(bool paused); event MerkleRootUpdated(bytes32 oldMerkleRoot, bytes32 newMerkleRoot); event ExcludedUpdated(address user, address token, uint256 amount); address public immutable USDC; bytes32 public merkleRoot; bool public paused; mapping(address => uint256) public excluded; mapping(address => bool) public claimed; address public creth2Repayment; constructor(bytes32 _merkleRoot, address _token) { merkleRoot = _merkleRoot; USDC = _token; } function claim(uint256 amount, bytes32[] memory proof) external { _claimAndTransfer(msg.sender, msg.sender, amount, proof); } function claimFor(address _address, uint256 amount, bytes32[] memory proof) external { require(msg.sender == creth2Repayment, "creth2Repayment contract only"); _claimAndTransfer(_address, _address, amount, proof); } // Like claim(), but transfer to `to` address. function claimAndTransfer(address to, uint256 amount, bytes32[] memory proof) external { _claimAndTransfer(msg.sender, to, amount, proof); } // Claim for a contract and transfer tokens to `to` address. function adminClaimAndTransfer(address from, address to, uint256 amount, bytes32[] memory proof) external onlyOwner { require(Address.isContract(from), "not a contract"); _claimAndTransfer(from, to, amount, proof); } function _claimAndTransfer(address from, address to, uint256 amount, bytes32[] memory proof) internal nonReentrant { require(claimed[from] == false, "claimed"); require(!paused, "claim paused"); // Check the Merkle proof. bytes32 leaf = keccak256(abi.encodePacked(from, amount)); bool verified = MerkleProof.verify(proof, merkleRoot, leaf); require(verified, "invalid amount"); // Update the storage. claimed[from] = true; if (amount > excluded[from]) { IERC20(USDC).transfer(to, amount - excluded[from]); emit Claim(from, to, USDC, amount - excluded[from]); } } function seize(address token, uint amount) external onlyOwner { IERC20(token).safeTransfer(owner(), amount); emit TokenSeized(token, amount); } function updateMerkleTree(bytes32 _merkleRoot) external onlyOwner { bytes32 oldMerkleRoot = merkleRoot; merkleRoot = _merkleRoot; emit MerkleRootUpdated(oldMerkleRoot, _merkleRoot); } function pause(bool _paused) external onlyOwner { require(paused != _paused, "invalid paused"); paused = _paused; emit Paused(_paused); } function setExcluded(address user, uint256 amount) external onlyOwner { require(!claimed[user], "already claimed"); if (amount != excluded[user]) { excluded[user] = amount; emit ExcludedUpdated(user, USDC, amount); } } function setCreth2Repayment(address _creth2Repayment) external onlyOwner { creth2Repayment = _creth2Repayment; } }
Like claim(), but transfer to `to` address.
function claimAndTransfer(address to, uint256 amount, bytes32[] memory proof) external { _claimAndTransfer(msg.sender, to, amount, proof); }
6,950,475
[ 1, 8804, 7516, 9334, 1496, 7412, 358, 1375, 869, 68, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 1876, 5912, 12, 2867, 358, 16, 2254, 5034, 3844, 16, 1731, 1578, 8526, 3778, 14601, 13, 3903, 288, 203, 3639, 389, 14784, 1876, 5912, 12, 3576, 18, 15330, 16, 358, 16, 3844, 16, 14601, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.24; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; function balanceOf(address _owner) external view returns (uint256 amount); function transfer(address _to, uint256 _value) external returns(bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); } contract Burnable { function burn(uint256 _value) external returns(bool success); function burnFrom(address _from, uint256 _value) external returns(bool success); // This notifies clients about the amount burnt event Burn(address indexed _from, uint256 _value); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; modifier onlyOwner { require(msg.sender == owner, "only Owner can do this"); _; } function transferOwnership(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require(msg.sender == newOwner, "only new Owner can do this"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } event OwnershipTransferred(address indexed _from, address indexed _to); } contract Permissioned { function approve(address _spender, uint256 _value) public returns(bool success); function transferFrom(address _from, address _to, uint256 _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns (uint256 amount); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "mul overflow"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "div by zero"); uint256 c = a / b; 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, "sub overflow"); 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, "add overflow"); return c; } } //interface for approveAndCall interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /** @title NelCoin token. */ contract NelCoin is ERC20Interface, Burnable, Owned, Permissioned { // be aware of overflows using SafeMath for uint256; // This creates an array with all balances mapping(address => uint256) internal _balanceOf; // This creates an array with all allowance mapping(address => mapping(address => uint256)) internal _allowance; uint public forSale; /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { owner = msg.sender; symbol = "NEL"; name = "NelCoin"; decimals = 2; forSale = 12000000 * (10 ** uint(decimals)); totalSupply = 21000000 * (10 ** uint256(decimals)); _balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } /** * Get the token balance for account * * Get token balance of `_owner` account * * @param _owner The address of the owner */ function balanceOf(address _owner) external view returns(uint256 balance) { return _balanceOf[_owner]; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0), "use burn() instead"); // Check if the sender has enough require(_balanceOf[_from] >= _value, "not enough balance"); // Subtract from the sender _balanceOf[_from] = _balanceOf[_from].sub(_value); // Add the same to the recipient _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } /** * 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) external returns(bool success) { _transfer(msg.sender, _to, _value); return true; } /** * 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) external returns(bool success) { require(_value <= _allowance[_from][msg.sender], "allowance too loow"); // Check allowance _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); emit Approval(_from, _to, _allowance[_from][_to]); return true; } /** * 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) { _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on 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) external returns(bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) external view returns(uint256 amount) { return _allowance[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) external returns(bool success) { _allowance[msg.sender][_spender] = _allowance[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, _allowance[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) external returns(bool success) { uint256 oldValue = _allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { _allowance[msg.sender][_spender] = 0; } else { _allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, _allowance[msg.sender][_spender]); return true; } /** * @dev Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) external returns(bool success) { _burn(msg.sender, _value); return true; } /** * @dev 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) external returns(bool success) { require(_value <= _allowance[_from][msg.sender], "allowance too low"); // Check allowance require(_value <= _balanceOf[_from], "balance too low"); // Is tehere enough coins on account _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _burn(_from, _value); emit Approval(_from, msg.sender, _allowance[_from][msg.sender]); return true; } //internal burn function function _burn(address _from, uint256 _value) internal { require(_balanceOf[_from] >= _value, "balance too low"); // Check if the targeted balance is enough _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(_from, address(0), _value); } //We accept intentional donations in ETH event Donated(address indexed _from, uint256 _value); /** * Donate ETH tokens to contract (Owner) */ function donation() external payable returns (bool success){ emit Donated(msg.sender, msg.value); return(true); } //Don`t accept accidental ETH function() external payable { require(false, "Use fund() or donation()"); } /** * Buy NelCoin using ETH * Contract is selling tokens at price 20000NEL/1ETH, * total 12000000NEL for sale */ function fund() external payable returns (uint amount){ require(forSale > 0, "Sold out!"); uint tokenCount = ((msg.value).mul(20000 * (10 ** uint(decimals)))).div(10**18); require(tokenCount >= 1, "Send more ETH to buy at least one token!"); require(tokenCount <= forSale, "You want too much! Check forSale()"); forSale -= tokenCount; _transfer(owner, msg.sender, tokenCount); return tokenCount; } /** * Tranfer all ETH from contract to Owner addres. */ function withdraw() onlyOwner external returns (bool success){ require(address(this).balance > 0, "Nothing to withdraw"); owner.transfer(address(this).balance); return true; } /** * Transfer some ETH tokens from contract * * Transfer _value of ETH from contract to Owner addres. * @param _value number of wei to trasfer */ function withdraw(uint _value) onlyOwner external returns (bool success){ require(_value > 0, "provide amount pls"); require(_value < address(this).balance, "Too much! Check balance()"); owner.transfer(_value); return true; } /** * Check ETH balance of contract */ function balance() external view returns (uint amount){ return (address(this).balance); } /** * Transfer ERC20 tokens from contract * * Tranfer _amount of ERC20 from contract _tokenAddress to Owner addres. * * @param _amount amount of ERC20 tokens to be transferred * @param _tokenAddress address of ERC20 token contract */ function transferAnyERC20Token(address _tokenAddress, uint256 _amount) onlyOwner external returns(bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _amount); } }
---------------------------------------------------------------------------- ERC Token Standard #20 Interface https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md ----------------------------------------------------------------------------
contract ERC20Interface { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; function balanceOf(address _owner) external view returns (uint256 amount); function transfer(address _to, uint256 _value) external returns(bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); }
1,818,192
[ 1, 5802, 7620, 4232, 39, 3155, 8263, 4200, 6682, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 10721, 19, 7525, 19, 41, 2579, 55, 19, 73, 625, 17, 3462, 18, 1264, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 1358, 288, 203, 377, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 261, 11890, 5034, 3844, 1769, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 3903, 1135, 12, 6430, 2216, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 2254, 5034, 389, 1132, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens interface ERC721 { // Required methods function totalSupply() external view returns (uint256 total); function balanceOf(address _owner) external view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of pony 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of dad /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); // calculate the cooldown of child pony function processCooldown(uint16 childGen, uint256 targetBlock) public returns (uint16); // calculate the result for upgrading pony function upgradePonyResult(uint8 unicornation, uint256 targetBlock) public returns (bool); function setMatingSeason(bool _isMatingSeason) public returns (bool); } /// @title Interface for contracts conforming to ERC-20 interface ERC20 { //core ERC20 functions function transfer(address _to, uint _value) external returns (bool success); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool success); function transferPreSigned(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external returns (bool); function recoverSigner(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external view returns (address); } /** * @title Signature verifier * @dev To verify C level actions */ contract SignatureVerifier { function splitSignature(bytes sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recover(bytes32 hash, bytes sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables (v, r, s) = splitSignature(sig); // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); return ecrecover(prefixedHash, v, r, s); } } } /** * @title A DEKLA token access control * @author DEKLA (https://www.dekla.io) * @dev The Dekla token has 3 C level address to manage. * They can execute special actions but it need to be approved by another C level address. */ contract AccessControl is SignatureVerifier { using SafeMath for uint256; // C level address that can execute special actions. address public ceoAddress; address public cfoAddress; address public cooAddress; address public systemAddress; uint256 public CLevelTxCount_ = 0; mapping(address => uint256) nonces; // @dev C level transaction must be approved with another C level address modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @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); _; } // @dev return true if transaction already signed by a C Level address // @param _message The string to be verify function signedByCLevel( bytes32 _message, bytes _sig ) internal view onlyCLevel returns (bool) { address signer = recover(_message, _sig); require(signer != msg.sender); return ( signer == cooAddress || signer == ceoAddress || signer == cfoAddress ); } // @dev return true if transaction already signed by a C Level address // @param _message The string to be verify // @param _sig the signature from signing the _message with system key function signedBySystem( bytes32 _message, bytes _sig ) internal view returns (bool) { address signer = recover(_message, _sig); require(signer != msg.sender); return ( signer == systemAddress ); } /** * @notice Hash (keccak256) of the payload used by setCEO * @param _newCEO address The address of the new CEO * @param _nonce uint256 setCEO transaction number. */ function getCEOHashing(address _newCEO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E94), _newCEO, _nonce)); } // @dev Assigns a new address to act as the CEO. The C level transaction, must verify. // @param _newCEO The address of the new CEO // @param _sig the signature from signing the _message with CEO key function setCEO( address _newCEO, bytes _sig ) external onlyCLevel { require( _newCEO != address(0) && _newCEO != cfoAddress && _newCEO != cooAddress ); bytes32 hashedTx = getCEOHashing(_newCEO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; ceoAddress = _newCEO; CLevelTxCount_++; } /** * @notice Hash (keccak256) of the payload used by setCFO * @param _newCFO address The address of the new CFO * @param _nonce uint256 setCFO transaction number. */ function getCFOHashing(address _newCFO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E95), _newCFO, _nonce)); } // @dev Assigns a new address to act as the CFO. The C level transaction, must verify. // @param _newCFO The address of the new CFO function setCFO( address _newCFO, bytes _sig ) external onlyCLevel { require( _newCFO != address(0) && _newCFO != ceoAddress && _newCFO != cooAddress ); bytes32 hashedTx = getCFOHashing(_newCFO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; cfoAddress = _newCFO; CLevelTxCount_++; } /** * @notice Hash (keccak256) of the payload used by setCOO * @param _newCOO address The address of the new COO * @param _nonce uint256 setCO transaction number. */ function getCOOHashing(address _newCOO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E96), _newCOO, _nonce)); } // @dev Assigns a new address to act as the COO. The C level transaction, must verify. // @param _newCOO The address of the new COO, _sig signature used to verify COO address // @param _sig the signature from signing the _newCOO with 1 of the C-level key function setCOO( address _newCOO, bytes _sig ) external onlyCLevel { require( _newCOO != address(0) && _newCOO != ceoAddress && _newCOO != cfoAddress ); bytes32 hashedTx = getCOOHashing(_newCOO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; cooAddress = _newCOO; CLevelTxCount_++; } function getNonces(address _sender) public view returns (uint256) { return nonces[_sender]; } } /// @title A facet of PonyCore that manages special access privileges. contract PonyAccessControl is AccessControl { /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBase is PonyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new pony comes into existence. This obviously /// includes any time a pony is created through the giveBirth method, but it is also called /// when a new gen0 pony is created. event Birth(address owner, uint256 ponyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a pony /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Pony struct. Every pony in MyEtherPonies is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Pony { // The Pony's genetic code is packed into these 256-bits, the format is // sooper-sekret! A pony's genes never change. uint256 genes; // The timestamp from the block when this pony came into existence. uint64 birthTime; // The minimum timestamp after which this pony can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Pony, set to 0 for gen0 ponies. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion ponies. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire pony for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a pony // is pregnant. Used to retrieve the genetic material for the new // pony when the birth transpires. uint32 matingWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Pony. This starts at zero // for gen0 ponies, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this ponies is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this pony. ponies minted by the EP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other ponies is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; uint16 txCount; uint8 unicornation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a pony /// is bred, encouraging owners not to just keep breeding the same pony over /// and over again. Caps out at one week (a pony can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[10] public cooldowns = [ uint32(1 minutes), uint32(5 minutes), uint32(30 minutes), uint32(1 hours), uint32(4 hours), uint32(8 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; uint8[5] public incubators = [ uint8(5), uint8(10), uint8(15), uint8(20), uint8(25) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Pony struct for all Ponies in existence. The ID /// of each pony is actually an index into this array. Note that ID 0 is a genesispony, /// the unPony, the mythical beast that is the parent of all gen0 ponies. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, pony ID 0 is invalid... ;-) Pony[] ponies; /// @dev A mapping from ponies IDs to the address that owns them. All ponies have /// some valid owner address, even gen0 ponies are created with a non-zero owner. mapping(uint256 => address) public ponyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping(address => uint256) ownershipTokenCount; /// @dev A mapping from PonyIDs to an address that has been approved to call /// transferFrom(). Each Pony can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping(uint256 => address) public ponyIndexToApproved; /// @dev A mapping from PonyIDs to an address that has been approved to use /// this Pony for siring via breedWith(). Each Pony can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping(uint256 => address) public matingAllowedToAddress; mapping(address => bool) public hasIncubator; /// @dev The address of the ClockAuction contract that handles sales of Ponies. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; BiddingClockAuction public biddingAuction; /// @dev Assigns ownership of a specific Pony to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of ponies is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership ponyIndexToOwner[_tokenId] = _to; // When creating new ponies _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the pony is transferred also clear sire allowances delete matingAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete ponyIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Pony and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Pony ID of the matron of this pony (zero for gen0) /// @param _sireId The Pony ID of the sire of this pony (zero for gen0) /// @param _generation The generation number of this pony, must be computed by caller. /// @param _genes The Pony's genetic code. /// @param _owner The inital owner of this pony, must be non-zero (except for the unPony, ID 0) function _createPony( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner, uint16 _cooldownIndex ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createPony() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); Pony memory _pony = Pony({ genes : _genes, birthTime : uint64(now), cooldownEndBlock : 0, matronId : uint32(_matronId), sireId : uint32(_sireId), matingWithId : 0, cooldownIndex : _cooldownIndex, generation : uint16(_generation), unicornation : 0, txCount : 0 }); uint256 newPonyId = ponies.push(_pony) - 1; require(newPonyId == uint256(uint32(newPonyId))); // emit the birth event emit Birth( _owner, newPonyId, uint256(_pony.matronId), uint256(_pony.sireId), _pony.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPonyId); return newPonyId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The facet of the EtherPonies core contract that manages ownership, ERC-721 (draft) compliant. /// @author Dekla (https://www.dekla.io) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyOwnership is PonyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "EtherPonies"; string public constant symbol = "EP"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Pony. /// @param _claimant the address we are validating against. /// @param _tokenId pony id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ponyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Pony. /// @param _claimant the address we are confirming pony is approved for. /// @param _tokenId pony id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ponyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Ponies on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ponyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Ponies owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Pony to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// EtherPonies specifically) or your Pony may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Pony to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any ponies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // You can only send your own pony. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Pony via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Pony that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Pony owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Pony to be transfered. /// @param _to The address that should take ownership of the Pony. Can be any address, /// including the caller. /// @param _tokenId The ID of the Pony to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Ponies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Ponies currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return ponies.length - 1; } /// @notice Returns the address currently assigned ownership of a given Pony. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ponyIndexToOwner[_tokenId]; } /// @notice Returns a list of all Pony IDs assigned to an address. /// @param _owner The owner whose Ponies we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Pony array looking for ponies belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPonies = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all ponies have IDs starting at 1 and increasing // sequentially up to the totalPony count. uint256 ponyId; for (ponyId = 1; ponyId <= totalPonies; ponyId++) { if (ponyIndexToOwner[ponyId] == _owner) { result[resultIndex] = ponyId; resultIndex++; } } return result; } } function transferPreSignedHashing( address _token, address _to, uint256 _id, uint256 _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E97), _token, _to, _id, _nonce)); } function transferPreSigned( bytes _signature, address _to, uint256 _id, uint256 _nonce ) public { require(_to != address(0)); // require(signatures[_signature] == false); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _id, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); require(_to != address(this)); // You can only send your own pony. require(_owns(from, _id)); nonces[from]++; // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(from, _to, _id); } function approvePreSignedHashing( address _token, address _spender, uint256 _tokenId, uint256 _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token, _spender, _tokenId, _nonce)); } function approvePreSigned( bytes _signature, address _spender, uint256 _tokenId, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); // require(signatures[_signature] == false); bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _tokenId, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); // Only an owner can grant transfer approval. require(_owns(from, _tokenId)); nonces[from]++; // Register the approval (replacing any previous approval). _approve(_tokenId, _spender); // Emit approval event. emit Approval(from, _spender, _tokenId); return true; } } /// @title A facet of PonyCore that manages Pony siring, gestation, and birth. /// @author Dekla (https://www.dekla.io) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBreeding is PonyOwnership { /// @dev The Pregnant event is fired when two ponies successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant Ponies. uint256 public pregnantPonies; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given pony is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToMate(Pony _pon) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the pony has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_pon.matingWithId == 0) && (_pon.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isMatingPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = ponyIndexToOwner[_matronId]; address sireOwner = ponyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || matingAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Pony, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _pony A reference to the Pony in storage which needs its timer started. function _triggerCooldown(Pony storage _pony) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_pony.cooldownIndex < 13) { _pony.cooldownIndex += 1; } } function _triggerPregnant(Pony storage _pony, uint8 _incubator) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). if (_incubator > 0) { uint64 initialCooldown = uint64(cooldowns[_pony.cooldownIndex] / secondsPerBlock); _pony.cooldownEndBlock = uint64((initialCooldown - (initialCooldown * incubators[_incubator] / 100)) + block.number); } else { _pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number); } // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_pony.cooldownIndex < 13) { _pony.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Ponies. /// @param _addr The address that will be able to sire with your Pony. Set to /// address(0) to clear all siring approvals for this Pony. /// @param _sireId A Pony that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); matingAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Pony is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Pony _matron) private view returns (bool) { return (_matron.matingWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given pony is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _ponyId reference the id of the pony, any user can inquire about it function isReadyToMate(uint256 _ponyId) public view returns (bool) { require(_ponyId > 0); Pony storage pon = ponies[_ponyId]; return _isReadyToMate(pon); } /// @dev Checks whether a Pony is currently pregnant. /// @param _ponyId reference the id of the pony, any user can inquire about it function isPregnant(uint256 _ponyId) public view returns (bool) { require(_ponyId > 0); // A Pony is pregnant if and only if this field is set return ponies[_ponyId].matingWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Pony struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Pony struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Pony storage _matron, uint256 _matronId, Pony storage _sire, uint256 _sireId ) private view returns (bool) { // A Pony can't breed with itself! if (_matronId == _sireId) { return false; } // Ponies can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either pony is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Ponies can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev 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 canMateWithViaAuction(uint256 _matronId, uint256 _sireId) public view returns (bool) { Pony storage matron = ponies[_matronId]; Pony storage sire = ponies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two ponies can breed together, including checks for /// ownership and siring approvals. Does NOT check that both ponies are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canMateWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { require(_matronId > 0); require(_sireId > 0); Pony storage matron = ponies[_matronId]; Pony storage sire = ponies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isMatingPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _mateWith(uint256 _matronId, uint256 _sireId, uint8 _incubator) internal { // Grab a reference to the Ponies from storage. Pony storage sire = ponies[_sireId]; Pony storage matron = ponies[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.matingWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerPregnant(matron, _incubator); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete matingAllowedToAddress[_matronId]; delete matingAllowedToAddress[_sireId]; // Every time a Pony gets pregnant, counter is incremented. pregnantPonies++; // Emit the pregnancy event. emit Pregnant(ponyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } function getIncubatorHashing( address _sender, uint8 _incubator, uint256 txCount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E98), _sender, _incubator, txCount)); } /// @notice Breed a Pony you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your pony pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Pony acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Pony acting as sire (will begin its siring cooldown if successful) function mateWithAuto(uint256 _matronId, uint256 _sireId, uint8 _incubator, bytes _sig) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); require(_isMatingPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Pony storage matron = ponies[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToMate(matron)); // Grab a reference to the potential sire Pony storage sire = ponies[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToMate(sire)); // Test that these ponies are a valid mating pair. require( _isValidMatingPair(matron, _matronId, sire, _sireId) ); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @notice Have a pregnant Pony give birth! /// @param _matronId A Pony ready to give birth. /// @return The Pony ID of the new pony. /// @dev Looks at a given Pony and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new pony. The new Pony is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new pony will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new pony always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns (uint256) { // Grab a reference to the matron in storage. Pony storage matron = ponies[_matronId]; // Check that the matron is a valid pony. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.matingWithId; Pony storage sire = ponies[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // New Pony starts with the same cooldown as parent gen/20 uint16 cooldownIndex = geneScience.processCooldown(parentGen + 1, block.number); if (cooldownIndex > 13) { cooldownIndex = 13; } // Make the new pony! address owner = ponyIndexToOwner[_matronId]; uint256 ponyId = _createPony(_matronId, matron.matingWithId, parentGen + 1, childGenes, owner, cooldownIndex); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.matingWithId; // Every time a Pony gives birth counter is decremented. pregnantPonies--; // Send the balance fee to the person who made birth happen. msg.sender.transfer(autoBirthFee); // return the new pony's ID return ponyId; } function setMatingSeason(bool _isMatingSeason) external onlyCLevel { geneScience.setMatingSeason(_isMatingSeason); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; uint256 price; bool allowPayDekla; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; ERC20 public tokens; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 500; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidEth(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(!auction.allowPayDekla); // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = auction.price; require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidDkl(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.allowPayDekla); // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = auction.price; require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; tokens.transfer(seller, sellerProceeds); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.price > 0); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is AccessControl{ event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyCEO whenNotPaused public returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyCEO whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. constructor(address _nftAddress, address _tokenAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); tokens = ERC20(_tokenAddress); nonFungibleContract = candidateContract; } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCEO external { Auction storage auction = tokenIdToAuction[_tokenId]; _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, bool allowPayDekla ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.price, auction.allowPayDekla ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return auction.price; } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; address prizeAddress; // Delegate constructor constructor(address _nftAddr, address _tokenAddress, address _prizeAddress) public ClockAuction(_nftAddr, _tokenAddress) { prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createEthAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); require(_price > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, false ); _addAuction(_tokenId, auction); } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); require(_price > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the PonyCore contract because all bid methods /// should be wrapped. Also returns the pony to the /// seller rather than the winner. function bidEth(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bidEth(_tokenId, msg.value); // We transfer the pony back to the seller, the winner will get // the offspring uint256 prizeAmount = (msg.value * prizeCut) / 10000; prizeAddress.transfer(prizeAmount); _transfer(seller, _tokenId); } function bidDkl(uint256 _tokenId, uint256 _price, uint256 _fee, bytes _signature, uint256 _nonce) external whenNotPaused { address seller = tokenIdToAuction[_tokenId].seller; tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce); // _bid will throw if the bid or funds transfer fails _bidDkl(_tokenId, _price); tokens.transfer(msg.sender, _fee); address spender = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce); uint256 discountAmount = (_price * tokenDiscount) / 10000; uint256 prizeAmount = (_price * prizeCut) / 10000; tokens.transfer(prizeAddress, prizeAmount); tokens.transfer(spender, discountAmount); _transfer(seller, _tokenId); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this)); } } /// @title Clock auction modified for sale of Ponies /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; address prizeAddress; // Tracks last 5 sale price of gen0 Pony sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor constructor(address _nftAddr, address _token, address _prizeAddress) public ClockAuction(_nftAddr, _token) { prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createEthAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, false ); _addAuction(_tokenId, auction); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); } function bidEth(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bidEth(_tokenId, msg.value); uint256 prizeAmount = (msg.value * prizeCut) / 10000; prizeAddress.transfer(prizeAmount); _transfer(msg.sender, _tokenId); } function bidDkl(uint256 _tokenId, uint256 _price, uint256 _fee, bytes _signature, uint256 _nonce) external whenNotPaused { address buyer = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce); tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce); // _bid will throw if the bid or funds transfer fails _bidDkl(_tokenId, _price); uint256 prizeAmount = (_price * prizeCut) / 10000; uint256 discountAmount = (_price * tokenDiscount) / 10000; tokens.transfer(buyer, discountAmount); tokens.transfer(prizeAddress, prizeAmount); _transfer(buyer, _tokenId); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this)); } } /// @title Handles creating auctions for sale and siring of Ponies. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract PonyAuction is PonyBreeding { // @notice The auction contract variables are defined in PonyBase to allow // us to refer to them in PonyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of Ponies. // `siringAuction` refers to the auction for siring rights of Ponies. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Sets the reference to the bidding auction. /// @param _address - Address of bidding contract. function setBiddingAuctionAddress(address _address) external onlyCEO { BiddingClockAuction candidateContract = BiddingClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isBiddingClockAuction()); // Set the new contract address biddingAuction = candidateContract; } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createEthSaleAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createEthAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklSaleAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), saleAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, saleAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createDklAuction( _tokenId, from, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklSiringAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), siringAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, siringAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createDklAuction( _tokenId, from, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklBidAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce, uint16 _durationIndex ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), biddingAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, biddingAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. biddingAuction.createDklAuction(_tokenId, from, _durationIndex, _price); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createEthSiringAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToMate(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createEthAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createDklSaleAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createDklAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createDklSiringAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToMate(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createDklAuction( _PonyId, msg.sender, _price ); } function createEthBidAuction( uint256 _ponyId, uint256 _price, uint16 _durationIndex ) external whenNotPaused { require(_owns(msg.sender, _ponyId)); _approve(_ponyId, biddingAuction); biddingAuction.createETHAuction(_ponyId, msg.sender, _durationIndex, _price); } function createDeklaBidAuction( uint256 _ponyId, uint256 _price, uint16 _durationIndex ) external whenNotPaused { require(_owns(msg.sender, _ponyId)); _approve(_ponyId, biddingAuction); biddingAuction.createDklAuction(_ponyId, msg.sender, _durationIndex, _price); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnEthSiringAuction( uint256 _sireId, uint256 _matronId, uint8 _incubator, bytes _sig ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToMate(_matronId)); require(canMateWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bidEth.value(msg.value - autoBirthFee)(_sireId); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnDklSiringAuction( uint256 _sireId, uint256 _matronId, uint8 _incubator, bytes _incubatorSig, uint256 _price, uint256 _fee, bytes _delegateSig, uint256 _nonce ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToMate(_matronId)); require(canMateWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= autoBirthFee); require(_price >= currentPrice); // Siring auction will throw if the bid fails. siringAuction.bidDkl(_sireId, _price, _fee, _delegateSig, _nonce); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _incubatorSig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @dev Transfers the balance of the sale auction contract /// to the PonyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); biddingAuction.withdrawBalance(); } function withdrawAuctionDklBalance() external onlyCLevel { saleAuction.withdrawDklBalance(); siringAuction.withdrawDklBalance(); biddingAuction.withdrawDklBalance(); } function setBiddingRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { biddingAuction.setCut(_prizeCut, _tokenDiscount); } function setSaleRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { saleAuction.setCut(_prizeCut, _tokenDiscount); } function setSiringRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { siringAuction.setCut(_prizeCut, _tokenDiscount); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingAuctionBase { // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Duration (in seconds) of auction uint16 durationIndex; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; uint64 auctionEndBlock; // Price (in wei) at beginning of auction uint256 startingPrice; bool allowPayDekla; } uint32[4] public auctionDuration = [ //production uint32(2 days), uint32(3 days), uint32(4 days), uint32(5 days) ]; // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; uint256 public ownerCut = 500; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) public tokenIdToAuction; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingAuction is Pausable, BiddingAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. constructor(address _nftAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function cancelAuctionHashing( uint256 _tokenId, uint64 _endblock ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9E), _tokenId, _endblock)); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction( uint256 _tokenId, bytes _sig ) external { Auction storage auction = tokenIdToAuction[_tokenId]; address seller = auction.seller; uint64 endblock = auction.auctionEndBlock; require(msg.sender == seller); require(endblock < block.number); bytes32 hashedTx = cancelAuctionHashing(_tokenId, endblock); require(signedBySystem(hashedTx, _sig)); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCLevel external { Auction storage auction = tokenIdToAuction[_tokenId]; _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint64 startedAt, uint16 durationIndex, uint64 auctionEndBlock, uint256 startingPrice, bool allowPayDekla ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.startedAt, auction.durationIndex, auction.auctionEndBlock, auction.startingPrice, auction.allowPayDekla ); } function setSecondsPerBlock(uint256 secs) external onlyCEO { secondsPerBlock = secs; } } contract BiddingWallet is AccessControl { //user balances is stored in this balances map and could be withdraw by owner at anytime mapping(address => uint) public EthBalances; mapping(address => uint) public DeklaBalances; ERC20 public tokens; //the limit of deposit and withdraw the minimum amount you can deposit is 0.05 eth //you also have to have at least 0.05 eth uint public EthLimit = 50000000000000000; uint public DeklaLimit = 100; uint256 public totalEthDeposit; uint256 public totalDklDeposit; event withdrawSuccess(address receiver, uint amount); event cancelPendingWithdrawSuccess(address sender); function getNonces(address _address) public view returns (uint256) { return nonces[_address]; } function setSystemAddress(address _systemAddress, address _tokenAddress) internal { systemAddress = _systemAddress; tokens = ERC20(_tokenAddress); } //user will be assign an equivalent amount of bidding credit to bid function depositETH() payable external { require(msg.value >= EthLimit); EthBalances[msg.sender] = EthBalances[msg.sender] + msg.value; totalEthDeposit = totalEthDeposit + msg.value; } function depositDekla( uint256 _amount, uint256 _fee, bytes _signature, uint256 _nonce) external { address sender = tokens.recoverSigner(_signature, address(this), _amount, _fee, _nonce); tokens.transferPreSigned(_signature, address(this), _amount, _fee, _nonce); DeklaBalances[sender] = DeklaBalances[sender] + _amount; totalDklDeposit = totalDklDeposit + _amount; } function withdrawAmountHashing(uint256 _amount, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9B), _amount, _nonce)); } // Withdraw all available eth back to user wallet, need co-verify function withdrawEth( uint256 _amount, bytes _sig ) external { require(EthBalances[msg.sender] >= _amount); bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); EthBalances[msg.sender] = EthBalances[msg.sender] - _amount; totalEthDeposit = totalEthDeposit - _amount; msg.sender.transfer(_amount); nonces[msg.sender]++; emit withdrawSuccess(msg.sender, _amount); } // Withdraw all available dekla back to user wallet, need co-verify function withdrawDekla( uint256 _amount, bytes _sig ) external { require(DeklaBalances[msg.sender] >= _amount); bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); DeklaBalances[msg.sender] = DeklaBalances[msg.sender] - _amount; totalDklDeposit = totalDklDeposit - _amount; tokens.transfer(msg.sender, _amount); nonces[msg.sender]++; emit withdrawSuccess(msg.sender, _amount); } event valueLogger(uint256 value); //bidding success tranfer eth to seller wallet function winBidEth( address winner, address seller, uint256 sellerProceeds, uint256 auctioneerCut ) internal { require(EthBalances[winner] >= sellerProceeds + auctioneerCut); seller.transfer(sellerProceeds); EthBalances[winner] = EthBalances[winner] - (sellerProceeds + auctioneerCut); } //bidding success tranfer eth to seller wallet function winBidDekla( address winner, address seller, uint256 sellerProceeds, uint256 auctioneerCut ) internal { require(DeklaBalances[winner] >= sellerProceeds + auctioneerCut); tokens.transfer(seller, sellerProceeds); DeklaBalances[winner] = DeklaBalances[winner] - (sellerProceeds + auctioneerCut); } function() public { revert(); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingClockAuction is BiddingAuction, BiddingWallet { address public prizeAddress; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isBiddingClockAuction = true; modifier onlySystem() { require(msg.sender == systemAddress); _; } // Delegate constructor constructor( address _nftAddr, address _tokenAddress, address _prizeAddress, address _systemAddress, address _ceoAddress, address _cfoAddress, address _cooAddress) public BiddingAuction(_nftAddr) { // validate address require(_systemAddress != address(0)); require(_tokenAddress != address(0)); require(_ceoAddress != address(0)); require(_cooAddress != address(0)); require(_cfoAddress != address(0)); require(_prizeAddress != address(0)); setSystemAddress(_systemAddress, _tokenAddress); ceoAddress = _ceoAddress; cooAddress = _cooAddress; cfoAddress = _cfoAddress; prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. function createETHAuction( uint256 _tokenId, address _seller, uint16 _durationIndex, uint256 _startingPrice ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number); Auction memory auction = Auction( _seller, _durationIndex, uint64(now), auctionEndBlock, _startingPrice, false ); _addAuction(_tokenId, auction); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. function createDklAuction( uint256 _tokenId, address _seller, uint16 _durationIndex, uint256 _startingPrice ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number); Auction memory auction = Auction( _seller, _durationIndex, uint64(now), auctionEndBlock, _startingPrice, true ); _addAuction(_tokenId, auction); } function getNonces(address _address) public view returns (uint256) { return nonces[_address]; } function auctionEndHashing(uint _amount, uint256 _tokenId) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0F0E), _tokenId, _amount)); } function auctionEthEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem { bytes32 hashedTx = auctionEndHashing(_amount, _tokenId); require(recover(hashedTx, _sig) == _winner); Auction storage auction = tokenIdToAuction[_tokenId]; uint64 endblock = auction.auctionEndBlock; require(endblock < block.number); require(!auction.allowPayDekla); uint256 prize = _amount * prizeCut / 10000; uint256 auctioneerCut = _computeCut(_amount) - prize; uint256 sellerProceeds = _amount - auctioneerCut; winBidEth(_winner, auction.seller, sellerProceeds, auctioneerCut); prizeAddress.transfer(prize); _removeAuction(_tokenId); _transfer(_winner, _tokenId); emit AuctionSuccessful(_tokenId, _amount, _winner); } function auctionDeklaEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem { bytes32 hashedTx = auctionEndHashing(_amount, _tokenId); require(recover(hashedTx, _sig) == _winner); Auction storage auction = tokenIdToAuction[_tokenId]; uint64 endblock = auction.auctionEndBlock; require(endblock < block.number); require(auction.allowPayDekla); uint256 prize = _amount * prizeCut / 10000; uint256 discountAmount = _amount * tokenDiscount / 10000; uint256 auctioneerCut = _computeCut(_amount) - discountAmount - prizeCut; uint256 sellerProceeds = _amount - auctioneerCut; winBidDekla(_winner, auction.seller, sellerProceeds, auctioneerCut); tokens.transfer(prizeAddress, prize); tokens.transfer(_winner, discountAmount); _removeAuction(_tokenId); _transfer(_winner, _tokenId); emit AuctionSuccessful(_tokenId, _amount, _winner); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance - totalEthDeposit); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this) - totalDklDeposit); } } /// @title all functions related to creating ponies contract PonyMinting is PonyAuction { // Limits the number of ponies the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 50; uint256 public constant GEN0_CREATION_LIMIT = 4950; // Counts the number of ponies the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo ponies, up to a limit. Only callable by COO /// @param _genes the encoded genes of the pony to be created, any value is accepted /// @param _owner the future owner of the created ponies. Default to contract COO function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address ponyOwner = _owner; if (ponyOwner == address(0)) { ponyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, ponyOwner, 0); } /// @dev Creates a new gen0 Pony with the given genes and /// creates an auction for it. function createGen0(uint256 _genes, uint256 _price, uint16 _durationIndex, bool _saleDKL ) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 ponyId = _createPony(0, 0, 0, _genes, ceoAddress, 0); _approve(ponyId, biddingAuction); if(_saleDKL) { biddingAuction.createDklAuction(ponyId, ceoAddress, _durationIndex, _price); } else { biddingAuction.createETHAuction(ponyId, ceoAddress, _durationIndex, _price); } gen0CreatedCount++; } } contract PonyUpgrade is PonyMinting { event PonyUpgraded(uint256 upgradedPony, uint256 tributePony, uint8 unicornation); function upgradePonyHashing(uint256 _upgradeId, uint256 _txCount) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9D), _upgradeId, _txCount)); } function upgradePony(uint256 _upgradeId, uint256 _tributeId, bytes _sig) external whenNotPaused { require(_owns(msg.sender, _upgradeId)); require(_upgradeId != _tributeId); Pony storage upPony = ponies[_upgradeId]; bytes32 hashedTx = upgradePonyHashing(_upgradeId, upPony.txCount); require(signedBySystem(hashedTx, _sig)); upPony.txCount += 1; if (upPony.unicornation == 0) { if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) { upPony.unicornation += 1; emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } } else if (upPony.unicornation > 0) { require(_owns(msg.sender, _tributeId)); if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) { upPony.unicornation += 1; _transfer(msg.sender, address(0), _tributeId); emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } else if (upPony.unicornation == 2) { upPony.unicornation += 1; _transfer(msg.sender, address(0), _tributeId); emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } } } } /// @title EtherPonies: Collectible, breedable, and oh-so-adorable ponies on the Ethereum blockchain. /// @author Dekla (https://www.dekla.io) /// @dev The main EtherPonies contract, keeps track of ponies so they don't wander around and get lost. contract PonyCore is PonyUpgrade { event WithdrawEthBalanceSuccessful(address sender, uint256 amount); event WithdrawDeklaBalanceSuccessful(address sender, uint256 amount); // This is the main MyEtherPonies contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Pony ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - PonyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - PonyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - PonyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - PonyBreeding: This file contains the methods necessary to breed ponies together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - PonyAuctions: Here we have the public methods for auctioning or bidding on ponies or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - PonyMinting: This final facet contains the functionality we use for creating new gen0 ponies. // We can make up to 5000 "promo" ponies that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 ponies. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; // ERC20 basic token contract being held ERC20 public token; /// @notice Creates the main EtherPonies smart contract instance. constructor( address _ceoAddress, address _cfoAddress, address _cooAddress, address _systemAddress, address _tokenAddress ) public { // validate address require(_ceoAddress != address(0)); require(_cooAddress != address(0)); require(_cfoAddress != address(0)); require(_systemAddress != address(0)); require(_tokenAddress != address(0)); // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = _ceoAddress; cfoAddress = _cfoAddress; cooAddress = _cooAddress; systemAddress = _systemAddress; token = ERC20(_tokenAddress); // start with the mythical pony 0 - so we don't have generation-0 parent issues _createPony(0, 0, 0, uint256(- 1), address(0), 0); } //check that the token is set modifier validToken() { require(token != address(0)); _; } function getTokenAddressHashing(address _token, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A1216), _token, _nonce)); } function setTokenAddress(address _token, bytes _sig) external onlyCLevel { bytes32 hashedTx = getTokenAddressHashing(_token, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; token = ERC20(_token); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { } /// @notice Returns all the relevant information about a specific Pony. /// @param _id The ID of the Pony of interest. function getPony(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes, uint16 upgradeIndex, uint8 unicornation ) { Pony storage pon = ponies[_id]; // if this variable is 0 then it's not gestating isGestating = (pon.matingWithId != 0); isReady = (pon.cooldownEndBlock <= block.number); cooldownIndex = uint256(pon.cooldownIndex); nextActionAt = uint256(pon.cooldownEndBlock); siringWithId = uint256(pon.matingWithId); birthTime = uint256(pon.birthTime); matronId = uint256(pon.matronId); sireId = uint256(pon.sireId); generation = uint256(pon.generation); genes = pon.genes; upgradeIndex = pon.txCount; unicornation = pon.unicornation; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function withdrawBalanceHashing(address _address, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A1217), _address, _nonce)); } function withdrawEthBalance(address _withdrawWallet, bytes _sig) external onlyCLevel { bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); uint256 balance = address(this).balance; // Subtract all the currently pregnant ponies we have, plus 1 of margin. uint256 subtractFees = (pregnantPonies + 1) * autoBirthFee; require(balance > 0); require(balance > subtractFees); nonces[msg.sender]++; _withdrawWallet.transfer(balance - subtractFees); emit WithdrawEthBalanceSuccessful(_withdrawWallet, balance - subtractFees); } function withdrawDeklaBalance(address _withdrawWallet, bytes _sig) external validToken onlyCLevel { bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); uint256 balance = token.balanceOf(this); require(balance > 0); nonces[msg.sender]++; token.transfer(_withdrawWallet, balance); emit WithdrawDeklaBalanceSuccessful(_withdrawWallet, balance); } }
@title Auction Core @dev Contains models, variables, and internal methods for the auction. @notice We omit a fallback function to prevent accidental sends to this contract. Represents an auction on an NFT
contract ClockAuctionBase { struct Auction { address seller; uint256 price; bool allowPayDekla; } ERC20 public tokens; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); ERC721 public nonFungibleContract; uint256 public ownerCut = 500; mapping(uint256 => Auction) tokenIdToAuction; function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, this, _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } function _bidEth(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(!auction.allowPayDekla); require(_isOnAuction(auction)); uint256 price = auction.price; require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } return price; } function _bidEth(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(!auction.allowPayDekla); require(_isOnAuction(auction)); uint256 price = auction.price; require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } return price; } emit AuctionSuccessful(_tokenId, price, msg.sender); function _bidDkl(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.allowPayDekla); require(_isOnAuction(auction)); uint256 price = auction.price; require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; tokens.transfer(seller, sellerProceeds); } return price; } function _bidDkl(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.allowPayDekla); require(_isOnAuction(auction)); uint256 price = auction.price; require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; tokens.transfer(seller, sellerProceeds); } return price; } emit AuctionSuccessful(_tokenId, price, msg.sender); function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.price > 0); } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _computeCut(uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } }
6,389,635
[ 1, 37, 4062, 4586, 225, 8398, 3679, 16, 3152, 16, 471, 2713, 2590, 364, 326, 279, 4062, 18, 225, 1660, 14088, 279, 5922, 445, 358, 5309, 25961, 287, 9573, 358, 333, 6835, 18, 868, 6706, 87, 392, 279, 4062, 603, 392, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 18051, 37, 4062, 2171, 288, 203, 203, 565, 1958, 432, 4062, 288, 203, 3639, 1758, 29804, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 1426, 1699, 9148, 758, 79, 11821, 31, 203, 565, 289, 203, 203, 203, 565, 4232, 39, 3462, 1071, 2430, 31, 203, 203, 203, 203, 565, 871, 432, 4062, 6119, 12, 11890, 5034, 1147, 548, 1769, 203, 565, 871, 432, 4062, 14277, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 2078, 5147, 16, 1758, 5657, 1224, 1769, 203, 565, 871, 432, 4062, 21890, 12, 11890, 5034, 1147, 548, 1769, 203, 203, 565, 4232, 39, 27, 5340, 1071, 1661, 42, 20651, 1523, 8924, 31, 203, 565, 2254, 5034, 1071, 3410, 15812, 273, 6604, 31, 203, 565, 2874, 12, 11890, 5034, 516, 432, 4062, 13, 1147, 28803, 37, 4062, 31, 203, 565, 445, 389, 995, 87, 12, 2867, 389, 14784, 970, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 5836, 42, 20651, 1523, 8924, 18, 8443, 951, 24899, 2316, 548, 13, 422, 389, 14784, 970, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 742, 492, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 288, 203, 3639, 1661, 42, 20651, 1523, 8924, 18, 13866, 1265, 24899, 8443, 16, 333, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 24454, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 288, 203, 3639, 1661, 42, 20651, 1523, 8924, 18, 13866, 24899, 24454, 2 ]
./partial_match/1/0xdecaCC56fc347274D3Df2b709602632845611D39/sources/src/Staking.sol
@notice The pauser contract. @dev Keeps the pause state across the protocol.
IPauserRead public pauser;
4,386,054
[ 1, 1986, 6790, 1355, 6835, 18, 225, 10498, 87, 326, 11722, 919, 10279, 326, 1771, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2971, 69, 1355, 1994, 1071, 6790, 1355, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; //Libraries import './libraries/SafeMath.sol'; //Interfaces import './interfaces/IStrategyToken.sol'; import './interfaces/ITradingBot.sol'; import './interfaces/IIndicator.sol'; import './interfaces/IComparator.sol'; import './interfaces/IERC20.sol'; import './interfaces/IAddressResolver.sol'; import './interfaces/ITradingBotRewards.sol'; import './interfaces/ISettings.sol'; import './interfaces/IComponents.sol'; //Adapters import './adapters/interfaces/IBaseUbeswapAdapter.sol'; contract TradingBot is ITradingBot { using SafeMath for uint; IAddressResolver public ADDRESS_RESOLVER; //parameters Rule[] private _entryRules; Rule[] private _exitRules; uint public _maxTradeDuration; uint public _profitTarget; //assumes profit target is % uint public _stopLoss; //assumes stop loss is % address public _underlyingAsset; //state variables uint private _currentOrderSize; uint private _currentOrderEntryPrice; uint private _currentTradeDuration; address private _oracleAddress; address private _strategyAddress; constructor(uint[] memory entryRules, uint[] memory exitRules, uint maxTradeDuration, uint profitTarget, uint stopLoss, uint underlyingAssetID, IAddressResolver addressResolver) public onlyStrategy { ADDRESS_RESOLVER = addressResolver; _underlyingAsset = ISettings(addressResolver.getContractAddress("Settings")).getCurrencyKeyFromIndex(underlyingAssetID); _maxTradeDuration = maxTradeDuration; _profitTarget = profitTarget; _stopLoss = stopLoss; _strategyAddress = msg.sender; _generateRules(entryRules, exitRules); } /* ========== VIEWS ========== */ /** * @dev Returns the index of each pool the user manages * @return (Rule[], Rule[], uint, uint, uint, address) The trading bot's entry rules, exit rules, max trade duration, profit target, stop loss, and underlying asset address */ function getTradingBotParameters() public view override returns (Rule[] memory, Rule[] memory, uint, uint, uint, address) { return (_entryRules, _exitRules, _maxTradeDuration, _profitTarget, _stopLoss, _underlyingAsset); } /** * @dev Returns the address of the strategy associated with this bot * @return address The address of the strategy this bot belongs to */ function getStrategyAddress() public view override onlyTradingBotRewards returns (address) { return _strategyAddress; } /** * @dev Returns whether the bot is in a trade * @return bool Whether the bot is currently in a trade */ function checkIfBotIsInATrade() public view override returns (bool) { return (_currentOrderSize == 0); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Given the latest price from the bot's underlying asset, updates entry/exit rules and makes a trade depending on entry/exit rules * @param latestPrice Latest price from the underlying asset's oracle price feed */ function onPriceFeedUpdate(uint latestPrice) public override onlyOracle { _updateRules(latestPrice); //check if bot is not in a trade if (_currentOrderSize == 0) { if (_checkEntryRules()) { (_currentOrderSize, _currentOrderEntryPrice) = _placeOrder(true); } } else { if (_checkProfitTarget(latestPrice) || _checkStopLoss(latestPrice) || _currentTradeDuration >= _maxTradeDuration) { address tradingBotRewardsAddress = ADDRESS_RESOLVER.getContractAddress("TradingBotRewards"); (, uint exitPrice) = _placeOrder(false); (bool profitOrLoss, uint amount) = _calculateProfitOrLoss(exitPrice); _currentOrderEntryPrice = 0; _currentOrderSize = 0; _currentTradeDuration = 0; ITradingBotRewards(tradingBotRewardsAddress).updateRewards(profitOrLoss, amount, IStrategyToken(_strategyAddress).getCirculatingSupply()); } else { _currentTradeDuration = _currentTradeDuration.add(1); } } } /** * @dev Transfers the user's stake in bot's underlying asset when user withdraws from strategy * @param user Address of user to transfer funds to * @param amount Amount of funds to transfer */ function withdraw(address user, uint amount) public override onlyOwner { require(user != address(0), "Invalid user address"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_underlyingAsset); uint numberOfTokens = amount.div(tokenToUSD); IERC20(_underlyingAsset).approve(user, numberOfTokens); IERC20(_underlyingAsset).transferFrom(address(this), user, numberOfTokens); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Places an order to buy/sell the bot's underling asset * @param buyOrSell Whether the order represents buying or selling * @return (uint, uint) Number of tokens received and the price executed */ function _placeOrder(bool buyOrSell) private returns (uint, uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); uint stableCoinBalance = IERC20(stableCoinAddress).balanceOf(address(this)); uint tokenBalance = IERC20(_underlyingAsset).balanceOf(address(this)); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_underlyingAsset); uint numberOfTokens = buyOrSell ? stableCoinBalance : tokenBalance; uint amountInUSD = buyOrSell ? numberOfTokens.div(tokenToUSD) : numberOfTokens.mul(tokenToUSD); uint minAmountOut = buyOrSell ? numberOfTokens.mul(98).div(100) : amountInUSD.mul(98).div(100); //max slippage 2% uint numberOfTokensReceived; //buying if (buyOrSell) { numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromBot(stableCoinAddress, _underlyingAsset, amountInUSD, minAmountOut); } //selling else { numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromBot(_underlyingAsset, stableCoinAddress, numberOfTokens, minAmountOut); } emit PlacedOrder(address(this), block.timestamp, _underlyingAsset, 0, 0, buyOrSell); return (numberOfTokensReceived, tokenToUSD); } /** * @dev Given the exit price of the bot's most recent trade, return the profit/loss for the trade * @param exitPrice Price of the bot's underlying asset when exiting the trade * @return (bool, uint) Whether the trade is profit/loss, and the amount of profit/loss */ function _calculateProfitOrLoss(uint exitPrice) private view returns (bool, uint) { return (exitPrice >= _currentOrderEntryPrice) ? (true, exitPrice.sub(_currentOrderEntryPrice).div(_currentOrderEntryPrice)) : (false, _currentOrderEntryPrice.sub(exitPrice).div(_currentOrderEntryPrice)); } /** * @dev Updates the entry/exit rules of the bot based on the underlying asset's latest price * @param latestPrice Latest price of the bot's underlying asset */ function _updateRules(uint latestPrice) private { //Bounded by maximum number of entry rules (from Settings contract) for (uint i = 0; i < _entryRules.length; i++) { IIndicator(_entryRules[i].firstIndicatorAddress).update(_entryRules[i].firstIndicatorIndex, latestPrice); IIndicator(_entryRules[i].secondIndicatorAddress).update(_entryRules[i].secondIndicatorIndex, latestPrice); } for (uint i = 0; i < _exitRules.length; i++) { IIndicator(_exitRules[i].firstIndicatorAddress).update(_exitRules[i].firstIndicatorIndex, latestPrice); IIndicator(_exitRules[i].secondIndicatorAddress).update(_exitRules[i].secondIndicatorIndex, latestPrice); } } /** * @dev Checks whether all entry rules are met * @return bool Whether each entry rule is met */ function _checkEntryRules() private returns (bool) { for (uint i = 0; i < _entryRules.length; i++) { if (!IComparator(_entryRules[i].comparatorAddress).checkConditions(_entryRules[i].comparatorIndex, _entryRules[i].firstIndicatorIndex, _entryRules[i].secondIndicatorIndex)) { return false; } } return true; } /** * @dev Checks whether at least one exit rule is met * @return bool Whether at least one exit rule is met */ function _checkExitRules() private returns (bool) { for (uint i = 0; i < _exitRules.length; i++) { if (!IComparator(_exitRules[i].comparatorAddress).checkConditions(_exitRules[i].comparatorIndex, _exitRules[i].firstIndicatorIndex, _exitRules[i].secondIndicatorIndex)) { return true; } } return false; } /** * @dev Given the latest price of the bot's underlying asset, returns whether the profit target is met * @param latestPrice Latest price of the bot's underlying asset * @return bool Whether the profit target is met */ function _checkProfitTarget(uint latestPrice) private view returns (bool) { return (latestPrice > _currentOrderEntryPrice.mul(1 + _profitTarget.div(100))); } /** * @dev Given the latest price of the bot's underlying asset, returns whether the stop loss is met * @param latestPrice Latest price of the bot's underlying asset * @return bool Whether the stop loss is met */ function _checkStopLoss(uint latestPrice) private view returns (bool) { return (latestPrice < _currentOrderEntryPrice.mul(1 - _stopLoss.div(100))); } /** * @dev Generates entry/exit rules based on the parameters of each entry/exit rule * @param entryRules Parameters of each entry rule * @param exitRules Parameters of each exit rule */ function _generateRules(uint[] memory entryRules, uint[] memory exitRules) internal { for (uint i = 0; i < entryRules.length; i++) { _entryRules.push(_generateRule(entryRules[i])); } for (uint i = 0; i < exitRules.length; i++) { _exitRules.push(_generateRule(exitRules[i])); } } /** * @dev Generates a Rule based on the given parameters * @notice bits 0-124: empty bit 125: whether the comparator is default bits 126-141: comparator type bit 142: whether the first indicator is default bits 143-158: first indicator type bit 159: whether the second indicator is default bits 160-175: second indicator type bits 176-215: first indicator parameter bits 216-255: second indicator parameter * @param rule Parameters of the rule * @return Rule The indicators and comparators generated from the rule's parameters */ function _generateRule(uint rule) private returns (Rule memory) { bool comparatorIsDefault = ((rule << 125) >> 255) == 1; uint comparator = (rule << 126) >> 240; bool firstIndicatorIsDefault = ((rule << 142) >> 255) == 1; uint firstIndicator = (rule << 143) >> 240; bool secondIndicatorIsDefault = ((rule << 159) >> 255) == 1; uint secondIndicator = (rule << 160) >> 240; uint firstIndicatorParam = (rule << 176) >> 216; uint secondIndicatorParam = (rule << 216) >> 216; (address firstIndicatorAddress, uint firstIndicatorIndex) = _addBotToIndicator(firstIndicatorIsDefault, firstIndicator, firstIndicatorParam); (address secondIndicatorAddress, uint secondIndicatorIndex) = _addBotToIndicator(secondIndicatorIsDefault, secondIndicator, secondIndicatorParam); (address comparatorAddress, uint comparatorIndex) = _addBotToComparator(comparatorIsDefault, comparator, firstIndicatorAddress, secondIndicatorAddress); require(firstIndicatorAddress != address(0) && secondIndicatorAddress != address(0) && comparatorAddress != address(0), "Invalid address when generating rule"); return Rule(firstIndicatorAddress, secondIndicatorAddress, comparatorAddress, uint8(firstIndicatorIndex), uint8(secondIndicatorIndex), uint8(comparatorIndex)); } /** * @dev Adds trading bot to the indicator * @param isDefault Whether indicator is a default indicator * @param indicatorIndex Index of indicator in array of available indicators * @param indicatorParam Parameter for the indicator * @return address Address of the indicator */ function _addBotToIndicator(bool isDefault, uint indicatorIndex, uint indicatorParam) private returns (address, uint) { address componentsAddress = ADDRESS_RESOLVER.getContractAddress("Components"); address indicatorAddress = IComponents(componentsAddress).getIndicatorFromIndex(isDefault, indicatorIndex); uint index = IIndicator(indicatorAddress).addTradingBot(indicatorParam); return (indicatorAddress, index); } /** * @dev Adds trading bot to the comparator * @param isDefault Whether comparator is a default comparator * @param comparatorIndex Index of comparator in array of available comparators * @param firstIndicatorAddress Address of the first indicator * @param secondIndicatorAddress Address of the second indicator * @return address Address of the comparator */ function _addBotToComparator(bool isDefault, uint comparatorIndex, address firstIndicatorAddress, address secondIndicatorAddress) private returns (address, uint) { require(firstIndicatorAddress != address(0), "Invalid first indicator address"); require(secondIndicatorAddress != address(0), "Invalid second indicator address"); address componentsAddress = ADDRESS_RESOLVER.getContractAddress("Components"); address comparatorAddress = IComponents(componentsAddress).getComparatorFromIndex(isDefault, comparatorIndex); uint index = IComparator(comparatorAddress).addTradingBot(firstIndicatorAddress, secondIndicatorAddress); return (comparatorAddress, index); } /* ========== MODIFIERS ========== */ modifier onlyOracle() { require(msg.sender == _oracleAddress, "Only the oracle can call this function"); _; } modifier onlyOwner() { require(msg.sender == _strategyAddress, "Only the strategy can call this function"); _; } modifier onlyTradingBotRewards() { require(msg.sender == ADDRESS_RESOLVER.getContractAddress("TradingBotRewards"), "Only the TradingBotRewards contract can call this function"); _; } modifier onlyStrategy() { require(ADDRESS_RESOLVER.checkIfStrategyAddressIsValid(msg.sender), "Only the Strategy contract can call this function"); _; } /* ========== EVENTS ========== */ event PlacedOrder(address tradingBotAddress, uint256 timestamp, address underlyingAsset, uint size, uint price, bool orderType); }
* @dev Adds trading bot to the comparator @param isDefault Whether comparator is a default comparator @param comparatorIndex Index of comparator in array of available comparators @param firstIndicatorAddress Address of the first indicator @param secondIndicatorAddress Address of the second indicator @return address Address of the comparator/
function _addBotToComparator(bool isDefault, uint comparatorIndex, address firstIndicatorAddress, address secondIndicatorAddress) private returns (address, uint) { require(firstIndicatorAddress != address(0), "Invalid first indicator address"); require(secondIndicatorAddress != address(0), "Invalid second indicator address"); address componentsAddress = ADDRESS_RESOLVER.getContractAddress("Components"); address comparatorAddress = IComponents(componentsAddress).getComparatorFromIndex(isDefault, comparatorIndex); uint index = IComparator(comparatorAddress).addTradingBot(firstIndicatorAddress, secondIndicatorAddress); return (comparatorAddress, index); }
1,807,611
[ 1, 3655, 1284, 7459, 2512, 358, 326, 8862, 225, 20652, 17403, 8862, 353, 279, 805, 8862, 225, 8862, 1016, 3340, 434, 8862, 316, 526, 434, 2319, 8862, 87, 225, 1122, 13140, 1887, 5267, 434, 326, 1122, 10664, 225, 2205, 13140, 1887, 5267, 434, 326, 2205, 10664, 327, 1758, 5267, 434, 326, 8862, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 6522, 774, 5559, 12, 6430, 20652, 16, 2254, 8862, 1016, 16, 1758, 1122, 13140, 1887, 16, 1758, 2205, 13140, 1887, 13, 3238, 1135, 261, 2867, 16, 2254, 13, 288, 203, 3639, 2583, 12, 3645, 13140, 1887, 480, 1758, 12, 20, 3631, 315, 1941, 1122, 10664, 1758, 8863, 203, 3639, 2583, 12, 8538, 13140, 1887, 480, 1758, 12, 20, 3631, 315, 1941, 2205, 10664, 1758, 8863, 203, 203, 3639, 1758, 4085, 1887, 273, 11689, 10203, 67, 17978, 2204, 18, 588, 8924, 1887, 2932, 7171, 8863, 203, 3639, 1758, 8862, 1887, 273, 467, 7171, 12, 8119, 1887, 2934, 588, 5559, 1265, 1016, 12, 291, 1868, 16, 8862, 1016, 1769, 203, 203, 3639, 2254, 770, 273, 467, 5559, 12, 832, 2528, 1887, 2934, 1289, 1609, 7459, 6522, 12, 3645, 13140, 1887, 16, 2205, 13140, 1887, 1769, 203, 203, 3639, 327, 261, 832, 2528, 1887, 16, 770, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x0328a867c3aFD0792F8b849A71F6a0c98e3E5901/sources/contracts/SigmoidBank.sol
recognise new stable stable coin
function addStablecoinToList(address contract_address) public override returns (bool) { require(msg.sender == governance_contract); require(checkIntheList(contract_address) == false); USD_token_list.push(contract_address); if(IUniswapV2Factory(SwapFactoryAddress).getPair(contract_address,token_contract[0])==address(0)){ IUniswapV2Factory(SwapFactoryAddress).createPair(contract_address,token_contract[0]); } return(true); }
8,191,828
[ 1, 3927, 4198, 784, 394, 14114, 14114, 13170, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 30915, 12645, 25772, 12, 2867, 6835, 67, 2867, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 314, 1643, 82, 1359, 67, 16351, 1769, 203, 3639, 2583, 12, 1893, 382, 5787, 682, 12, 16351, 67, 2867, 13, 422, 629, 1769, 203, 3639, 587, 9903, 67, 2316, 67, 1098, 18, 6206, 12, 16351, 67, 2867, 1769, 203, 3639, 309, 12, 45, 984, 291, 91, 438, 58, 22, 1733, 12, 12521, 1733, 1887, 2934, 588, 4154, 12, 16351, 67, 2867, 16, 2316, 67, 16351, 63, 20, 5717, 631, 2867, 12, 20, 3719, 95, 21281, 5411, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 12521, 1733, 1887, 2934, 2640, 4154, 12, 16351, 67, 2867, 16, 2316, 67, 16351, 63, 20, 19226, 203, 3639, 289, 203, 540, 203, 3639, 327, 12, 3767, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; address public ICOAddress; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the ico. */ modifier onlyICO() { require(msg.sender == ICOAddress); _; } modifier onlyOwnerOrICO() { require(msg.sender == ICOAddress || msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function setICOAddress(address _icoAddress) public onlyOwner { require(_icoAddress != address(0)); ICOAddress = _icoAddress; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = true; /** * @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() onlyOwnerOrICO whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); 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); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, Pausable{ using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { return _transfer(_to, _value); } function ownerTransfer(address _to, uint256 _value) onlyOwnerOrICO public returns (bool) { return _transfer(_to, _value); } function _transfer(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @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) whenNotPaused public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenNotPaused public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) whenNotPaused public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) whenNotPaused public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) whenNotPaused public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract OPKToken is StandardToken { address public teamAddress; address public advisorsAddress; address public reserveAddress; string public constant name = "OPK"; // solium-disable-line uppercase string public constant symbol = "OPK"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 50000000 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } }
* @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: @param _spender The address which will spend the funds. @param _value The amount of tokens to be spent./
function approve(address _spender, uint256 _value) whenNotPaused public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
47,933
[ 1, 12053, 537, 326, 2275, 1758, 358, 17571, 326, 1269, 3844, 434, 2430, 603, 12433, 6186, 434, 1234, 18, 15330, 18, 605, 359, 834, 716, 12770, 392, 1699, 1359, 598, 333, 707, 5186, 899, 326, 18404, 716, 18626, 2026, 999, 3937, 326, 1592, 471, 326, 394, 1699, 1359, 635, 640, 22618, 340, 2492, 9543, 18, 6942, 3323, 6959, 358, 20310, 360, 340, 333, 17996, 2269, 353, 358, 1122, 5459, 326, 17571, 264, 1807, 1699, 1359, 358, 374, 471, 444, 326, 6049, 460, 23838, 30, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1132, 1021, 3844, 434, 2430, 358, 506, 26515, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1347, 1248, 28590, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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); }
solhint-disable-next-line payable-fallback,no-complex-fallback solhint-disable-next-line no-inline-assembly
fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { let handler := sload(slot) if iszero(handler) { return(0, 0) } calldatacopy(0, 0, calldatasize()) returndatacopy(0, 0, returndatasize()) if iszero(success) { revert(0, returndatasize()) } return(0, returndatasize()) } }
431,280
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 8843, 429, 17, 16471, 16, 2135, 17, 14259, 17, 16471, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 5922, 1435, 3903, 288, 203, 3639, 1731, 1578, 4694, 273, 478, 4685, 8720, 67, 19937, 67, 19009, 67, 55, 1502, 56, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 1838, 519, 272, 945, 12, 14194, 13, 203, 5411, 309, 353, 7124, 12, 4176, 13, 288, 203, 7734, 327, 12, 20, 16, 374, 13, 203, 5411, 289, 203, 5411, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 5411, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 5411, 309, 353, 7124, 12, 4768, 13, 288, 203, 7734, 15226, 12, 20, 16, 327, 13178, 554, 10756, 203, 5411, 289, 203, 5411, 327, 12, 20, 16, 327, 13178, 554, 10756, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xA7A4541132a542E3eBa320FFEDDA8c4B27a65c05/sources/hallowinu.sol
* @dev 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/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HALLOW::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
4,626,814
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 44, 13511, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2, -100, -100 ]
./partial_match/1313161554/0x9C3AFDDEa87a726891A44C037242393D524CAcFE/sources/contracts/DonaswapV3Factory.sol
@title Canonical Donaswa V3 factory @notice Deploys Donaswap V3 pools and manages ownership and control over pool protocol fees
contract DonaswapV3Factory is IDonaswapV3Factory { address public override owner; address public immutable poolDeployer; mapping(uint24 => int24) public override feeAmountTickSpacing; mapping(address => mapping(address => mapping(uint24 => address))) public override getPool; mapping(uint24 => TickSpacingExtraInfo) public override feeAmountTickSpacingExtraInfo; mapping(address => bool) private _whiteListAddresses; address public lmPoolDeployer; pragma solidity =0.7.6; modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } modifier onlyOwnerOrLmPoolDeployer() { require(msg.sender == owner || msg.sender == lmPoolDeployer, "Not owner or LM pool deployer"); _; } constructor(address _poolDeployer) { poolDeployer = _poolDeployer; owner = msg.sender; emit OwnerChanged(address(0), msg.sender); feeAmountTickSpacing[100] = 1; emit FeeAmountEnabled(100, 1); emit FeeAmountExtraInfoUpdated(100, false, true); feeAmountTickSpacing[500] = 10; emit FeeAmountEnabled(500, 10); emit FeeAmountExtraInfoUpdated(500, false, true); feeAmountTickSpacing[2500] = 50; emit FeeAmountEnabled(2500, 50); emit FeeAmountExtraInfoUpdated(2500, false, true); feeAmountTickSpacing[10000] = 200; emit FeeAmountEnabled(10000, 200); emit FeeAmountExtraInfoUpdated(10000, false, true); } feeAmountTickSpacingExtraInfo[100] = TickSpacingExtraInfo({whitelistRequested: false, enabled: true}); feeAmountTickSpacingExtraInfo[500] = TickSpacingExtraInfo({whitelistRequested: false, enabled: true}); feeAmountTickSpacingExtraInfo[2500] = TickSpacingExtraInfo({whitelistRequested: false, enabled: true}); feeAmountTickSpacingExtraInfo[10000] = TickSpacingExtraInfo({whitelistRequested: false, enabled: true}); function createPool( address tokenA, address tokenB, uint24 fee ) external override returns (address pool) { require(tokenA != tokenB); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0)); int24 tickSpacing = feeAmountTickSpacing[fee]; TickSpacingExtraInfo memory info = feeAmountTickSpacingExtraInfo[fee]; require(tickSpacing != 0 && info.enabled, "fee is not available yet"); if (info.whitelistRequested) { require(_whiteListAddresses[msg.sender], "user should be in the white list for this fee tier"); } require(getPool[token0][token1][fee] == address(0)); pool = IDonaswapV3PoolDeployer(poolDeployer).deploy(address(this), token0, token1, fee, tickSpacing); getPool[token0][token1][fee] = pool; emit PoolCreated(token0, token1, fee, tickSpacing, pool); } function createPool( address tokenA, address tokenB, uint24 fee ) external override returns (address pool) { require(tokenA != tokenB); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0)); int24 tickSpacing = feeAmountTickSpacing[fee]; TickSpacingExtraInfo memory info = feeAmountTickSpacingExtraInfo[fee]; require(tickSpacing != 0 && info.enabled, "fee is not available yet"); if (info.whitelistRequested) { require(_whiteListAddresses[msg.sender], "user should be in the white list for this fee tier"); } require(getPool[token0][token1][fee] == address(0)); pool = IDonaswapV3PoolDeployer(poolDeployer).deploy(address(this), token0, token1, fee, tickSpacing); getPool[token0][token1][fee] = pool; emit PoolCreated(token0, token1, fee, tickSpacing, pool); } getPool[token1][token0][fee] = pool; function setOwner(address _owner) external override onlyOwner { emit OwnerChanged(owner, _owner); owner = _owner; } function enableFeeAmount(uint24 fee, int24 tickSpacing) public override onlyOwner { require(fee < 1000000); require(tickSpacing > 0 && tickSpacing < 16384); require(feeAmountTickSpacing[fee] == 0); feeAmountTickSpacing[fee] = tickSpacing; emit FeeAmountEnabled(fee, tickSpacing); emit FeeAmountExtraInfoUpdated(fee, false, true); } feeAmountTickSpacingExtraInfo[fee] = TickSpacingExtraInfo({whitelistRequested: false, enabled: true}); function setWhiteListAddress(address user, bool verified) public override onlyOwner { require(_whiteListAddresses[user] != verified, "state not change"); _whiteListAddresses[user] = verified; emit WhiteListAdded(user, verified); } function setFeeAmountExtraInfo( uint24 fee, bool whitelistRequested, bool enabled ) public override onlyOwner { require(feeAmountTickSpacing[fee] != 0); feeAmountTickSpacingExtraInfo[fee] = TickSpacingExtraInfo({ whitelistRequested: whitelistRequested, enabled: enabled }); emit FeeAmountExtraInfoUpdated(fee, whitelistRequested, enabled); } function setFeeAmountExtraInfo( uint24 fee, bool whitelistRequested, bool enabled ) public override onlyOwner { require(feeAmountTickSpacing[fee] != 0); feeAmountTickSpacingExtraInfo[fee] = TickSpacingExtraInfo({ whitelistRequested: whitelistRequested, enabled: enabled }); emit FeeAmountExtraInfoUpdated(fee, whitelistRequested, enabled); } function setLmPoolDeployer(address _lmPoolDeployer) external override onlyOwner { lmPoolDeployer = _lmPoolDeployer; emit SetLmPoolDeployer(_lmPoolDeployer); } function setFeeProtocol(address pool, uint32 feeProtocol0, uint32 feeProtocol1) external override onlyOwner { IDonaswapV3Pool(pool).setFeeProtocol(feeProtocol0, feeProtocol1); } function collectProtocol( address pool, address recipient, uint128 amount0Requested, uint128 amount1Requested ) external override onlyOwner returns (uint128 amount0, uint128 amount1) { return IDonaswapV3Pool(pool).collectProtocol(recipient, amount0Requested, amount1Requested); } function setLmPool(address pool, address lmPool) external override onlyOwnerOrLmPoolDeployer { IDonaswapV3Pool(pool).setLmPool(lmPool); } }
16,934,626
[ 1, 15512, 7615, 345, 91, 69, 776, 23, 3272, 225, 4019, 383, 1900, 7615, 345, 91, 438, 776, 23, 16000, 471, 20754, 281, 23178, 471, 3325, 1879, 2845, 1771, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7615, 345, 91, 438, 58, 23, 1733, 353, 1599, 265, 345, 91, 438, 58, 23, 1733, 288, 203, 565, 1758, 1071, 3849, 3410, 31, 203, 203, 565, 1758, 1071, 11732, 2845, 10015, 264, 31, 203, 203, 565, 2874, 12, 11890, 3247, 516, 509, 3247, 13, 1071, 3849, 14036, 6275, 6264, 18006, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2874, 12, 11890, 3247, 516, 1758, 20349, 1071, 3849, 28575, 31, 203, 565, 2874, 12, 11890, 3247, 516, 13588, 18006, 7800, 966, 13, 1071, 3849, 14036, 6275, 6264, 18006, 7800, 966, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 14739, 682, 7148, 31, 203, 203, 565, 1758, 1071, 14966, 2864, 10015, 264, 31, 203, 203, 683, 9454, 18035, 560, 273, 20, 18, 27, 18, 26, 31, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 1248, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1162, 48, 81, 2864, 10015, 264, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 747, 1234, 18, 15330, 422, 14966, 2864, 10015, 264, 16, 315, 1248, 3410, 578, 511, 49, 2845, 7286, 264, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 12, 2867, 389, 6011, 10015, 264, 13, 288, 203, 3639, 2845, 10015, 264, 273, 389, 6011, 10015, 264, 31, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 16837, 5033, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 2 ]
./partial_match/1/0xafCc79d4cbe7E5B6E6997BBE7233e8E9179f664a/sources/ProfitSharing.sol
Check for overflow
if (previousBalanceTo + _amount < previousBalanceTo) throw;
2,607,292
[ 1, 1564, 364, 9391, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 11515, 13937, 774, 397, 389, 8949, 411, 2416, 13937, 774, 13, 604, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/73799/0x4545C3dAbc5b6D1c19A52006C2eaF598a599dE2A/sources/contracts/trove.sol
* @dev is called to redeem StableCoin for token, called by factory when MCR > ICR, amount of StableCoin is taken from balance and must be <= netDebt. uses priceFeed to calculate collateral amount. returns amount of StableCoin used and collateral recieved @param _recipient the address which recieves redeemed token @param _newNextTrove hint for next trove after reorder, if it's not full redemption/ console.log('before repay', _collateralRecieved, _stableAmount, netDebt()); console.log('after repay',_collateralRecieved, _stableAmount, netDebt());
function redeem(address _recipient, address _newNextTrove) public onlyFactory returns (uint256 _stableAmount, uint256 _collateralRecieved) { getLiquidationRewards(); require(mcr() < collateralization(), "e957f TCR must be gt MCR"); ITroveFactory factory_cache = factory; _stableAmount = factory_cache.stableCoin().balanceOf(address(this)) - liquidationReserve; require( _newNextTrove == address(0) ? _stableAmount == netDebt() : _stableAmount <= netDebt(), "e957f amount != debt and no hint" ); IERC20 token_cache = token; uint256 collateralToTransfer = (_stableAmount * DECIMAL_PRECISION) / factory_cache.tokenToPriceFeed().tokenPrice(address(token_cache)); token_cache.transfer(_recipient, collateralToTransfer); _collateralRecieved = collateralToTransfer; return (_stableAmount, _collateralRecieved); }
16,363,682
[ 1, 291, 2566, 358, 283, 24903, 934, 429, 27055, 364, 1147, 16, 2566, 635, 3272, 1347, 490, 5093, 405, 467, 5093, 16, 3844, 434, 934, 429, 27055, 353, 9830, 628, 11013, 471, 1297, 506, 1648, 2901, 758, 23602, 18, 4692, 6205, 8141, 358, 4604, 4508, 2045, 287, 3844, 18, 1135, 3844, 434, 934, 429, 27055, 1399, 471, 4508, 2045, 287, 1950, 1385, 2155, 225, 389, 20367, 326, 1758, 1492, 1950, 1385, 3324, 283, 24903, 329, 1147, 225, 389, 2704, 2134, 56, 303, 537, 7380, 364, 1024, 23432, 537, 1839, 19427, 16, 309, 518, 1807, 486, 1983, 283, 19117, 375, 19, 2983, 18, 1330, 2668, 5771, 2071, 528, 2187, 389, 12910, 2045, 287, 5650, 1385, 2155, 16, 389, 15021, 6275, 16, 2901, 758, 23602, 10663, 2983, 18, 1330, 2668, 5205, 2071, 528, 2187, 67, 12910, 2045, 287, 5650, 1385, 2155, 16, 389, 15021, 6275, 16, 2901, 758, 23602, 10663, 2, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 225, 445, 283, 24903, 12, 2867, 389, 20367, 16, 1758, 389, 2704, 2134, 56, 303, 537, 13, 203, 565, 1071, 203, 565, 1338, 1733, 203, 565, 1135, 261, 11890, 5034, 389, 15021, 6275, 16, 2254, 5034, 389, 12910, 2045, 287, 5650, 1385, 2155, 13, 203, 225, 288, 203, 565, 9014, 18988, 350, 367, 17631, 14727, 5621, 203, 565, 2583, 12, 81, 3353, 1435, 411, 4508, 2045, 287, 1588, 9334, 315, 73, 8778, 27, 74, 399, 5093, 1297, 506, 9879, 490, 5093, 8863, 203, 565, 24142, 303, 537, 1733, 3272, 67, 2493, 273, 3272, 31, 203, 565, 389, 15021, 6275, 273, 3272, 67, 2493, 18, 15021, 27055, 7675, 12296, 951, 12, 2867, 12, 2211, 3719, 300, 4501, 26595, 367, 607, 6527, 31, 203, 565, 2583, 12, 203, 1377, 389, 2704, 2134, 56, 303, 537, 422, 1758, 12, 20, 13, 692, 389, 15021, 6275, 422, 2901, 758, 23602, 1435, 294, 389, 15021, 6275, 1648, 2901, 758, 23602, 9334, 203, 1377, 315, 73, 8778, 27, 74, 3844, 480, 18202, 88, 471, 1158, 7380, 6, 203, 565, 11272, 203, 203, 565, 467, 654, 39, 3462, 1147, 67, 2493, 273, 1147, 31, 203, 203, 565, 2254, 5034, 4508, 2045, 287, 774, 5912, 273, 261, 67, 15021, 6275, 380, 25429, 67, 3670, 26913, 13, 342, 203, 1377, 3272, 67, 2493, 18, 2316, 774, 5147, 8141, 7675, 2316, 5147, 12, 2867, 12, 2316, 67, 2493, 10019, 203, 565, 1147, 67, 2493, 18, 13866, 24899, 20367, 16, 4508, 2045, 287, 774, 5912, 1769, 203, 565, 389, 12910, 2045, 287, 5650, 1385, 2155, 2 ]
pragma solidity ^0.4.18; import './deps/MintableToken.sol'; import './deps/ERC20Interface.sol'; import './deps/Ownable.sol'; import './deps/ApproveAndCallFallBack.sol'; contract Fr8NetworkToken is ERC20Interface, Ownable { using SafeMath for uint; // standard ERC20 stuff string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bool public mintable; // contract version uint public version; mapping(address => uint) internal balances; mapping(address => mapping(address => uint)) internal allowed; event MintingDisabled(); function Fr8NetworkToken() public { version = 10; // initial erc20 settings symbol = "FR8"; name = "Fr8 Network Test Token"; decimals = 18; mintable = true; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function disableMinting() public onlyOwner { require(mintable); mintable = false; MintingDisabled(); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } /** * Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account * * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md * recommends that there are no checks for the approval double-spend attack * as this should be implemented in user interfaces */ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } /** * Transfer `tokens` from the `from` account to the `to` account * * The calling account must already have sufficient tokens approve(...)-d * for spending from the `from` account and * - From account must have sufficient balance to transfer * - Spender must have sufficient allowance to transfer * - 0 value transfers are allowed */ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } /** * Returns the amount of tokens approved by the owner that can be * transferred to the spender's account */ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account. The `spender` contract function * `receiveApproval(...)` is then executed */ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } /** * Mint tokens */ function mint(address tokenOwner, uint tokens) public onlyOwner returns (bool success) { require(mintable); balances[tokenOwner] = balances[tokenOwner].add(tokens); _totalSupply = _totalSupply.add(tokens); Transfer(address(0), tokenOwner, tokens); return true; } /** * [Deprecated] Owner can transfer out any accidentally sent ERC20 tokens * Ensure cannot send self token */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
initial erc20 settings
function Fr8NetworkToken() public { version = 10; symbol = "FR8"; name = "Fr8 Network Test Token"; decimals = 18; mintable = true; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); }
13,017,470
[ 1, 6769, 6445, 71, 3462, 1947, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 13363, 28, 3906, 1345, 1435, 1071, 288, 203, 565, 1177, 273, 1728, 31, 203, 203, 565, 3273, 273, 315, 9981, 28, 14432, 203, 565, 508, 273, 315, 7167, 28, 5128, 7766, 3155, 14432, 203, 565, 15105, 273, 6549, 31, 203, 565, 312, 474, 429, 273, 638, 31, 203, 203, 565, 389, 4963, 3088, 1283, 273, 15088, 3784, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 203, 565, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 565, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.6; import "../ContractManager.sol"; import "../storage/OrderStorage.sol"; import "../storage/UserStorage.sol"; import "./VatLogic.sol"; import "./ProductLogic.sol"; contract OrderLogic { ContractManager internal contractManager; OrderStorage internal orderStorage; VatLogic internal vatLogic; UserStorage internal userStorage; ProductLogic internal productLogic; event PurchaseOrderInserted(address indexed _buyer, bytes32 indexed _keyHash, bytes32 indexed _vatKey); event SellOrderInserted(address indexed _seller, bytes32 indexed _keyHash, bytes32 indexed _vatKey); modifier onlyBuyerOrSeller(bytes32 _keyHash, address _user) { require(_user == orderStorage.getBuyer(_keyHash) || _user == orderStorage.getSeller(_keyHash), "Cannot access the specified order, you are not the buyer or seller" ); _; } modifier onlyPurchaseContract { require(msg.sender == contractManager.getContractAddress("Purchase"), "No permission"); _; } modifier onlyValidIpfsCid(bytes32 _hashIpfs, uint8 _hashFun, uint8 _hashSize) { require(_hashIpfs[0] != 0 && _hashFun > 0 && _hashSize > 0, "Invalid Ipfs key"); _; } constructor(address _contractManagerAddress) public { contractManager = ContractManager(_contractManagerAddress); orderStorage = OrderStorage(contractManager.getContractAddress("OrderStorage")); vatLogic = VatLogic(contractManager.getContractAddress("VatLogic")); userStorage = UserStorage(contractManager.getContractAddress("UserStorage")); productLogic = ProductLogic(contractManager.getContractAddress("ProductLogic")); } function registerOrder( bytes32 _hashIpfs, uint8 _hashFun, uint8 _hashSize, address _buyer, string calldata _period, bytes32[] calldata _productsHash, uint8[] calldata _productsQtn ) external //onlyPurchaseContract { setVatLogic(); setProductLogic(); address _seller = productLogic.getProductSeller(_productsHash[0]); require(_productsHash.length > 0, "OrderLogic: products not provided"); require(_seller != address(0), "OrderLogic: invalid seller address"); require(_buyer != address(0), "OrderLogic: invalid buyer address"); require(_buyer != _seller, "OrderLogic: cannot buy from yourself"); // calculate the netTotal and the VAT Total (uint256 total, uint256 vatTotal) = calculateOrderTotal(_productsHash, _productsQtn); //register the order orderStorage.addOrder(_hashIpfs, _hashFun, _hashSize, _buyer, _seller, _productsHash, total, vatTotal); // Create instance of Vat Logic // if the buyer is a business, the vat movement needs to be registered // to do so a UserStorage instance is created and if and only if the buyer // is a business, the vat movement is registere if (userStorage.getUserType(_buyer) == 2) { vatLogic.registerVat(_buyer, (int256(vatTotal)*(-1)), _period); emit PurchaseOrderInserted(_buyer, _hashIpfs, vatLogic.createVatKey(_buyer, _period)); } else { emit PurchaseOrderInserted(_buyer, _hashIpfs, bytes32("0")); } vatLogic.registerVat(_seller, (int256(vatTotal)), _period); // Using these events it's possible to see the orders history, both purchase and sell //emit the event on the blockchain: the event shows the buyer and the hash of the order //emit the event on the blockchain: the event shows the seller and the hash of the order emit SellOrderInserted(_seller, _hashIpfs, vatLogic.createVatKey(_seller, _period)); } function getOrderSeller(bytes32 _keyHash) public view returns(address) { return orderStorage.getSeller(_keyHash); } function getOrderTotal(bytes32 _keyHash) public view returns(uint) { return (orderStorage.getOrderNetTotal(_keyHash) + orderStorage.getOrderVatTotal(_keyHash)); } function calculateOrderTotal(bytes32[] memory _productsHash, uint8[] memory _prodQtn) public returns(uint256, uint256) { require(_productsHash.length > 0, "Empty array"); setProductLogic(); uint256 total = 0; address seller = productLogic.getProductSeller(_productsHash[0]); uint256 vatTotal = 0; for (uint i = 0; i < _productsHash.length; ++i) { require(productLogic.getProductSeller(_productsHash[i]) == seller, "Invalid product, wrong seller"); total += ((productLogic.getProductNetPrice(_productsHash[i])) * (_prodQtn[i])); vatTotal += ((productLogic.calculateProductVat(_productsHash[i])) * (_prodQtn[i])); } return(total, vatTotal); } function setVatLogic() internal { vatLogic = VatLogic(contractManager.getContractAddress("VatLogic")); } function setProductLogic() internal { productLogic = ProductLogic(contractManager.getContractAddress("ProductLogic")); } function getOrderCid(bytes32 _keyHash) external view returns(bytes32, uint8, uint8) { return( orderStorage.getOrderCid(_keyHash) ); } }
emit the event on the blockchain: the event shows the seller and the hash of the order
emit SellOrderInserted(_seller, _hashIpfs, vatLogic.createVatKey(_seller, _period));
1,840,421
[ 1, 18356, 326, 871, 603, 326, 16766, 30, 326, 871, 17975, 326, 29804, 471, 326, 1651, 434, 326, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3626, 348, 1165, 2448, 27329, 24899, 1786, 749, 16, 389, 2816, 5273, 2556, 16, 17359, 20556, 18, 2640, 15706, 653, 24899, 1786, 749, 16, 389, 6908, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x00F3823D6bf45DF3c34354CbeC54F087479A6A11/sources/MerkleClaim.sol
@notice Emitted after a successful token claim @param to recipient of claim @param amount of tokens claimed
event Claim(address indexed to, uint256 amount);
4,157,210
[ 1, 1514, 11541, 1839, 279, 6873, 1147, 7516, 225, 358, 8027, 434, 7516, 225, 3844, 434, 2430, 7516, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 18381, 12, 2867, 8808, 358, 16, 2254, 5034, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xC4bfcAC43433C2435184c87aF26daDE9379b5B11/sources/project:/contracts/MtrollerCommon.sol
* @title Based on Compound's Mtroller Contract, with some modifications @dev This contract must not declare any variables. All required storage must be in MtrollerV1Storage @author Compound, mmo.finance/
contract MtrollerCommon is MtrollerV1Storage, MtrollerCommonInterface { constructor() public { } function getAdmin() public view returns (address payable admin) { bytes32 position = mDelegatorAdminPosition; assembly { admin := sload(position) } } function getAdmin() public view returns (address payable admin) { bytes32 position = mDelegatorAdminPosition; assembly { admin := sload(position) } } function underlyingContractETH() public pure returns (address) { return address(uint160(-1)); } function getAnchorToken(address mTokenContract) public pure returns (uint240) { return assembleToken(MTokenIdentifier(mTokenContract).getTokenType(), 0, mTokenContract); } function getAnchorToken(uint240 mToken) internal pure returns (uint240) { return (mToken & 0xff000000000000000000ffffffffffffffffffffffffffffffffffffffff); } function assembleToken(MTokenType mTokenType, uint72 mTokenSeqNr, address mTokenAddress) public pure returns (uint240 mToken) { bytes10 mTokenData = bytes10(uint80(mTokenSeqNr) + (uint80(mTokenType) << 72)); return (uint240(bytes30(mTokenData)) + uint240(uint160(mTokenAddress))); } function parseToken(uint240 mToken) public pure returns (MTokenType mTokenType, uint72 mTokenSeqNr, address mTokenAddress) { mTokenAddress = address(uint160(mToken)); bytes10 mTokenData = bytes10(bytes30(mToken)); mTokenSeqNr = uint72(uint80(mTokenData)); mTokenType = MTokenType(uint8(mTokenData[0])); require(mTokenType == MTokenIdentifier(mTokenAddress).getTokenType(), "Invalid mToken type"); if (mTokenType == MTokenType.FUNGIBLE_MTOKEN) { require(mTokenSeqNr <= 1, "Invalid seqNr for fungible token"); } else if (mTokenType != MTokenType.ERC721_MTOKEN) { revert("Unknown mToken type"); } return (mTokenType, mTokenSeqNr, mTokenAddress); } function parseToken(uint240 mToken) public pure returns (MTokenType mTokenType, uint72 mTokenSeqNr, address mTokenAddress) { mTokenAddress = address(uint160(mToken)); bytes10 mTokenData = bytes10(bytes30(mToken)); mTokenSeqNr = uint72(uint80(mTokenData)); mTokenType = MTokenType(uint8(mTokenData[0])); require(mTokenType == MTokenIdentifier(mTokenAddress).getTokenType(), "Invalid mToken type"); if (mTokenType == MTokenType.FUNGIBLE_MTOKEN) { require(mTokenSeqNr <= 1, "Invalid seqNr for fungible token"); } else if (mTokenType != MTokenType.ERC721_MTOKEN) { revert("Unknown mToken type"); } return (mTokenType, mTokenSeqNr, mTokenAddress); } function parseToken(uint240 mToken) public pure returns (MTokenType mTokenType, uint72 mTokenSeqNr, address mTokenAddress) { mTokenAddress = address(uint160(mToken)); bytes10 mTokenData = bytes10(bytes30(mToken)); mTokenSeqNr = uint72(uint80(mTokenData)); mTokenType = MTokenType(uint8(mTokenData[0])); require(mTokenType == MTokenIdentifier(mTokenAddress).getTokenType(), "Invalid mToken type"); if (mTokenType == MTokenType.FUNGIBLE_MTOKEN) { require(mTokenSeqNr <= 1, "Invalid seqNr for fungible token"); } else if (mTokenType != MTokenType.ERC721_MTOKEN) { revert("Unknown mToken type"); } return (mTokenType, mTokenSeqNr, mTokenAddress); } function _supportMarketInternal(uint240 mToken) internal returns (uint) { if (isListed(mToken)) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mTokenSeqNr <= MTokenCommon(mTokenAddress).totalCreatedMarkets(), "invalid mToken SeqNr"); uint240 tokenAnchor = getAnchorToken(mTokenAddress); require(tokenAnchor == getAnchorToken(mToken), "invalid anchor token"); if (msg.sender != getAdmin()) { if (msg.sender != mTokenAddress || mToken == tokenAnchor || !isListed(tokenAnchor)) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } } if (mToken == tokenAnchor) { _addMarketInternal(mToken); } emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _supportMarketInternal(uint240 mToken) internal returns (uint) { if (isListed(mToken)) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mTokenSeqNr <= MTokenCommon(mTokenAddress).totalCreatedMarkets(), "invalid mToken SeqNr"); uint240 tokenAnchor = getAnchorToken(mTokenAddress); require(tokenAnchor == getAnchorToken(mToken), "invalid anchor token"); if (msg.sender != getAdmin()) { if (msg.sender != mTokenAddress || mToken == tokenAnchor || !isListed(tokenAnchor)) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } } if (mToken == tokenAnchor) { _addMarketInternal(mToken); } emit MarketListed(mToken); return uint(Error.NO_ERROR); } ( , uint72 mTokenSeqNr, address mTokenAddress) = parseToken(mToken); function _supportMarketInternal(uint240 mToken) internal returns (uint) { if (isListed(mToken)) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mTokenSeqNr <= MTokenCommon(mTokenAddress).totalCreatedMarkets(), "invalid mToken SeqNr"); uint240 tokenAnchor = getAnchorToken(mTokenAddress); require(tokenAnchor == getAnchorToken(mToken), "invalid anchor token"); if (msg.sender != getAdmin()) { if (msg.sender != mTokenAddress || mToken == tokenAnchor || !isListed(tokenAnchor)) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } } if (mToken == tokenAnchor) { _addMarketInternal(mToken); } emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _supportMarketInternal(uint240 mToken) internal returns (uint) { if (isListed(mToken)) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mTokenSeqNr <= MTokenCommon(mTokenAddress).totalCreatedMarkets(), "invalid mToken SeqNr"); uint240 tokenAnchor = getAnchorToken(mTokenAddress); require(tokenAnchor == getAnchorToken(mToken), "invalid anchor token"); if (msg.sender != getAdmin()) { if (msg.sender != mTokenAddress || mToken == tokenAnchor || !isListed(tokenAnchor)) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } } if (mToken == tokenAnchor) { _addMarketInternal(mToken); } emit MarketListed(mToken); return uint(Error.NO_ERROR); } markets[mToken] = Market({_isListed: true, _collateralFactorMantissa: 0}); function _supportMarketInternal(uint240 mToken) internal returns (uint) { if (isListed(mToken)) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mTokenSeqNr <= MTokenCommon(mTokenAddress).totalCreatedMarkets(), "invalid mToken SeqNr"); uint240 tokenAnchor = getAnchorToken(mTokenAddress); require(tokenAnchor == getAnchorToken(mToken), "invalid anchor token"); if (msg.sender != getAdmin()) { if (msg.sender != mTokenAddress || mToken == tokenAnchor || !isListed(tokenAnchor)) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } } if (mToken == tokenAnchor) { _addMarketInternal(mToken); } emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(uint240 mToken) internal { require(allMarketsIndex[mToken] == 0, "market already added"); allMarketsSize++; allMarkets[allMarketsSize] = mToken; allMarketsIndex[mToken] = allMarketsSize; } function isListed(uint240 mToken) internal view returns (bool) { if (!(markets[getAnchorToken(mToken)]._isListed)) { return false; } return (markets[mToken]._isListed); } function isListed(uint240 mToken) internal view returns (bool) { if (!(markets[getAnchorToken(mToken)]._isListed)) { return false; } return (markets[mToken]._isListed); } function collateralFactorMantissa(uint240 mToken) public view returns (uint) { require(isListed(mToken), "mToken not listed"); uint240 tokenAnchor = getAnchorToken(mToken); uint result = markets[tokenAnchor]._collateralFactorMantissa; if (result == 0) { return 0; } if (mToken != tokenAnchor) { uint localFactor = markets[mToken]._collateralFactorMantissa; if (localFactor != 0) { result = localFactor; } } require(result <= collateralFactorMaxMantissa, "collateral factor too high"); return result; } function collateralFactorMantissa(uint240 mToken) public view returns (uint) { require(isListed(mToken), "mToken not listed"); uint240 tokenAnchor = getAnchorToken(mToken); uint result = markets[tokenAnchor]._collateralFactorMantissa; if (result == 0) { return 0; } if (mToken != tokenAnchor) { uint localFactor = markets[mToken]._collateralFactorMantissa; if (localFactor != 0) { result = localFactor; } } require(result <= collateralFactorMaxMantissa, "collateral factor too high"); return result; } function collateralFactorMantissa(uint240 mToken) public view returns (uint) { require(isListed(mToken), "mToken not listed"); uint240 tokenAnchor = getAnchorToken(mToken); uint result = markets[tokenAnchor]._collateralFactorMantissa; if (result == 0) { return 0; } if (mToken != tokenAnchor) { uint localFactor = markets[mToken]._collateralFactorMantissa; if (localFactor != 0) { result = localFactor; } } require(result <= collateralFactorMaxMantissa, "collateral factor too high"); return result; } function collateralFactorMantissa(uint240 mToken) public view returns (uint) { require(isListed(mToken), "mToken not listed"); uint240 tokenAnchor = getAnchorToken(mToken); uint result = markets[tokenAnchor]._collateralFactorMantissa; if (result == 0) { return 0; } if (mToken != tokenAnchor) { uint localFactor = markets[mToken]._collateralFactorMantissa; if (localFactor != 0) { result = localFactor; } } require(result <= collateralFactorMaxMantissa, "collateral factor too high"); return result; } }
4,993,132
[ 1, 9802, 603, 21327, 1807, 490, 88, 1539, 13456, 16, 598, 2690, 17953, 225, 1220, 6835, 1297, 486, 14196, 1281, 3152, 18, 4826, 1931, 2502, 1297, 506, 316, 490, 88, 1539, 58, 21, 3245, 225, 21327, 16, 312, 8683, 18, 926, 1359, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 88, 1539, 6517, 353, 490, 88, 1539, 58, 21, 3245, 16, 490, 88, 1539, 6517, 1358, 288, 203, 203, 565, 3885, 1435, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 22501, 1435, 1071, 1476, 1135, 261, 2867, 8843, 429, 3981, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 312, 15608, 639, 4446, 2555, 31, 203, 3639, 19931, 288, 203, 5411, 3981, 519, 272, 945, 12, 3276, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 22501, 1435, 1071, 1476, 1135, 261, 2867, 8843, 429, 3981, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 312, 15608, 639, 4446, 2555, 31, 203, 3639, 19931, 288, 203, 5411, 3981, 519, 272, 945, 12, 3276, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 203, 565, 445, 6808, 8924, 1584, 44, 1435, 1071, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1758, 12, 11890, 16874, 19236, 21, 10019, 203, 565, 289, 203, 203, 565, 445, 336, 11605, 1345, 12, 2867, 312, 1345, 8924, 13, 1071, 16618, 1135, 261, 11890, 28784, 13, 288, 203, 3639, 327, 19540, 1345, 12, 49, 1345, 3004, 12, 81, 1345, 8924, 2934, 588, 28675, 9334, 374, 16, 312, 1345, 8924, 1769, 203, 565, 289, 203, 203, 565, 445, 336, 11605, 1345, 12, 11890, 28784, 312, 1345, 13, 2713, 16618, 1135, 261, 11890, 28784, 13, 288, 203, 3639, 327, 261, 81, 1345, 473, 374, 5297, 12648, 2787, 9449, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 1769, 203, 565, 289, 203, 203, 565, 445, 19540, 1345, 2 ]
./full_match/3/0x0074FB56Aa4581D67Bb4f56AE17b5D6DcAb13BFc/sources/contracts/Nimble.sol
* @dev Returns true if the contract is paused, and false otherwise./
function paused(uint transferId) public view returns (bool) { return _blocked[_transferPending[transferId].tokenId]; }
14,155,178
[ 1, 1356, 638, 309, 326, 6835, 353, 17781, 16, 471, 629, 3541, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17781, 12, 11890, 7412, 548, 13, 1071, 1476, 225, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 23156, 63, 67, 13866, 8579, 63, 13866, 548, 8009, 2316, 548, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x6179e059D9a892ee1a2BAC39dd6a8e5703583918/sources/LucasStaking.sol
yfdai token contract address reward rate 72.00% per year staking fee 1.50 percent unstaking fee 0.50 percent unstaking possible after 72 hours
contract LucasStaking is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); address public tokenAddress; uint public constant rewardRate = 7200; uint public constant rewardInterval = 365 days; uint public constant stakingFeeRate = 150; uint public constant unstakingFeeRate = 50; uint public constant cliffTime = 72 hours; uint public totalClaimedRewards = 0; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public stakingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; constructor( address _tokenAddress ) public { tokenAddress = _tokenAddress; } function updateAccount(address account) private { uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } lastClaimedTime[account] = now; } function updateAccount(address account) private { uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } lastClaimedTime[account] = now; } function getPendingDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint pendingDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return pendingDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function deposit(uint amountToStake) public { require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function deposit(uint amountToStake) public { require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer withdraw fee."); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer withdraw fee."); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimDivs() public { updateAccount(msg.sender); } function getStakersList(uint startIndex, uint endIndex) public view returns (address[] memory stakers, uint[] memory stakingTimestamps, uint[] memory lastClaimedTimeStamps, uint[] memory stakedTokens) { require (startIndex < endIndex); uint length = endIndex.sub(startIndex); address[] memory _stakers = new address[](length); uint[] memory _stakingTimestamps = new uint[](length); uint[] memory _lastClaimedTimeStamps = new uint[](length); uint[] memory _stakedTokens = new uint[](length); for (uint i = startIndex; i < endIndex; i = i.add(1)) { address staker = holders.at(i); uint listIndex = i.sub(startIndex); _stakers[listIndex] = staker; _stakingTimestamps[listIndex] = stakingTime[staker]; _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker]; _stakedTokens[listIndex] = depositedTokens[staker]; } return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens); } uint private constant stakingAndDaoTokens = 5129e18; function getStakersList(uint startIndex, uint endIndex) public view returns (address[] memory stakers, uint[] memory stakingTimestamps, uint[] memory lastClaimedTimeStamps, uint[] memory stakedTokens) { require (startIndex < endIndex); uint length = endIndex.sub(startIndex); address[] memory _stakers = new address[](length); uint[] memory _stakingTimestamps = new uint[](length); uint[] memory _lastClaimedTimeStamps = new uint[](length); uint[] memory _stakedTokens = new uint[](length); for (uint i = startIndex; i < endIndex; i = i.add(1)) { address staker = holders.at(i); uint listIndex = i.sub(startIndex); _stakers[listIndex] = staker; _stakingTimestamps[listIndex] = stakingTime[staker]; _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker]; _stakedTokens[listIndex] = depositedTokens[staker]; } return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens); } uint private constant stakingAndDaoTokens = 5129e18; function getStakingAndDaoAmount() public view returns (uint) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } function getStakingAndDaoAmount() public view returns (uint) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require (_tokenAddr != tokenAddress, "Cannot Transfer Out YF-DAI!"); Token(_tokenAddr).transfer(_to, _amount); } function showAddressToken() public view returns (address) { return tokenAddress; } }
3,419,412
[ 1, 93, 74, 2414, 77, 1147, 6835, 1758, 19890, 4993, 19387, 18, 713, 9, 1534, 3286, 384, 6159, 14036, 404, 18, 3361, 5551, 640, 334, 6159, 14036, 374, 18, 3361, 5551, 640, 334, 6159, 3323, 1839, 19387, 7507, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 5286, 345, 510, 6159, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 871, 534, 359, 14727, 1429, 4193, 12, 2867, 10438, 16, 2254, 3844, 1769, 203, 377, 203, 565, 1758, 1071, 1147, 1887, 31, 203, 377, 203, 565, 2254, 1071, 5381, 19890, 4727, 273, 2371, 6976, 31, 203, 565, 2254, 1071, 5381, 19890, 4006, 273, 21382, 4681, 31, 203, 377, 203, 565, 2254, 1071, 5381, 384, 6159, 14667, 4727, 273, 18478, 31, 203, 377, 203, 565, 2254, 1071, 5381, 640, 334, 6159, 14667, 4727, 273, 6437, 31, 203, 377, 203, 565, 2254, 1071, 5381, 927, 3048, 950, 273, 19387, 7507, 31, 203, 377, 203, 565, 2254, 1071, 2078, 9762, 329, 17631, 14727, 273, 374, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 366, 4665, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 443, 1724, 329, 5157, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 384, 6159, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1142, 9762, 329, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 2078, 41, 1303, 329, 5157, 31, 203, 203, 565, 3885, 12, 203, 1377, 1758, 389, 2316, 1887, 203, 565, 262, 1071, 288, 203, 1377, 1147, 1887, 273, 389, 2316, 1887, 31, 203, 565, 289, 203, 377, 203, 565, 445, 1089, 3032, 12, 2867, 2236, 13, 3238, 288, 203, 3639, 2 ]
pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // 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 balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Staff is Ownable, RBAC { string public constant ROLE_STAFF = "staff"; function addStaff(address _staff) public onlyOwner { addRole(_staff, ROLE_STAFF); } function removeStaff(address _staff) public onlyOwner { removeRole(_staff, ROLE_STAFF); } function isStaff(address _staff) view public returns (bool) { return hasRole(_staff, ROLE_STAFF); } } contract StaffUtil { Staff public staffContract; constructor (Staff _staffContract) public { require(msg.sender == _staffContract.owner()); staffContract = _staffContract; } modifier onlyOwner() { require(msg.sender == staffContract.owner()); _; } modifier onlyOwnerOrStaff() { require(msg.sender == staffContract.owner() || staffContract.isStaff(msg.sender)); _; } } contract Crowdsale is StaffUtil { using SafeMath for uint256; Token tokenContract; PromoCodes promoCodesContract; DiscountPhases discountPhasesContract; DiscountStructs discountStructsContract; address ethFundsWallet; uint256 referralBonusPercent; uint256 startDate; uint256 crowdsaleStartDate; uint256 endDate; uint256 tokenDecimals; uint256 tokenRate; uint256 tokensForSaleCap; uint256 minPurchaseInWei; uint256 maxInvestorContributionInWei; bool paused; bool finalized; uint256 weiRaised; uint256 soldTokens; uint256 bonusTokens; uint256 sentTokens; uint256 claimedSoldTokens; uint256 claimedBonusTokens; uint256 claimedSentTokens; uint256 purchasedTokensClaimDate; uint256 bonusTokensClaimDate; mapping(address => Investor) public investors; enum InvestorStatus {UNDEFINED, WHITELISTED, BLOCKED} struct Investor { InvestorStatus status; uint256 contributionInWei; uint256 purchasedTokens; uint256 bonusTokens; uint256 referralTokens; uint256 receivedTokens; TokensPurchase[] tokensPurchases; bool isBlockpass; } struct TokensPurchase { uint256 value; uint256 amount; uint256 bonus; address referrer; uint256 referrerSentAmount; } event InvestorWhitelisted(address indexed investor, uint timestamp, address byStaff); event InvestorBlocked(address indexed investor, uint timestamp, address byStaff); event TokensPurchased( address indexed investor, uint indexed purchaseId, uint256 value, uint256 purchasedAmount, uint256 promoCodeAmount, uint256 discountPhaseAmount, uint256 discountStructAmount, address indexed referrer, uint256 referrerSentAmount, uint timestamp ); event TokensPurchaseRefunded( address indexed investor, uint indexed purchaseId, uint256 value, uint256 amount, uint256 bonus, uint timestamp, address byStaff ); event Paused(uint timestamp, address byStaff); event Resumed(uint timestamp, address byStaff); event Finalized(uint timestamp, address byStaff); event TokensSent(address indexed investor, uint256 amount, uint timestamp, address byStaff); event PurchasedTokensClaimLocked(uint date, uint timestamp, address byStaff); event PurchasedTokensClaimUnlocked(uint timestamp, address byStaff); event BonusTokensClaimLocked(uint date, uint timestamp, address byStaff); event BonusTokensClaimUnlocked(uint timestamp, address byStaff); event CrowdsaleStartDateUpdated(uint date, uint timestamp, address byStaff); event EndDateUpdated(uint date, uint timestamp, address byStaff); event MinPurchaseChanged(uint256 minPurchaseInWei, uint timestamp, address byStaff); event MaxInvestorContributionChanged(uint256 maxInvestorContributionInWei, uint timestamp, address byStaff); event TokenRateChanged(uint newRate, uint timestamp, address byStaff); event TokensClaimed( address indexed investor, uint256 purchased, uint256 bonus, uint256 referral, uint256 received, uint timestamp, address byStaff ); event TokensBurned(uint256 amount, uint timestamp, address byStaff); constructor ( uint256[11] uint256Args, address[5] addressArgs ) StaffUtil(Staff(addressArgs[4])) public { // uint256 args startDate = uint256Args[0]; crowdsaleStartDate = uint256Args[1]; endDate = uint256Args[2]; tokenDecimals = uint256Args[3]; tokenRate = uint256Args[4]; tokensForSaleCap = uint256Args[5]; minPurchaseInWei = uint256Args[6]; maxInvestorContributionInWei = uint256Args[7]; purchasedTokensClaimDate = uint256Args[8]; bonusTokensClaimDate = uint256Args[9]; referralBonusPercent = uint256Args[10]; // address args ethFundsWallet = addressArgs[0]; promoCodesContract = PromoCodes(addressArgs[1]); discountPhasesContract = DiscountPhases(addressArgs[2]); discountStructsContract = DiscountStructs(addressArgs[3]); require(startDate < crowdsaleStartDate); require(crowdsaleStartDate < endDate); require(tokenDecimals > 0); require(tokenRate > 0); require(tokensForSaleCap > 0); require(minPurchaseInWei <= maxInvestorContributionInWei); require(ethFundsWallet != address(0)); } function getState() external view returns (bool[2] boolArgs, uint256[18] uint256Args, address[6] addressArgs) { boolArgs[0] = paused; boolArgs[1] = finalized; uint256Args[0] = weiRaised; uint256Args[1] = soldTokens; uint256Args[2] = bonusTokens; uint256Args[3] = sentTokens; uint256Args[4] = claimedSoldTokens; uint256Args[5] = claimedBonusTokens; uint256Args[6] = claimedSentTokens; uint256Args[7] = purchasedTokensClaimDate; uint256Args[8] = bonusTokensClaimDate; uint256Args[9] = startDate; uint256Args[10] = crowdsaleStartDate; uint256Args[11] = endDate; uint256Args[12] = tokenRate; uint256Args[13] = tokenDecimals; uint256Args[14] = minPurchaseInWei; uint256Args[15] = maxInvestorContributionInWei; uint256Args[16] = referralBonusPercent; uint256Args[17] = getTokensForSaleCap(); addressArgs[0] = staffContract; addressArgs[1] = ethFundsWallet; addressArgs[2] = promoCodesContract; addressArgs[3] = discountPhasesContract; addressArgs[4] = discountStructsContract; addressArgs[5] = tokenContract; } function fitsTokensForSaleCap(uint256 _amount) public view returns (bool) { return getDistributedTokens().add(_amount) <= getTokensForSaleCap(); } function getTokensForSaleCap() public view returns (uint256) { if (tokenContract != address(0)) { return tokenContract.balanceOf(this); } return tokensForSaleCap; } function getDistributedTokens() public view returns (uint256) { return soldTokens.sub(claimedSoldTokens).add(bonusTokens.sub(claimedBonusTokens)).add(sentTokens.sub(claimedSentTokens)); } function setTokenContract(Token token) external onlyOwner { require(token.balanceOf(this) >= 0); require(tokenContract == address(0)); require(token != address(0)); tokenContract = token; } function getInvestorClaimedTokens(address _investor) external view returns (uint256) { if (tokenContract != address(0)) { return tokenContract.balanceOf(_investor); } return 0; } function isBlockpassInvestor(address _investor) external constant returns (bool) { return investors[_investor].status == InvestorStatus.WHITELISTED && investors[_investor].isBlockpass; } function whitelistInvestor(address _investor, bool _isBlockpass) external onlyOwnerOrStaff { require(_investor != address(0)); require(investors[_investor].status != InvestorStatus.WHITELISTED); investors[_investor].status = InvestorStatus.WHITELISTED; investors[_investor].isBlockpass = _isBlockpass; emit InvestorWhitelisted(_investor, now, msg.sender); } function bulkWhitelistInvestor(address[] _investors) external onlyOwnerOrStaff { for (uint256 i = 0; i < _investors.length; i++) { if (_investors[i] != address(0) && investors[_investors[i]].status != InvestorStatus.WHITELISTED) { investors[_investors[i]].status = InvestorStatus.WHITELISTED; emit InvestorWhitelisted(_investors[i], now, msg.sender); } } } function blockInvestor(address _investor) external onlyOwnerOrStaff { require(_investor != address(0)); require(investors[_investor].status != InvestorStatus.BLOCKED); investors[_investor].status = InvestorStatus.BLOCKED; emit InvestorBlocked(_investor, now, msg.sender); } function lockPurchasedTokensClaim(uint256 _date) external onlyOwner { require(_date > now); purchasedTokensClaimDate = _date; emit PurchasedTokensClaimLocked(_date, now, msg.sender); } function unlockPurchasedTokensClaim() external onlyOwner { purchasedTokensClaimDate = now; emit PurchasedTokensClaimUnlocked(now, msg.sender); } function lockBonusTokensClaim(uint256 _date) external onlyOwner { require(_date > now); bonusTokensClaimDate = _date; emit BonusTokensClaimLocked(_date, now, msg.sender); } function unlockBonusTokensClaim() external onlyOwner { bonusTokensClaimDate = now; emit BonusTokensClaimUnlocked(now, msg.sender); } function setCrowdsaleStartDate(uint256 _date) external onlyOwner { crowdsaleStartDate = _date; emit CrowdsaleStartDateUpdated(_date, now, msg.sender); } function setEndDate(uint256 _date) external onlyOwner { endDate = _date; emit EndDateUpdated(_date, now, msg.sender); } function setMinPurchaseInWei(uint256 _minPurchaseInWei) external onlyOwner { minPurchaseInWei = _minPurchaseInWei; emit MinPurchaseChanged(_minPurchaseInWei, now, msg.sender); } function setMaxInvestorContributionInWei(uint256 _maxInvestorContributionInWei) external onlyOwner { require(minPurchaseInWei <= _maxInvestorContributionInWei); maxInvestorContributionInWei = _maxInvestorContributionInWei; emit MaxInvestorContributionChanged(_maxInvestorContributionInWei, now, msg.sender); } function changeTokenRate(uint256 _tokenRate) external onlyOwner { require(_tokenRate > 0); tokenRate = _tokenRate; emit TokenRateChanged(_tokenRate, now, msg.sender); } function buyTokens(bytes32 _promoCode, address _referrer) external payable { require(!finalized); require(!paused); require(startDate < now); require(investors[msg.sender].status == InvestorStatus.WHITELISTED); require(msg.value > 0); require(msg.value >= minPurchaseInWei); require(investors[msg.sender].contributionInWei.add(msg.value) <= maxInvestorContributionInWei); // calculate purchased amount uint256 purchasedAmount; if (tokenDecimals > 18) { purchasedAmount = msg.value.mul(tokenRate).mul(10 ** (tokenDecimals - 18)); } else if (tokenDecimals < 18) { purchasedAmount = msg.value.mul(tokenRate).div(10 ** (18 - tokenDecimals)); } else { purchasedAmount = msg.value.mul(tokenRate); } // calculate total amount, this includes promo code amount or discount phase amount uint256 promoCodeBonusAmount = promoCodesContract.applyBonusAmount(msg.sender, purchasedAmount, _promoCode); uint256 discountPhaseBonusAmount = discountPhasesContract.calculateBonusAmount(purchasedAmount); uint256 discountStructBonusAmount = discountStructsContract.getBonus(msg.sender, purchasedAmount, msg.value); uint256 bonusAmount = promoCodeBonusAmount.add(discountPhaseBonusAmount).add(discountStructBonusAmount); // update referrer's referral tokens uint256 referrerBonusAmount; address referrerAddr; if ( _referrer != address(0) && msg.sender != _referrer && investors[_referrer].status == InvestorStatus.WHITELISTED ) { referrerBonusAmount = purchasedAmount * referralBonusPercent / 100; referrerAddr = _referrer; } // check that calculated tokens will not exceed tokens for sale cap require(fitsTokensForSaleCap(purchasedAmount.add(bonusAmount).add(referrerBonusAmount))); // update crowdsale total amount of capital raised weiRaised = weiRaised.add(msg.value); soldTokens = soldTokens.add(purchasedAmount); bonusTokens = bonusTokens.add(bonusAmount).add(referrerBonusAmount); // update referrer's bonus tokens investors[referrerAddr].referralTokens = investors[referrerAddr].referralTokens.add(referrerBonusAmount); // update investor's purchased tokens investors[msg.sender].purchasedTokens = investors[msg.sender].purchasedTokens.add(purchasedAmount); // update investor's bonus tokens investors[msg.sender].bonusTokens = investors[msg.sender].bonusTokens.add(bonusAmount); // update investor's tokens eth value investors[msg.sender].contributionInWei = investors[msg.sender].contributionInWei.add(msg.value); // update investor's tokens purchases uint tokensPurchasesLength = investors[msg.sender].tokensPurchases.push(TokensPurchase({ value : msg.value, amount : purchasedAmount, bonus : bonusAmount, referrer : referrerAddr, referrerSentAmount : referrerBonusAmount }) ); // log investor's tokens purchase emit TokensPurchased( msg.sender, tokensPurchasesLength - 1, msg.value, purchasedAmount, promoCodeBonusAmount, discountPhaseBonusAmount, discountStructBonusAmount, referrerAddr, referrerBonusAmount, now ); // forward eth to funds wallet require(ethFundsWallet.call.gas(300000).value(msg.value)()); } function sendTokens(address _investor, uint256 _amount) external onlyOwner { require(investors[_investor].status == InvestorStatus.WHITELISTED); require(_amount > 0); require(fitsTokensForSaleCap(_amount)); // update crowdsale total amount of capital raised sentTokens = sentTokens.add(_amount); // update investor's received tokens balance investors[_investor].receivedTokens = investors[_investor].receivedTokens.add(_amount); // log tokens sent action emit TokensSent( _investor, _amount, now, msg.sender ); } function burnUnsoldTokens() external onlyOwner { require(tokenContract != address(0)); require(finalized); uint256 tokensToBurn = tokenContract.balanceOf(this).sub(getDistributedTokens()); require(tokensToBurn > 0); tokenContract.burn(tokensToBurn); // log tokens burned action emit TokensBurned(tokensToBurn, now, msg.sender); } function claimTokens() external { require(tokenContract != address(0)); require(!paused); require(investors[msg.sender].status == InvestorStatus.WHITELISTED); uint256 clPurchasedTokens; uint256 clReceivedTokens; uint256 clBonusTokens_; uint256 clRefTokens; require(purchasedTokensClaimDate < now || bonusTokensClaimDate < now); { uint256 purchasedTokens = investors[msg.sender].purchasedTokens; uint256 receivedTokens = investors[msg.sender].receivedTokens; if (purchasedTokensClaimDate < now && (purchasedTokens > 0 || receivedTokens > 0)) { investors[msg.sender].contributionInWei = 0; investors[msg.sender].purchasedTokens = 0; investors[msg.sender].receivedTokens = 0; claimedSoldTokens = claimedSoldTokens.add(purchasedTokens); claimedSentTokens = claimedSentTokens.add(receivedTokens); // free up storage used by transaction delete (investors[msg.sender].tokensPurchases); clPurchasedTokens = purchasedTokens; clReceivedTokens = receivedTokens; tokenContract.transfer(msg.sender, purchasedTokens.add(receivedTokens)); } } { uint256 bonusTokens_ = investors[msg.sender].bonusTokens; uint256 refTokens = investors[msg.sender].referralTokens; if (bonusTokensClaimDate < now && (bonusTokens_ > 0 || refTokens > 0)) { investors[msg.sender].bonusTokens = 0; investors[msg.sender].referralTokens = 0; claimedBonusTokens = claimedBonusTokens.add(bonusTokens_).add(refTokens); clBonusTokens_ = bonusTokens_; clRefTokens = refTokens; tokenContract.transfer(msg.sender, bonusTokens_.add(refTokens)); } } require(clPurchasedTokens > 0 || clBonusTokens_ > 0 || clRefTokens > 0 || clReceivedTokens > 0); emit TokensClaimed(msg.sender, clPurchasedTokens, clBonusTokens_, clRefTokens, clReceivedTokens, now, msg.sender); } function refundTokensPurchase(address _investor, uint _purchaseId) external payable onlyOwner { require(msg.value > 0); require(investors[_investor].tokensPurchases[_purchaseId].value == msg.value); _refundTokensPurchase(_investor, _purchaseId); // forward eth to investor's wallet address _investor.transfer(msg.value); } function refundAllInvestorTokensPurchases(address _investor) external payable onlyOwner { require(msg.value > 0); require(investors[_investor].contributionInWei == msg.value); for (uint i = 0; i < investors[_investor].tokensPurchases.length; i++) { if (investors[_investor].tokensPurchases[i].value == 0) { continue; } _refundTokensPurchase(_investor, i); } // forward eth to investor's wallet address _investor.transfer(msg.value); } function _refundTokensPurchase(address _investor, uint _purchaseId) private { // update referrer's referral tokens address referrer = investors[_investor].tokensPurchases[_purchaseId].referrer; if (referrer != address(0)) { uint256 sentAmount = investors[_investor].tokensPurchases[_purchaseId].referrerSentAmount; investors[referrer].referralTokens = investors[referrer].referralTokens.sub(sentAmount); bonusTokens = bonusTokens.sub(sentAmount); } // update investor's eth amount uint256 purchaseValue = investors[_investor].tokensPurchases[_purchaseId].value; investors[_investor].contributionInWei = investors[_investor].contributionInWei.sub(purchaseValue); // update investor's purchased tokens uint256 purchaseAmount = investors[_investor].tokensPurchases[_purchaseId].amount; investors[_investor].purchasedTokens = investors[_investor].purchasedTokens.sub(purchaseAmount); // update investor's bonus tokens uint256 bonusAmount = investors[_investor].tokensPurchases[_purchaseId].bonus; investors[_investor].bonusTokens = investors[_investor].bonusTokens.sub(bonusAmount); // update crowdsale total amount of capital raised weiRaised = weiRaised.sub(purchaseValue); soldTokens = soldTokens.sub(purchaseAmount); bonusTokens = bonusTokens.sub(bonusAmount); // free up storage used by transaction delete (investors[_investor].tokensPurchases[_purchaseId]); // log investor's tokens purchase refund emit TokensPurchaseRefunded(_investor, _purchaseId, purchaseValue, purchaseAmount, bonusAmount, now, msg.sender); } function getInvestorTokensPurchasesLength(address _investor) public constant returns (uint) { return investors[_investor].tokensPurchases.length; } function getInvestorTokensPurchase( address _investor, uint _purchaseId ) external constant returns ( uint256 value, uint256 amount, uint256 bonus, address referrer, uint256 referrerSentAmount ) { value = investors[_investor].tokensPurchases[_purchaseId].value; amount = investors[_investor].tokensPurchases[_purchaseId].amount; bonus = investors[_investor].tokensPurchases[_purchaseId].bonus; referrer = investors[_investor].tokensPurchases[_purchaseId].referrer; referrerSentAmount = investors[_investor].tokensPurchases[_purchaseId].referrerSentAmount; } function pause() external onlyOwner { require(!paused); paused = true; emit Paused(now, msg.sender); } function resume() external onlyOwner { require(paused); paused = false; emit Resumed(now, msg.sender); } function finalize() external onlyOwner { require(!finalized); finalized = true; emit Finalized(now, msg.sender); } } contract DiscountPhases is StaffUtil { using SafeMath for uint256; event DiscountPhaseAdded(uint index, string name, uint8 percent, uint fromDate, uint toDate, uint timestamp, address byStaff); event DiscountPhaseRemoved(uint index, uint timestamp, address byStaff); struct DiscountPhase { uint8 percent; uint fromDate; uint toDate; } DiscountPhase[] public discountPhases; constructor(Staff _staffContract) StaffUtil(_staffContract) public { } function calculateBonusAmount(uint256 _purchasedAmount) public constant returns (uint256) { for (uint i = 0; i < discountPhases.length; i++) { if (now >= discountPhases[i].fromDate && now <= discountPhases[i].toDate) { return _purchasedAmount.mul(discountPhases[i].percent).div(100); } } } function addDiscountPhase(string _name, uint8 _percent, uint _fromDate, uint _toDate) public onlyOwnerOrStaff { require(bytes(_name).length > 0); require(_percent > 0 && _percent <= 100); if (now > _fromDate) { _fromDate = now; } require(_fromDate < _toDate); for (uint i = 0; i < discountPhases.length; i++) { require(_fromDate > discountPhases[i].toDate || _toDate < discountPhases[i].fromDate); } uint index = discountPhases.push(DiscountPhase({percent : _percent, fromDate : _fromDate, toDate : _toDate})) - 1; emit DiscountPhaseAdded(index, _name, _percent, _fromDate, _toDate, now, msg.sender); } function removeDiscountPhase(uint _index) public onlyOwnerOrStaff { require(now < discountPhases[_index].toDate); delete discountPhases[_index]; emit DiscountPhaseRemoved(_index, now, msg.sender); } } contract DiscountStructs is StaffUtil { using SafeMath for uint256; address public crowdsale; event DiscountStructAdded( uint index, bytes32 name, uint256 tokens, uint[2] dates, uint256[] fromWei, uint256[] toWei, uint256[] percent, uint timestamp, address byStaff ); event DiscountStructRemoved( uint index, uint timestamp, address byStaff ); event DiscountStructUsed( uint index, uint step, address investor, uint256 tokens, uint timestamp ); struct DiscountStruct { uint256 availableTokens; uint256 distributedTokens; uint fromDate; uint toDate; } struct DiscountStep { uint256 fromWei; uint256 toWei; uint256 percent; } DiscountStruct[] public discountStructs; mapping(uint => DiscountStep[]) public discountSteps; constructor(Staff _staffContract) StaffUtil(_staffContract) public { } modifier onlyCrowdsale() { require(msg.sender == crowdsale); _; } function setCrowdsale(Crowdsale _crowdsale) external onlyOwner { require(crowdsale == address(0)); require(_crowdsale.staffContract() == staffContract); crowdsale = _crowdsale; } function getBonus(address _investor, uint256 _purchasedAmount, uint256 _purchasedValue) public onlyCrowdsale returns (uint256) { for (uint i = 0; i < discountStructs.length; i++) { if (now >= discountStructs[i].fromDate && now <= discountStructs[i].toDate) { if (discountStructs[i].distributedTokens >= discountStructs[i].availableTokens) { return; } for (uint j = 0; j < discountSteps[i].length; j++) { if (_purchasedValue >= discountSteps[i][j].fromWei && (_purchasedValue < discountSteps[i][j].toWei || discountSteps[i][j].toWei == 0)) { uint256 bonus = _purchasedAmount.mul(discountSteps[i][j].percent).div(100); if (discountStructs[i].distributedTokens.add(bonus) > discountStructs[i].availableTokens) { return; } discountStructs[i].distributedTokens = discountStructs[i].distributedTokens.add(bonus); emit DiscountStructUsed(i, j, _investor, bonus, now); return bonus; } } return; } } } function calculateBonus(uint256 _purchasedAmount, uint256 _purchasedValue) public constant returns (uint256) { for (uint i = 0; i < discountStructs.length; i++) { if (now >= discountStructs[i].fromDate && now <= discountStructs[i].toDate) { if (discountStructs[i].distributedTokens >= discountStructs[i].availableTokens) { return; } for (uint j = 0; j < discountSteps[i].length; j++) { if (_purchasedValue >= discountSteps[i][j].fromWei && (_purchasedValue < discountSteps[i][j].toWei || discountSteps[i][j].toWei == 0)) { uint256 bonus = _purchasedAmount.mul(discountSteps[i][j].percent).div(100); if (discountStructs[i].distributedTokens.add(bonus) > discountStructs[i].availableTokens) { return; } return bonus; } } return; } } } function addDiscountStruct(bytes32 _name, uint256 _tokens, uint[2] _dates, uint256[] _fromWei, uint256[] _toWei, uint256[] _percent) external onlyOwnerOrStaff { require(_name.length > 0); require(_tokens > 0); require(_dates[0] < _dates[1]); require(_fromWei.length > 0 && _fromWei.length == _toWei.length && _fromWei.length == _percent.length); for (uint j = 0; j < discountStructs.length; j++) { require(_dates[0] > discountStructs[j].fromDate || _dates[1] < discountStructs[j].toDate); } DiscountStruct memory ds = DiscountStruct(_tokens, 0, _dates[0], _dates[1]); uint index = discountStructs.push(ds) - 1; for (uint i = 0; i < _fromWei.length; i++) { require(_fromWei[i] > 0 || _toWei[i] > 0); if (_fromWei[i] > 0 && _toWei[i] > 0) { require(_fromWei[i] < _toWei[i]); } require(_percent[i] > 0 && _percent[i] <= 100); discountSteps[index].push(DiscountStep(_fromWei[i], _toWei[i], _percent[i])); } emit DiscountStructAdded(index, _name, _tokens, _dates, _fromWei, _toWei, _percent, now, msg.sender); } function removeDiscountStruct(uint _index) public onlyOwnerOrStaff { require(now < discountStructs[_index].toDate); delete discountStructs[_index]; delete discountSteps[_index]; emit DiscountStructRemoved(_index, now, msg.sender); } } contract PromoCodes is StaffUtil { using SafeMath for uint256; address public crowdsale; event PromoCodeAdded(bytes32 indexed code, string name, uint8 percent, uint256 maxUses, uint timestamp, address byStaff); event PromoCodeRemoved(bytes32 indexed code, uint timestamp, address byStaff); event PromoCodeUsed(bytes32 indexed code, address investor, uint timestamp); struct PromoCode { uint8 percent; uint256 uses; uint256 maxUses; mapping(address => bool) investors; } mapping(bytes32 => PromoCode) public promoCodes; constructor(Staff _staffContract) StaffUtil(_staffContract) public { } modifier onlyCrowdsale() { require(msg.sender == crowdsale); _; } function setCrowdsale(Crowdsale _crowdsale) external onlyOwner { require(crowdsale == address(0)); require(_crowdsale.staffContract() == staffContract); crowdsale = _crowdsale; } function applyBonusAmount(address _investor, uint256 _purchasedAmount, bytes32 _promoCode) public onlyCrowdsale returns (uint256) { if (promoCodes[_promoCode].percent == 0 || promoCodes[_promoCode].investors[_investor] || promoCodes[_promoCode].uses == promoCodes[_promoCode].maxUses) { return 0; } promoCodes[_promoCode].investors[_investor] = true; promoCodes[_promoCode].uses = promoCodes[_promoCode].uses + 1; emit PromoCodeUsed(_promoCode, _investor, now); return _purchasedAmount.mul(promoCodes[_promoCode].percent).div(100); } function calculateBonusAmount(address _investor, uint256 _purchasedAmount, bytes32 _promoCode) public constant returns (uint256) { if (promoCodes[_promoCode].percent == 0 || promoCodes[_promoCode].investors[_investor] || promoCodes[_promoCode].uses == promoCodes[_promoCode].maxUses) { return 0; } return _purchasedAmount.mul(promoCodes[_promoCode].percent).div(100); } function addPromoCode(string _name, bytes32 _code, uint256 _maxUses, uint8 _percent) public onlyOwnerOrStaff { require(bytes(_name).length > 0); require(_code[0] != 0); require(_percent > 0 && _percent <= 100); require(_maxUses > 0); require(promoCodes[_code].percent == 0); promoCodes[_code].percent = _percent; promoCodes[_code].maxUses = _maxUses; emit PromoCodeAdded(_code, _name, _percent, _maxUses, now, msg.sender); } function removePromoCode(bytes32 _code) public onlyOwnerOrStaff { delete promoCodes[_code]; emit PromoCodeRemoved(_code, now, msg.sender); } } contract Token is BurnableToken { }
update crowdsale total amount of capital raised update investor's received tokens balance log tokens sent action
function sendTokens(address _investor, uint256 _amount) external onlyOwner { require(investors[_investor].status == InvestorStatus.WHITELISTED); require(_amount > 0); require(fitsTokensForSaleCap(_amount)); sentTokens = sentTokens.add(_amount); investors[_investor].receivedTokens = investors[_investor].receivedTokens.add(_amount); emit TokensSent( _investor, _amount, now, msg.sender ); }
187,908
[ 1, 2725, 276, 492, 2377, 5349, 2078, 3844, 434, 12872, 11531, 1089, 2198, 395, 280, 1807, 5079, 2430, 11013, 613, 2430, 3271, 1301, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1366, 5157, 12, 2867, 389, 5768, 395, 280, 16, 2254, 5034, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 202, 202, 6528, 12, 5768, 395, 1383, 63, 67, 5768, 395, 280, 8009, 2327, 422, 5454, 395, 280, 1482, 18, 16861, 7085, 2056, 1769, 203, 202, 202, 6528, 24899, 8949, 405, 374, 1769, 203, 202, 202, 6528, 12, 18352, 5157, 1290, 30746, 4664, 24899, 8949, 10019, 203, 203, 202, 202, 7569, 5157, 273, 3271, 5157, 18, 1289, 24899, 8949, 1769, 203, 203, 202, 202, 5768, 395, 1383, 63, 67, 5768, 395, 280, 8009, 15213, 5157, 273, 2198, 395, 1383, 63, 67, 5768, 395, 280, 8009, 15213, 5157, 18, 1289, 24899, 8949, 1769, 203, 203, 202, 202, 18356, 13899, 7828, 12, 203, 1082, 202, 67, 5768, 395, 280, 16, 203, 1082, 202, 67, 8949, 16, 203, 1082, 202, 3338, 16, 203, 1082, 202, 3576, 18, 15330, 203, 202, 202, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "./Proxy.sol"; /** * @title Allows to create new proxy contact and execute a message call to the * new proxy within one transaction. * * @dev This contract is adapted from a ProxyFactory contract implementation * from https://github.com/gnosis/safe-contracts. */ contract ProxyFactory { /** * @notice The event is emitted from the ProxyFactory::createProxy * function on success. * * @param _proxy A newly created proxy. */ event ProxyCreated(Proxy _proxy); /** * @dev Allows to create new proxy contact and execute a message call (if * a message data is non-empty) to the new proxy within one * transaction. * * Function requires: * - The specified master copy address is not null. * * @param _masterCopy Address of a master copy. * @param _data Payload for message call sent to new proxy contract. * Executes a message call to this parameter if it's not empty. * * @return proxy_ A newly created proxy. */ function createProxy(address _masterCopy, bytes memory _data) public returns (Proxy proxy_) { require( _masterCopy != address(0), "Master copy address is null." ); proxy_ = new Proxy(_masterCopy); if (_data.length > 0) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy_, 0, add(_data, 0x20), mload(_data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreated(proxy_); } }
* @title Allows to create new proxy contact and execute a message call to the new proxy within one transaction. @dev This contract is adapted from a ProxyFactory contract implementation/
contract ProxyFactory { event ProxyCreated(Proxy _proxy); function createProxy(address _masterCopy, bytes memory _data) public returns (Proxy proxy_) { require( _masterCopy != address(0), "Master copy address is null." ); proxy_ = new Proxy(_masterCopy); if (_data.length > 0) assembly { if eq(call(gas, proxy_, 0, add(_data, 0x20), mload(_data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreated(proxy_); } { require( _masterCopy != address(0), "Master copy address is null." ); proxy_ = new Proxy(_masterCopy); if (_data.length > 0) assembly { if eq(call(gas, proxy_, 0, add(_data, 0x20), mload(_data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreated(proxy_); } { require( _masterCopy != address(0), "Master copy address is null." ); proxy_ = new Proxy(_masterCopy); if (_data.length > 0) assembly { if eq(call(gas, proxy_, 0, add(_data, 0x20), mload(_data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreated(proxy_); } }
12,888,910
[ 1, 19132, 358, 752, 394, 2889, 5388, 471, 1836, 279, 883, 745, 358, 326, 3639, 394, 2889, 3470, 1245, 2492, 18, 225, 1220, 6835, 353, 28345, 628, 279, 7659, 1733, 6835, 4471, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7659, 1733, 288, 203, 203, 565, 871, 7659, 6119, 12, 3886, 389, 5656, 1769, 203, 203, 565, 445, 752, 3886, 12, 2867, 389, 7525, 2951, 16, 1731, 3778, 389, 892, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 3886, 2889, 67, 13, 203, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 7525, 2951, 480, 1758, 12, 20, 3631, 203, 5411, 315, 7786, 1610, 1758, 353, 446, 1199, 203, 3639, 11272, 203, 203, 3639, 2889, 67, 273, 394, 7659, 24899, 7525, 2951, 1769, 203, 3639, 309, 261, 67, 892, 18, 2469, 405, 374, 13, 203, 5411, 19931, 288, 203, 7734, 309, 7555, 12, 1991, 12, 31604, 16, 2889, 67, 16, 374, 16, 527, 24899, 892, 16, 374, 92, 3462, 3631, 312, 945, 24899, 892, 3631, 374, 16, 374, 3631, 374, 13, 288, 203, 10792, 15226, 12, 20, 16, 374, 13, 203, 7734, 289, 203, 5411, 289, 203, 203, 3639, 3626, 7659, 6119, 12, 5656, 67, 1769, 203, 565, 289, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 7525, 2951, 480, 1758, 12, 20, 3631, 203, 5411, 315, 7786, 1610, 1758, 353, 446, 1199, 203, 3639, 11272, 203, 203, 3639, 2889, 67, 273, 394, 7659, 24899, 7525, 2951, 1769, 203, 3639, 309, 261, 67, 892, 18, 2469, 405, 374, 13, 203, 5411, 19931, 288, 203, 7734, 309, 7555, 12, 1991, 12, 31604, 16, 2889, 67, 16, 374, 16, 527, 24899, 892, 16, 374, 92, 3462, 3631, 312, 945, 24899, 892, 3631, 374, 16, 374, 3631, 374, 13, 288, 203, 10792, 15226, 2 ]
pragma solidity 0.6.2; //new things contract Old{ address payable owner; bytes32 bytesnum; bytes32 hashnum; //function that has same name with contract's //is deprecated constructor(uint256 num) public{ owner = msg.sender; //sha3 is deprecated bytesnum =keccak256(abi.encode(num)); //var is deprecated uint8 a = 0; //block.blockhash is deprecated hashnum = blockhash(num); } //constant is deprecated function getOwner() view public returns(address){ return owner; } function callAnother() public{ bool flag; bytes memory data; (flag, data) = owner.call(""); //callcode and throw are deprecated if(flag){ revert(); } else{ //suicide is deprecated require(msg.sender == owner); selfdestruct(owner); } } fallback () external{ //msg.gas is deprecated uint remainGas = gasleft(); if(remainGas > 2300){ revert(); } } }
callcode and throw are deprecatedsuicide is deprecated
function callAnother() public{ bool flag; bytes memory data; (flag, data) = owner.call(""); if(flag){ revert(); } else{ require(msg.sender == owner); selfdestruct(owner); } }
13,037,777
[ 1, 1991, 710, 471, 604, 854, 6849, 26560, 335, 831, 353, 6849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 745, 37, 24413, 1435, 1071, 95, 203, 3639, 1426, 2982, 31, 203, 3639, 1731, 3778, 501, 31, 203, 3639, 261, 6420, 16, 501, 13, 273, 3410, 18, 1991, 2932, 8863, 203, 3639, 309, 12, 6420, 15329, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 5411, 365, 5489, 8813, 12, 8443, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import './SafeMath.sol'; contract Patron { using SafeMath for uint; // Total patrons on platform uint public numPatrons; // Mapping to keep track of new patrons mapping (address => bool) alreadyRegisteredPatron; // Mapping to get all the Creator ID's patron has subscribed to mapping (address => address[]) Subscriptions; // See implementation of add vs uint // Event flagging a new patron event NewPatron(); // Event for welcome back event WelcomeBackPatron(); modifier isPatronRegistered () { require(alreadyRegisteredPatron[msg.sender], "User not registered!"); _; } // Function to create a new patron from public address and return success function newPatronSignup () public { if (alreadyRegisteredPatron[msg.sender]) { emit WelcomeBackPatron(); } else { alreadyRegisteredPatron[msg.sender] = true; numPatrons = numPatrons.add(1); emit NewPatron(); } } // Function to get total number of creators a patron has subscribed to function getSubscriptionCount() public view isPatronRegistered returns (uint) { return Subscriptions[msg.sender].length; } // Function to get all creators a patron has subscribed to function getSubscriptions() public view isPatronRegistered returns (address[] memory) { return Subscriptions[msg.sender]; } } contract Creator { using SafeMath for uint; // Structure to store data of a creator struct CreatorDatastore { string imageHash; string contentHash; } // Total creators on platform uint public numCreators; // Get all creators for frontend address[] public allCreators; // Mapping to keep track of new creators mapping (address => bool) alreadyRegisteredCreator; // Mapping to get data of a creator mapping (address => CreatorDatastore) CreatorData; // Event flagging a new creator event NewCreator(); // Event for welcome back event WelcomeBackCreator(); modifier isCreatorRegistered () { require(alreadyRegisteredCreator[msg.sender], "Creator not registered!"); _; } // Function to create a new creator from public address and return success function newCreatorSignup () public { if (alreadyRegisteredCreator[msg.sender]) { emit WelcomeBackCreator(); } else { alreadyRegisteredCreator[msg.sender] = true; allCreators.push(msg.sender); numCreators = numCreators.add(1); emit NewCreator(); } } }
Mapping to get data of a creator
mapping (address => CreatorDatastore) CreatorData;
14,070,792
[ 1, 3233, 358, 336, 501, 434, 279, 11784, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 29525, 21191, 13, 29525, 751, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/Math.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "./StationConfig.sol"; import "./Orbit.sol"; import "./SafeToken.sol"; import "./interfaces/IUniverse.sol"; contract Station is ERC20, ReentrancyGuard, Ownable { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; /// @notice Events event AddDebt(uint256 indexed id, uint256 debtShare); event RemoveDebt(uint256 indexed id, uint256 debtShare); event Launch(uint256 indexed id, uint256 loan); event Terminate(uint256 indexed id, address indexed killer, uint256 prize, uint256 left); string public name = "Interest ETH"; string public symbol = "jETH"; uint8 public decimals = 18; IUniverse public universe; struct Position { address orbit; address owner; uint256 debtShare; uint256 leverageVal; } StationConfig public config; mapping (uint256 => Position) public positions; uint256 public nextPositionID = 1; uint256 public glbDebtShare; uint256 public glbDebtVal; uint256 public lastAccrueTime; uint256 public starGate; /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, "not eoa"); _; } constructor( StationConfig _config, IUniverse _universe ) public { config = _config; universe = _universe; lastAccrueTime = now; } /// @dev Add more debt to the global debt pool. modifier accrue(uint256 msgValue) { if (now > lastAccrueTime) { uint256 interest = pendingInterest(msgValue); uint256 toReserve = interest.mul(config.getStarGateBps()).div(10000); starGate = starGate.add(toReserve); glbDebtVal = glbDebtVal.add(interest); if(starGate > 0 && (universe.getHQBaseShare() > 0 || universe.getPlanetETHShare() > 0)){ sendToOperator(starGate); } lastAccrueTime = now; } _; } function sendToOperator(uint256 _starGate) internal { uint256 hqBaseAmount = _starGate.mul(universe.getHQBaseShare()).div(10000); uint256 poolETHAmount = _starGate.mul(universe.getPlanetETHShare()).div(10000); SafeToken.safeTransferETH(universe.getHQBase(), hqBaseAmount); universe.depositETH.value(poolETHAmount)(); starGate = starGate.sub(hqBaseAmount).sub(poolETHAmount); } /// @dev Return the pending interest that will be accrued in the next call. /// @param msgValue Balance value to subtract off address(this).balance when called from payable functions. function pendingInterest(uint256 msgValue) public view returns (uint256) { if (now > lastAccrueTime) { uint256 timePast = now.sub(lastAccrueTime); uint256 balance = address(this).balance.sub(msgValue); uint256 ratePerSec = config.getInterestRate(glbDebtVal, balance); return ratePerSec.mul(glbDebtVal).mul(timePast).div(1e18); } else { return 0; } } /// @dev Return the ETH debt value given the debt share. Be careful of unaccrued interests. /// @param debtShare The debt share to be converted. function debtShareToVal(uint256 debtShare) public view returns (uint256) { if (glbDebtShare == 0) return debtShare; // When there's no share, 1 share = 1 val. return debtShare.mul(glbDebtVal).div(glbDebtShare); } /// @dev Return the debt share for the given debt value. Be careful of unaccrued interests. /// @param debtVal The debt value to be converted. function debtValToShare(uint256 debtVal) public view returns (uint256) { if (glbDebtShare == 0) return debtVal; // When there's no share, 1 share = 1 val. return debtVal.mul(glbDebtShare).div(glbDebtVal); } /// @dev Return ETH value and debt of the given position. Be careful of unaccrued interests. /// @param id The position ID to query. function positionInfo(uint256 id) public view returns (uint256, uint256) { Position storage pos = positions[id]; return (Orbit(pos.orbit).condition(id), debtShareToVal(pos.debtShare)); } /// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests. function totalETH() public view returns (uint256) { return address(this).balance.add(glbDebtVal).sub(starGate); } /// @dev Add more ETH to the bank. Hope to get some good returns. function deposit() external payable accrue(msg.value) nonReentrant { uint256 total = totalETH().sub(msg.value); uint256 share = total == 0 ? msg.value : msg.value.mul(totalSupply()).div(total); _mint(msg.sender, share); } /// @dev Withdraw ETH from the bank by burning the share tokens. function withdraw(uint256 share) external accrue(0) nonReentrant { uint256 amount = share.mul(totalETH()).div(totalSupply()); _burn(msg.sender, share); uint256 profit = amount.sub(share); uint256 referralAmount = profit.mul(universe.getUniverseShare()).div(10000); address payable refferal = universe.getRefferral(); (bool sent, bytes memory data) = refferal.call.value(referralAmount)(""); require(sent, "Failed to transfer"); SafeToken.safeTransferETH(msg.sender, amount.sub(referralAmount)); } /// @dev Create a new farming position to unlock your yield farming potential. /// @param id The ID of the position to unlock the earning. Use ZERO for new position. /// @param orbit The address of the authorized orbit to work for this position. /// @param loan The amount of ETH to borrow from the pool. /// @param maxReturn The max amount of ETH to return to the pool. /// @param data The calldata to pass along to the orbit for more working context. function launch(uint256 id, address orbit, uint256 loan, uint256 maxReturn, uint256 leverageVal, bytes calldata data) external payable onlyEOA accrue(msg.value) nonReentrant { // 1. Sanity check the input position, or add a new position of ID is 0. if (id == 0) { id = nextPositionID++; positions[id].orbit = orbit; positions[id].owner = msg.sender; positions[id].leverageVal = leverageVal; } else { require(id < nextPositionID, "bad position id"); require(positions[id].orbit == orbit, "bad position orbit"); require(positions[id].owner == msg.sender, "not position owner"); } emit Launch(id, loan); // 2. Make sure the orbit can accept more debt and remove the existing debt. require(config.isOrbit(orbit), "not a orbit"); require(loan == 0 || config.acceptDebt(orbit), "orbit not accept more debt"); uint256 debt = _removeDebt(id).add(loan); // 3. Perform the actual work, using a new scope to avoid stack-too-deep errors. uint256 back; { uint256 sendETH = msg.value.add(loan); require(sendETH <= address(this).balance, "insufficient ETH in the bank"); uint256 beforeETH = address(this).balance.sub(sendETH); Orbit(orbit).launch.value(sendETH)(id, msg.sender, debt, data); back = address(this).balance.sub(beforeETH); } // 4. Check and update position debt. uint256 lessDebt = Math.min(debt, Math.min(back, maxReturn)); debt = debt.sub(lessDebt); if (debt > 0) { require(debt >= config.minDebtSize(), "too small debt size"); uint256 condition = Orbit(orbit).condition(id); uint256 launcher = config.launcher(orbit, debt); require(condition.mul(launcher) >= debt.mul(10000), "bad work factor"); _addDebt(id, debt); } // 5. Return excess ETH back. if (back > lessDebt) SafeToken.safeTransferETH(msg.sender, back - lessDebt); } /// @dev Kill the given to the position. Liquidate it immediately if terminator condition is met. /// @param id The position ID to be killed. function terminate(uint256 id) external onlyEOA accrue(0) nonReentrant { // 1. Verify that the position is eligible for liquidation. Position storage pos = positions[id]; require(pos.debtShare > 0, "no debt"); uint256 debt = _removeDebt(id); uint256 condition = Orbit(pos.orbit).condition(id); uint256 terminator = config.terminator(pos.orbit, debt); require(condition.mul(terminator) < debt.mul(10000), "can't liquidate"); // 2. Perform liquidation and compute the amount of ETH received. uint256 beforeETH = address(this).balance; Orbit(pos.orbit).destroy(id, msg.sender); uint256 back = address(this).balance.sub(beforeETH); uint256 prize = back.mul(config.getTerminateBps()).div(10000); uint256 rest = back.sub(prize); // 3. Clear position debt and return funds to liquidator and position owner. if (prize > 0) SafeToken.safeTransferETH(msg.sender, prize); uint256 left = rest > debt ? rest - debt : 0; if (left > 0) SafeToken.safeTransferETH(pos.owner, left); emit Terminate(id, msg.sender, prize, left); } /// @dev Internal function to add the given debt value to the given position. function _addDebt(uint256 id, uint256 debtVal) internal { Position storage pos = positions[id]; uint256 debtShare = debtValToShare(debtVal); pos.debtShare = pos.debtShare.add(debtShare); glbDebtShare = glbDebtShare.add(debtShare); glbDebtVal = glbDebtVal.add(debtVal); emit AddDebt(id, debtShare); } /// @dev Internal function to clear the debt of the given position. Return the debt value. function _removeDebt(uint256 id) internal returns (uint256) { Position storage pos = positions[id]; uint256 debtShare = pos.debtShare; if (debtShare > 0) { uint256 debtVal = debtShareToVal(debtShare); pos.debtShare = 0; glbDebtShare = glbDebtShare.sub(debtShare); glbDebtVal = glbDebtVal.sub(debtVal); emit RemoveDebt(id, debtShare); return debtVal; } else { return 0; } } /// @dev Update bank configuration to a new address. Must only be called by owner. /// @param _config The new configurator address. function updateConfig(StationConfig _config) external onlyOwner { config = _config; } /// @dev Withdraw ETH reserve for underwater positions to the given address. /// @param to The address to transfer ETH to. /// @param value The number of ETH tokens to withdraw. Must not exceed `starGate`. function withdrawReserve(address to, uint256 value) external onlyOwner nonReentrant { starGate = starGate.sub(value); SafeToken.safeTransferETH(to, value); } /// @dev Reduce ETH reserve, effectively giving them to the depositors. /// @param value The number of ETH reserve to reduce. function reduceReserve(uint256 value) external onlyOwner { starGate = starGate.sub(value); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } /// @dev Fallback function to accept ETH. Orbits will send ETH back the pool. function() external payable {} }
@dev Kill the given to the position. Liquidate it immediately if terminator condition is met. @param id The position ID to be killed. 1. Verify that the position is eligible for liquidation. 2. Perform liquidation and compute the amount of ETH received. 3. Clear position debt and return funds to liquidator and position owner.
function terminate(uint256 id) external onlyEOA accrue(0) nonReentrant { Position storage pos = positions[id]; require(pos.debtShare > 0, "no debt"); uint256 debt = _removeDebt(id); uint256 condition = Orbit(pos.orbit).condition(id); uint256 terminator = config.terminator(pos.orbit, debt); require(condition.mul(terminator) < debt.mul(10000), "can't liquidate"); uint256 beforeETH = address(this).balance; Orbit(pos.orbit).destroy(id, msg.sender); uint256 back = address(this).balance.sub(beforeETH); uint256 prize = back.mul(config.getTerminateBps()).div(10000); uint256 rest = back.sub(prize); if (prize > 0) SafeToken.safeTransferETH(msg.sender, prize); uint256 left = rest > debt ? rest - debt : 0; if (left > 0) SafeToken.safeTransferETH(pos.owner, left); emit Terminate(id, msg.sender, prize, left); }
12,836,960
[ 1, 19045, 326, 864, 358, 326, 1754, 18, 511, 18988, 350, 340, 518, 7636, 309, 24965, 2269, 353, 5100, 18, 225, 612, 1021, 1754, 1599, 358, 506, 24859, 18, 404, 18, 8553, 716, 326, 1754, 353, 21351, 364, 4501, 26595, 367, 18, 576, 18, 11217, 4501, 26595, 367, 471, 3671, 326, 3844, 434, 512, 2455, 5079, 18, 890, 18, 10121, 1754, 18202, 88, 471, 327, 284, 19156, 358, 4501, 26595, 639, 471, 1754, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10850, 12, 11890, 5034, 612, 13, 3903, 1338, 41, 28202, 4078, 86, 344, 12, 20, 13, 1661, 426, 8230, 970, 288, 203, 3639, 11010, 2502, 949, 273, 6865, 63, 350, 15533, 203, 3639, 2583, 12, 917, 18, 323, 23602, 9535, 405, 374, 16, 315, 2135, 18202, 88, 8863, 203, 3639, 2254, 5034, 18202, 88, 273, 389, 4479, 758, 23602, 12, 350, 1769, 203, 3639, 2254, 5034, 2269, 273, 2965, 3682, 12, 917, 18, 280, 3682, 2934, 4175, 12, 350, 1769, 203, 3639, 2254, 5034, 24965, 273, 642, 18, 9505, 639, 12, 917, 18, 280, 3682, 16, 18202, 88, 1769, 203, 3639, 2583, 12, 4175, 18, 16411, 12, 9505, 639, 13, 411, 18202, 88, 18, 16411, 12, 23899, 3631, 315, 4169, 1404, 4501, 26595, 340, 8863, 203, 3639, 2254, 5034, 1865, 1584, 44, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 2965, 3682, 12, 917, 18, 280, 3682, 2934, 11662, 12, 350, 16, 1234, 18, 15330, 1769, 203, 3639, 2254, 5034, 1473, 273, 1758, 12, 2211, 2934, 12296, 18, 1717, 12, 5771, 1584, 44, 1769, 203, 3639, 2254, 5034, 846, 554, 273, 1473, 18, 16411, 12, 1425, 18, 588, 26106, 38, 1121, 1435, 2934, 2892, 12, 23899, 1769, 203, 3639, 2254, 5034, 3127, 273, 1473, 18, 1717, 12, 683, 554, 1769, 203, 3639, 309, 261, 683, 554, 405, 374, 13, 14060, 1345, 18, 4626, 5912, 1584, 44, 12, 3576, 18, 15330, 16, 846, 554, 1769, 203, 3639, 2254, 5034, 2002, 273, 3127, 405, 18202, 88, 692, 3127, 300, 18202, 88, 294, 374, 2 ]
// Copyright (C) 2020 Easy Chain. <https://easychain.tech> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; pragma solidity 0.6.5; import { Ownable } from "../Ownable.sol"; import { ERC20 } from "../ERC20.sol"; /** * @dev BerezkaPriceOverride contract. * This contract allows to override token prices from 1inch exchange to correctly * adjust prices of composite tokens not yet supported by Zerion * @author Vasin Denis <denis.vasin@easychain.tech> */ contract BerezkaPriceOverride is Ownable() { mapping(address => uint256) public prices; mapping(address => address) public tokens; /** * Sets price (in USDC, i.e. decimals = 6) for a given token. 0 indicates no price override. * Sets price for a (decimals) amount single token of _token in USDC */ function setPrice( address _token, uint256 _price ) public onlyOwner() { require(_token != address(0)); prices[_token] = _price; } /** * Sets Token override */ function setToken( address _from, address _to ) public onlyOwner() { require(_to != address(0), "Should not be empty token"); tokens[_from] = _to; } function removeToken( address _from ) public onlyOwner() { delete tokens[_from]; } function computePrice( address _token, uint256 _amount ) public view returns (uint256) { uint256 decimals = ERC20(_token).decimals(); uint256 price = prices[_token]; return _amount * price / 10 ** decimals; } function hasOverride( address _token ) public view returns (bool) { return prices[_token] != 0; } function replaceToken( address _token, int256 _amount ) public view returns (address, int256) { address targetAddress = tokens[_token]; uint256 sourceDecimals = ERC20(_token).decimals(); uint256 targetDecimals = ERC20(targetAddress).decimals(); int256 adjustedAmount = _amount; if (sourceDecimals > targetDecimals) { adjustedAmount = _amount / int256((10 ** (sourceDecimals - targetDecimals))); } else { adjustedAmount = _amount * int256((10 ** (targetDecimals - sourceDecimals))); } return (targetAddress, adjustedAmount); } function hasTokenOverride( address _token ) public view returns (bool) { return tokens[_token] != address(0); } }
* @dev BerezkaPriceOverride contract. This contract allows to override token prices from 1inch exchange to correctly adjust prices of composite tokens not yet supported by Zerion @author Vasin Denis <denis.vasin@easychain.tech>/
contract BerezkaPriceOverride is Ownable() { mapping(address => uint256) public prices; mapping(address => address) public tokens; function setPrice( address _token, uint256 _price ) public onlyOwner() import { Ownable } from "../Ownable.sol"; import { ERC20 } from "../ERC20.sol"; { require(_token != address(0)); prices[_token] = _price; } function setToken( address _from, address _to ) public onlyOwner() { require(_to != address(0), "Should not be empty token"); tokens[_from] = _to; } function removeToken( address _from ) public onlyOwner() { delete tokens[_from]; } function computePrice( address _token, uint256 _amount ) public view returns (uint256) { uint256 decimals = ERC20(_token).decimals(); uint256 price = prices[_token]; return _amount * price / 10 ** decimals; } function hasOverride( address _token ) public view returns (bool) { return prices[_token] != 0; } function replaceToken( address _token, int256 _amount ) public view returns (address, int256) { address targetAddress = tokens[_token]; uint256 sourceDecimals = ERC20(_token).decimals(); uint256 targetDecimals = ERC20(targetAddress).decimals(); int256 adjustedAmount = _amount; if (sourceDecimals > targetDecimals) { adjustedAmount = _amount / int256((10 ** (sourceDecimals - targetDecimals))); adjustedAmount = _amount * int256((10 ** (targetDecimals - sourceDecimals))); } return (targetAddress, adjustedAmount); } function replaceToken( address _token, int256 _amount ) public view returns (address, int256) { address targetAddress = tokens[_token]; uint256 sourceDecimals = ERC20(_token).decimals(); uint256 targetDecimals = ERC20(targetAddress).decimals(); int256 adjustedAmount = _amount; if (sourceDecimals > targetDecimals) { adjustedAmount = _amount / int256((10 ** (sourceDecimals - targetDecimals))); adjustedAmount = _amount * int256((10 ** (targetDecimals - sourceDecimals))); } return (targetAddress, adjustedAmount); } } else { function hasTokenOverride( address _token ) public view returns (bool) { return tokens[_token] != address(0); } }
1,825,490
[ 1, 38, 822, 94, 7282, 5147, 6618, 6835, 18, 1220, 6835, 5360, 358, 3849, 1147, 19827, 628, 404, 267, 343, 7829, 358, 8783, 5765, 19827, 434, 9635, 2430, 486, 4671, 3260, 635, 2285, 264, 285, 225, 776, 345, 267, 22453, 291, 411, 13002, 291, 18, 4423, 267, 36, 73, 15762, 5639, 18, 28012, 16893, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 822, 94, 7282, 5147, 6618, 353, 14223, 6914, 1435, 288, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 19827, 31, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 2430, 31, 203, 203, 565, 445, 444, 5147, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 8694, 203, 565, 262, 7010, 3639, 1071, 203, 3639, 1338, 5541, 1435, 203, 203, 5666, 288, 14223, 6914, 289, 628, 315, 6216, 5460, 429, 18, 18281, 14432, 203, 5666, 288, 4232, 39, 3462, 289, 628, 315, 6216, 654, 39, 3462, 18, 18281, 14432, 203, 565, 288, 203, 3639, 2583, 24899, 2316, 480, 1758, 12, 20, 10019, 203, 203, 3639, 19827, 63, 67, 2316, 65, 273, 389, 8694, 31, 203, 565, 289, 203, 203, 565, 445, 22629, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 203, 565, 262, 7010, 3639, 1071, 203, 3639, 1338, 5541, 1435, 203, 565, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 3631, 315, 14309, 486, 506, 1008, 1147, 8863, 203, 3639, 2430, 63, 67, 2080, 65, 273, 389, 869, 31, 203, 565, 289, 203, 203, 565, 445, 1206, 1345, 12, 203, 3639, 1758, 389, 2080, 203, 565, 262, 7010, 3639, 1071, 203, 3639, 1338, 5541, 1435, 203, 565, 288, 203, 3639, 1430, 2430, 63, 67, 2080, 15533, 203, 565, 289, 203, 203, 565, 445, 3671, 5147, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 7010, 3639, 1071, 203, 3639, 1476, 203, 2 ]
./full_match/1/0xbF0972e87938483A02A0aB96F0d86e50C4dD1A11/sources/browser/MasterChef_all.sol
CREED tokens created per block.
uint256 public creedPerBlock;
4,877,987
[ 1, 5458, 2056, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1519, 329, 2173, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.1; pragma experimental ABIEncoderV2; import "../ZeroOne/UserGroups/lib/UserGroup.sol"; /** * @title UserGroupMock * @dev mock for testing UserGroup lib */ contract UserGroupMock { using UserGroup for UserGroup.Group; UserGroup.Group group; constructor(UserGroup.Group memory _group) public { require(_group.validate(), "Incorrect UserGroup"); group = _group; } /** * @dev method for testing getAdmin() method of user group * @return admin */ function testGetAdmin() public view returns(address admin) { return group.getAdmin(); } /** * @dev method for testing getAdmin() method of user group * @return totalSupply */ function testGetTotalSupply() public view returns(uint256 totalSupply) { return group.getTotalSupply(); } }
* @dev method for testing getAdmin() method of user group @return admin/
function testGetAdmin() public view returns(address admin) { return group.getAdmin(); }
990,489
[ 1, 2039, 364, 7769, 22501, 1435, 707, 434, 729, 1041, 327, 3981, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 967, 4446, 1435, 7010, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 12, 2867, 3981, 13, 203, 565, 288, 203, 3639, 327, 1041, 18, 588, 4446, 5621, 203, 565, 289, 7010, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x472D40b3138b9f55f5eD8fcEEe5130321D2552E8/sources/Connector.sol
CORE CONNECTION CoreVault coreContract = CoreVault(_addresses[0]); NFund fund = NFund(fundAddress); if (keccak256(bytes(functionName)) == keccak256(bytes("deposit"))) { fund.approveSpendERC20(_addresses[1], integers[0]); coreContract.deposit(integers[1], integers[2]); } if (keccak256(bytes(functionName)) == keccak256(bytes("depositFor"))) { coreContract.deposit(integers[0], integers[1]); } if (keccak256(bytes(functionName)) == keccak256(bytes("setAllowanceForPoolToken"))) { fund.approveSpendERC20(_addresses[1], integers[0]); coreContract.deposit(integers[1], integers[2]); } if (keccak256(bytes(functionName)) == keccak256(bytes("withdrawFrom"))) { coreContract.withdrawFrom(_addresses[1], integers[0], integers[1]); } if (keccak256(bytes(functionName)) == keccak256(bytes("withdraw"))) { coreContract.withdraw(integers[0], integers[1]); } if (keccak256(bytes(functionName)) == keccak256(bytes("emergencyWithdraw"))) { coreContract.emergencyWithdraw(integers[0]); }
function interfaceCore(string memory functionCode, string memory functionName, address[] memory _addresses, uint256[] memory integers, string[] memory strings, bytes[] memory bytesArr) internal { }
2,872,832
[ 1, 15715, 20695, 4586, 12003, 2922, 8924, 273, 4586, 12003, 24899, 13277, 63, 20, 19226, 423, 42, 1074, 284, 1074, 273, 423, 42, 1074, 12, 74, 1074, 1887, 1769, 309, 261, 79, 24410, 581, 5034, 12, 3890, 12, 915, 461, 3719, 422, 417, 24410, 581, 5034, 12, 3890, 2932, 323, 1724, 6, 20349, 288, 377, 284, 1074, 18, 12908, 537, 27223, 654, 39, 3462, 24899, 13277, 63, 21, 6487, 12321, 63, 20, 19226, 377, 2922, 8924, 18, 323, 1724, 12, 14970, 414, 63, 21, 6487, 12321, 63, 22, 19226, 289, 309, 261, 79, 24410, 581, 5034, 12, 3890, 12, 915, 461, 3719, 422, 417, 24410, 581, 5034, 12, 3890, 2932, 323, 1724, 1290, 6, 20349, 288, 377, 2922, 8924, 18, 323, 1724, 12, 14970, 414, 63, 20, 6487, 12321, 63, 21, 19226, 289, 309, 261, 79, 24410, 581, 5034, 12, 3890, 12, 915, 461, 3719, 422, 417, 24410, 581, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1560, 4670, 12, 1080, 3778, 445, 1085, 16, 533, 3778, 14117, 16, 1758, 8526, 3778, 389, 13277, 16, 2254, 5034, 8526, 3778, 12321, 16, 533, 8526, 3778, 2064, 16, 1731, 8526, 3778, 1731, 5715, 13, 2713, 288, 203, 565, 289, 203, 1377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./ERC1155MixedFungible.sol"; import "./ERC1155Metadata_URI.sol"; import "./ERC1155URIProvider.sol"; import "./IERC1155Mintable.sol"; import "./Operators.sol"; import "./ERC20.sol"; import "./ERC721.sol"; import "./MintCallbackInterface.sol"; /** @title Blockchain Cuties Collectible contract. @dev Mixed Fungible Mintable form of ERC1155 Shows how easy it is to mint new items */ contract BlockchainCutiesERC1155 is ERC1155MixedFungible, Operators, ERC1155Metadata_URI, IERC1155Mintable { mapping (uint256 => uint256) public maxIndex; mapping(uint256 => ERC721) public proxy721; mapping(uint256 => ERC20) public proxy20; mapping(uint256 => bool) public disallowSetProxy721; mapping(uint256 => bool) public disallowSetProxy20; ERC1155URIProvider public uriProvider; MintCallbackInterface public mintCallback; bytes4 constant private INTERFACE_SIGNATURE_ERC1155_URI = 0x0e89341c; function supportsInterface(bytes4 _interfaceId) public view returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == INTERFACE_SIGNATURE_ERC1155_URI; } // This function only creates the type. // _type must be shifted by 128 bits left // for NFT TYPE_NF_BIT should be added to _type function create(uint256 _type) onlyOwner external { // emit a Transfer event with Create semantic to help with discovery. emit TransferSingle(msg.sender, address(0x0), address(0x0), _type, 0); } function setMintCallback(MintCallbackInterface _newCallback) external onlyOwner { mintCallback = _newCallback; } function mintNonFungibleSingleShort(uint128 _type, address _to) external onlyOperator { uint tokenType = (uint256(_type) << 128) | (1 << 255); _mintNonFungibleSingle(tokenType, _to); } function mintNonFungibleSingle(uint256 _type, address _to) external onlyOperator { // No need to check this is a nf type require(isNonFungible(_type), "ERC1155: unknown NFT token type"); require(getNonFungibleIndex(_type) == 0, "ERC1155: unknown NFT token type"); _mintNonFungibleSingle(_type, _to); } function _mintNonFungibleSingle(uint256 _type, address _to) internal { // Index are 1-based. uint256 index = maxIndex[_type] + 1; uint256 id = _type | index; nfOwners[id] = _to; onTransferNft(address(0x0), _to, id); balances[_type][_to] = balances[_type][_to].add(1); emit TransferSingle(msg.sender, address(0x0), _to, id, 1); maxIndex[_type] = maxIndex[_type].add(1); if (address(mintCallback) != address(0)) { mintCallback.onMint(id); } if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, _to, id, 1, ''); } } function mintNonFungibleShort(uint128 _type, address[] calldata _to) external onlyOperator { uint tokenType = (uint256(_type) << 128) | (1 << 255); _mintNonFungible(tokenType, _to); } function mintNonFungible(uint256 _type, address[] calldata _to) external onlyOperator { // No need to check this is a nf type require(isNonFungible(_type), "ERC1155: token is not non-fungible"); _mintNonFungible(_type, _to); } function _mintNonFungible(uint256 _type, address[] memory _to) internal { // Index are 1-based. uint256 index = maxIndex[_type] + 1; for (uint256 i = 0; i < _to.length; ++i) { address dst = _to[i]; uint256 id = _type | index + i; nfOwners[id] = dst; onTransferNft(address(0x0), dst, id); balances[_type][dst] = balances[_type][dst].add(1); emit TransferSingle(msg.sender, address(0x0), dst, id, 1); if (address(mintCallback) != address(0)) { mintCallback.onMint(id); } if (dst.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, dst, id, 1, ''); } } maxIndex[_type] = _to.length.add(maxIndex[_type]); } function mintFungibleSingle(uint256 _id, address _to, uint256 _quantity) external onlyOperator { require(isFungible(_id), "ERC1155: token is not fungible"); // Grant the items to the caller balances[_id][_to] = _quantity.add(balances[_id][_to]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), _to, _id, _quantity); onTransfer20(address(0x0), _to, _id, _quantity); if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, _to, _id, _quantity, ''); } } function mintFungible(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external onlyOperator { require(isFungible(_id), "ERC1155: token is not fungible"); for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 quantity = _quantities[i]; // Grant the items to the caller balances[_id][to] = quantity.add(balances[_id][to]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); onTransfer20(address(0x0), to, _id, quantity); if (to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, ''); } } } function setURI(string calldata _uri, uint256 _id) external onlyOperator { emit URI(_uri, _id); } function setUriProvider(ERC1155URIProvider _uriProvider) onlyOwner external { uriProvider = _uriProvider; } function uri(uint256 _id) external view returns (string memory) { return uriProvider.uri(_id); } function withdraw() external onlyOwner { if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } function withdrawERC20(ERC20 _tokenContract) external onlyOwner { uint256 balance = _tokenContract.balanceOf(address(this)); if (balance > 0) { _tokenContract.transfer(msg.sender, balance); } } function approveERC721(ERC721 _tokenContract) external onlyOwner { _tokenContract.setApprovalForAll(msg.sender, true); } function totalSupplyNonFungible(uint256 _type) view external returns (uint256) { // No need to check this is a nf type require(isNonFungible(_type), "ERC1155: token type is not non-fungible"); return maxIndex[_type]; } function totalSupplyNonFungibleShort(uint128 _type) view external returns (uint256) { uint tokenType = (uint256(_type) << 128) | (1 << 255); return maxIndex[tokenType]; } function setProxy721(uint256 nftType, ERC721 proxy) external onlyOwner { require(!disallowSetProxy721[nftType], "ERC1155-ERC721: token setup forbidden"); proxy721[nftType] = proxy; } // @dev can be only disabled. There is not way to enable later. function disableSetProxy721(uint256 nftType) external onlyOwner { disallowSetProxy721[nftType] = true; } function setProxy20(uint256 _type, ERC20 proxy) external onlyOwner { require(!disallowSetProxy20[_type], "ERC1155-ERC20: token setup forbidden"); proxy20[_type] = proxy; } // @dev can be only disabled. There is not way to enable later. function disableSetProxy20(uint256 _type) external onlyOwner { disallowSetProxy20[_type] = true; } /** * @dev Transfer token when proxy contract transfer is called * @param _from address representing the previous owner of the given token ID * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address * @param _data bytes some arbitrary data */ function proxyTransfer721(address _from, address _to, uint256 _tokenId, bytes calldata _data) external { uint256 nftType = getNFTType(_tokenId); ERC721 proxy = proxy721[nftType]; require(msg.sender == address(proxy), "ERC1155-ERC721: caller is not token contract"); require(_ownerOf(_tokenId) == _from, "ERC1155-ERC721: cannot transfer token to itself"); // gives approval for proxy token contracts operatorApproval[_from][address(proxy)] = true; safeTransferFrom(_from, _to, _tokenId, 1, _data); } // override function onTransferNft(address _from, address _to, uint256 _tokenId) internal { uint256 nftType = getNFTType(_tokenId); uint256 nftIndex = getNonFungibleIndex(_tokenId); ERC721 proxy = proxy721[nftType]; // if a token has proxy contract call onTransfer if (address(proxy) != address(0x0)) { proxy.onTransfer(_from, _to, nftIndex); } } function proxyTransfer20(address _from, address _to, uint256 _tokenId, uint256 _value) external { ERC20 proxy = proxy20[_tokenId]; require(msg.sender == address(proxy), "ERC1155-ERC20: caller is not token contract"); require(_to != address(0x0), "ERC1155-ERC20: cannot send to zero address"); balances[_tokenId][_from] = balances[_tokenId][_from].sub(_value); balances[_tokenId][_to] = balances[_tokenId][_to].add(_value); emit TransferSingle(msg.sender, _from, _to, _tokenId, _value); onTransfer20(_from, _to, _tokenId, _value); } // override function onTransfer20(address _from, address _to, uint256 _tokenId, uint256 _value) internal { ERC20 proxy = proxy20[_tokenId]; // if a token has proxy contract call onTransfer if (address(proxy) != address(0x0)) { proxy.onTransfer(_from, _to, _value); } } // override function burn(address _from, uint256 _id, uint256 _value) external { require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "ERC1155: Need operator approval for 3rd party transfers."); address to = address(0x0); if (isNonFungible(_id)) { require(nfOwners[_id] == _from, "ERC1155: not a token owner"); nfOwners[_id] = to; onTransferNft(_from, to, _id); uint256 baseType = getNonFungibleBaseType(_id); balances[baseType][_from] = balances[baseType][_from].sub(_value); balances[baseType][to] = balances[baseType][to].add(_value); } else { onTransfer20(_from, to, _id, _value); balances[_id][_from] = balances[_id][_from].sub(_value); balances[_id][to] = balances[_id][to].add(_value); } emit TransferSingle(msg.sender, _from, to, _id, _value); } }
Grant the items to the caller Emit the Transfer/Mint event. the 0x0 source address implies a mint It will also provide the circulating supply info.
function mintFungible(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external onlyOperator { require(isFungible(_id), "ERC1155: token is not fungible"); for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 quantity = _quantities[i]; balances[_id][to] = quantity.add(balances[_id][to]); emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); onTransfer20(address(0x0), to, _id, quantity); if (to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, ''); } } }
1,119,868
[ 1, 9021, 326, 1516, 358, 326, 4894, 16008, 326, 12279, 19, 49, 474, 871, 18, 326, 374, 92, 20, 1084, 1758, 24168, 279, 312, 474, 2597, 903, 2546, 5615, 326, 5886, 1934, 1776, 14467, 1123, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 42, 20651, 1523, 12, 11890, 5034, 389, 350, 16, 1758, 8526, 745, 892, 389, 869, 16, 2254, 5034, 8526, 745, 892, 389, 17753, 1961, 13, 3903, 1338, 5592, 288, 203, 3639, 2583, 12, 291, 42, 20651, 1523, 24899, 350, 3631, 315, 654, 39, 2499, 2539, 30, 1147, 353, 486, 9831, 75, 1523, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 869, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 1758, 358, 273, 389, 869, 63, 77, 15533, 203, 5411, 2254, 5034, 10457, 273, 389, 17753, 1961, 63, 77, 15533, 203, 203, 5411, 324, 26488, 63, 67, 350, 6362, 869, 65, 273, 10457, 18, 1289, 12, 70, 26488, 63, 67, 350, 6362, 869, 19226, 203, 203, 5411, 3626, 12279, 5281, 12, 3576, 18, 15330, 16, 1758, 12, 20, 92, 20, 3631, 358, 16, 389, 350, 16, 10457, 1769, 203, 5411, 603, 5912, 3462, 12, 2867, 12, 20, 92, 20, 3631, 358, 16, 389, 350, 16, 10457, 1769, 203, 203, 5411, 309, 261, 869, 18, 291, 8924, 10756, 288, 203, 7734, 389, 2896, 9890, 5912, 5933, 1359, 1564, 12, 3576, 18, 15330, 16, 1234, 18, 15330, 16, 358, 16, 389, 350, 16, 10457, 16, 23489, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "./IFoxGame.sol"; import "./IFoxGameCarrot.sol"; import "./IFoxGameCrown.sol"; import "./IFoxGameNFT.sol"; contract FoxGames_v3 is IFoxGame, OwnableUpgradeable, IERC721ReceiverUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { using ECDSAUpgradeable for bytes32; // signature verification helpers using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; // iterable staked tokens /**** * Thanks for checking out our contracts. * If you're interested in working with us, you can find us on * discord (https://discord.gg/foxgame). We also have a bug bounty * program and are available at @officialfoxgame or [email protected] ***/ // Advantage score adjustments for both foxes and hunters uint8 public constant MAX_ADVANTAGE = 8; uint8 public constant MIN_ADVANTAGE = 5; // Foxes take a 40% tax on all rabbiot $CARROT claimed uint8 public constant RABBIT_CLAIM_TAX_PERCENTAGE = 40; // Hunters have a 5% chance of stealing a fox as it unstakes uint8 private hunterStealFoxProbabilityMod; // Cut between hunters and foxes uint8 private hunterTaxCutPercentage; // Total hunter marksman scores staked uint16 public totalMarksmanPointsStaked; // Total fox cunning scores staked uint16 public totalCunningPointsStaked; // Number of Rabbit staked uint32 public totalRabbitsStaked; // Number of Foxes staked uint32 public totalFoxesStaked; // Number of Hunters staked uint32 public totalHuntersStaked; // The last time $CARROT was claimed uint48 public lastClaimTimestamp; // Rabbits must have 2 days worth of $CARROT to unstake or else it's too cold uint48 public constant RABBIT_MINIMUM_TO_EXIT = 2 days; // There will only ever be (roughly) 2.5 billion $CARROT earned through staking uint128 public constant MAXIMUM_GLOBAL_CARROT = 2500000000 ether; // amount of $CARROT earned so far uint128 public totalCarrotEarned; // Collected rewards before any foxes staked uint128 public unaccountedFoxRewards; // Collected rewards before any foxes staked uint128 public unaccountedHunterRewards; // Amount of $CARROT due for each cunning point staked uint128 public carrotPerCunningPoint; // Amount of $CARROT due for each marksman point staked uint128 public carrotPerMarksmanPoint; // Rabbit earn 10000 $CARROT per day uint128 public constant RABBIT_EARNING_RATE = 115740740740740740; // 10000 ether / 1 days; // Hunters earn 20000 $CARROT per day uint128 public constant HUNTER_EARNING_RATE = 231481481481481470; // 20000 ether / 1 days; // Staking state for both time-based and point-based rewards struct TimeStake { uint16 tokenId; uint48 time; address owner; } struct EarningStake { uint16 tokenId; uint128 earningRate; address owner; } // Events event TokenStaked(string kind, uint16 tokenId, address owner); event TokenUnstaked(string kind, uint16 tokenId, address owner, uint128 earnings); event FoxStolen(uint16 foxTokenId, address thief, address victim); // Signature to prove membership and randomness address private signVerifier; // External contract reference IFoxGameNFT private foxNFT; IFoxGameCarrot private foxCarrot; // Staked rabbits mapping(uint16 => TimeStake) public rabbitStakeByToken; // Staked foxes mapping(uint8 => EarningStake[]) public foxStakeByCunning; // foxes grouped by cunning mapping(uint16 => uint16) public foxHierarchy; // fox location within cunning group // Staked hunters mapping(uint16 => TimeStake) public hunterStakeByToken; mapping(uint8 => EarningStake[]) public hunterStakeByMarksman; // hunter grouped by markman mapping(uint16 => uint16) public hunterHierarchy; // hunter location within marksman group // FoxGame membership date mapping(address => uint48) public membershipDate; mapping(address => uint32) public memberNumber; event MemberJoined(address member, uint32 memberCount); uint32 public membershipCount; // External contract reference IFoxGameNFT private foxNFTGen1; // Mapping for staked tokens mapping(address => EnumerableSetUpgradeable.UintSet) private _stakedTokens; // Bool to store staking data bool private _storeStaking; // Use seed instead uint256 private _seed; // Reference to phase 2 utility token IFoxGameCrown private foxCrown; // amount of $CROWN earned so far uint128 public totalCrownEarned; // Cap CROWN earnings after 2.5 billion has been distributed uint128 public constant MAXIMUM_GLOBAL_CROWN = 2500000000 ether; // Entropy storage for future events that require randomness (claim, unstake). // Address => OP (claim/unstake) => TokenID => BlockNumber mapping(address => mapping(uint8 => mapping(uint16 => uint32))) private _stakeClaimBlock; // Op keys for Entropy storage uint8 private constant UNSTAKE_AND_CLAIM_IDX = 0; uint8 private constant CLAIM_IDX = 1; // Cost of a barrel in CARROT uint256 public barrelPrice; // Track account purchase of barrels mapping(address => uint48) private barrelPurchaseDate; // Barrel event purchase event BarrelPurchase(address account, uint256 price, uint48 timestamp); // Date when corruption begins to spread... 2 things happen: // 1. Carrot begins to burning // 2. Game risks go up uint48 public corruptionStartDate; // The last time $CROWN was claimed uint48 public lastCrownClaimTimestamp; // Phase 2 start date with 3 meanings: // - the date carrot will no long accrue rewards // - the date crown will start acruing rewards // - the start of a 24-hour countdown for corruption uint48 public divergenceTime; // Corruption percent rate per second uint128 public constant CORRUPTION_BURN_PERCENT_RATE = 1157407407407; // 10% burned per day // Events for token claiming in phase 2 event ClaimCarrot(IFoxGameNFT.Kind, uint16 tokenId, address owner, uint128 reward, uint128 corruptedCarrot); event CrownClaimed(string kind, uint16 tokenId, address owner, bool unstake, uint128 reward, uint128 tax, bool elevatedRisk); // Store a bool per token to ensure we dont double claim carrot mapping(uint16 => bool) private tokenCarrotClaimed; // < Placeholder > uint48 private ___; // Amount of $CROWN due for each cunning point staked uint128 public crownPerCunningPoint; // Amount of $CROWN due for each marksman point staked uint128 public crownPerMarksmanPoint; // Indicator of which users are still grandfathered into the ground floor of // $CROWN earnings. mapping(uint16 => bool) private hasRecentEarningPoint; /** * Set the date for phase 2 launch. * @param timestamp Timestamp */ function setDivergenceTime(uint48 timestamp) external onlyOwner { divergenceTime = timestamp; } /** * Init contract upgradability (only called once). */ function initialize() public initializer { __Ownable_init(); __ReentrancyGuard_init(); __Pausable_init(); hunterStealFoxProbabilityMod = 20; // 100/5=20 hunterTaxCutPercentage = 30; // whole number % // Pause staking on init _pause(); } /** * Returns the corruption start date. */ function getCorruptionEnabled() external view returns (bool) { return corruptionStartDate != 0 && corruptionStartDate < block.timestamp; } /** * Sets the date when corruption will begin to destroy carrot. * @param timestamp time. */ function setCorruptionStartTime(uint48 timestamp) external onlyOwner { corruptionStartDate = timestamp; } /** * Helper functions for validating random seeds. */ function getClaimSigningHash(address recipient, uint16[] calldata tokenIds, bool unstake, uint32[] calldata blocknums, uint256[] calldata seeds) public pure returns (bytes32) { return keccak256(abi.encodePacked(recipient, tokenIds, unstake, blocknums, seeds)); } function getMintSigningHash(address recipient, uint8 token, uint32 blocknum, uint256 seed) public pure returns (bytes32) { return keccak256(abi.encodePacked(recipient, token, blocknum, seed)); } function isValidMintSignature(address recipient, uint8 token, uint32 blocknum, uint256 seed, bytes memory sig) public view returns (bool) { bytes32 message = getMintSigningHash(recipient, token, blocknum, seed).toEthSignedMessageHash(); return ECDSAUpgradeable.recover(message, sig) == signVerifier; } function isValidClaimSignature(address recipient, uint16[] calldata tokenIds, bool unstake, uint32[] calldata blocknums, uint256[] calldata seeds, bytes memory sig) public view returns (bool) { bytes32 message = getClaimSigningHash(recipient, tokenIds, unstake, blocknums, seeds).toEthSignedMessageHash(); return ECDSAUpgradeable.recover(message, sig) == signVerifier; } /** * Set the purchase price of Barrels. * @param price Cost in CARROT */ function setBarrelPrice(uint256 price) external onlyOwner { barrelPrice = price; } /** * Allow accounts to purchase barrels using CARROT. */ function purchaseBarrel() external nonReentrant { require(tx.origin == msg.sender, "eos"); require(barrelPurchaseDate[msg.sender] == 0, "one barrel per account"); barrelPurchaseDate[msg.sender] = uint48(block.timestamp); foxCarrot.burn(msg.sender, barrelPrice); emit BarrelPurchase(msg.sender, barrelPrice, uint48(block.timestamp)); } /** * Exposes user barrel purchase date. * @param account Account to query. */ function ownsBarrel(address account) external view returns (bool) { return barrelPurchaseDate[account] != 0; } /** * Return the appropriate contract interface for token. */ function getTokenContract(uint16 tokenId) private view returns (IFoxGameNFT) { return tokenId <= 10000 ? foxNFT : foxNFTGen1; } /** * Helper method to fetch rotating entropy used to generate random seeds off-chain. * @param tokenIds List of token IDs. * @return entropies List of stored blocks per token. */ function getEntropies(address recipient, uint16[] calldata tokenIds) external view returns (uint32[2][] memory entropies) { require(tx.origin == msg.sender, "eos"); entropies = new uint32[2][](tokenIds.length); for (uint8 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; entropies[i] = [ _stakeClaimBlock[recipient][UNSTAKE_AND_CLAIM_IDX][tokenId], _stakeClaimBlock[recipient][CLAIM_IDX][tokenId] ]; } } /** * Adds Rabbits, Foxes and Hunters to their respective safe homes. * @param account the address of the staker * @param tokenIds the IDs of the Rabbit and Foxes to stake */ function stakeTokens(address account, uint16[] calldata tokenIds) external nonReentrant _updateEarnings { require((account == msg.sender && tx.origin == msg.sender) || msg.sender == address(foxNFTGen1), "not approved"); IFoxGameNFT nftContract; uint32 blocknum = uint32(block.number); mapping(uint16 => uint32) storage senderUnstakeBlock = _stakeClaimBlock[msg.sender][UNSTAKE_AND_CLAIM_IDX]; for (uint16 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; // Thieves abound and leave minting gaps if (tokenId == 0) { continue; } // Set unstake entropy senderUnstakeBlock[tokenId] = blocknum; // Add to respective safe homes nftContract = getTokenContract(tokenId); IFoxGameNFT.Kind kind = _getKind(nftContract, tokenId); if (kind == IFoxGameNFT.Kind.RABBIT) { _addRabbitToKeep(account, tokenId); } else if (kind == IFoxGameNFT.Kind.FOX) { _addFoxToDen(nftContract, account, tokenId); } else { // HUNTER _addHunterToCabin(nftContract, account, tokenId); } // Transfer into safe house if (msg.sender != address(foxNFTGen1)) { // dont do this step if its a mint + stake require(nftContract.ownerOf(tokenId) == msg.sender, "not owner"); nftContract.transferFrom(msg.sender, address(this), tokenId); } } } /** * Adds Rabbit to the Keep. * @param account the address of the staker * @param tokenId the ID of the Rabbit to add to the Barn */ function _addRabbitToKeep(address account, uint16 tokenId) internal { rabbitStakeByToken[tokenId] = TimeStake({ owner: account, tokenId: tokenId, time: uint48(block.timestamp) }); totalRabbitsStaked += 1; emit TokenStaked("RABBIT", tokenId, account); } /** * Add Fox to the Den. * @param account the address of the staker * @param tokenId the ID of the Fox */ function _addFoxToDen(IFoxGameNFT nftContract, address account, uint16 tokenId) internal { uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); totalCunningPointsStaked += cunningIndex; // Store fox by rating foxHierarchy[tokenId] = uint16(foxStakeByCunning[cunningIndex].length); // Add fox to their cunning group foxStakeByCunning[cunningIndex].push(EarningStake({ owner: account, tokenId: tokenId, earningRate: crownPerCunningPoint })); // Phase 2 - Mark earning point as valid hasRecentEarningPoint[tokenId] = true; totalFoxesStaked += 1; emit TokenStaked("FOX", tokenId, account); } /** * Adds Hunter to the Cabin. * @param account the address of the staker * @param tokenId the ID of the Hunter */ function _addHunterToCabin(IFoxGameNFT nftContract, address account, uint16 tokenId) internal { uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId); totalMarksmanPointsStaked += marksmanIndex; // Store hunter by rating hunterHierarchy[tokenId] = uint16(hunterStakeByMarksman[marksmanIndex].length); // Add hunter to their marksman group hunterStakeByMarksman[marksmanIndex].push(EarningStake({ owner: account, tokenId: tokenId, earningRate: crownPerMarksmanPoint })); hunterStakeByToken[tokenId] = TimeStake({ owner: account, tokenId: tokenId, time: uint48(block.timestamp) }); // Phase 2 - Mark earning point as valid hasRecentEarningPoint[tokenId] = true; totalHuntersStaked += 1; emit TokenStaked("HUNTER", tokenId, account); } // NB: Param struct is a workaround for too many variables error struct Param { IFoxGameNFT nftContract; uint16 tokenId; bool unstake; uint256 seed; } /** * Realize $CARROT earnings and optionally unstake tokens. * @param tokenIds the IDs of the tokens to claim earnings from * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds * @param blocknums list of blocks each token previously was staked or claimed. * @param seeds random (off-chain) seeds provided for one-time use. * @param sig signature verification. */ function claimRewardsAndUnstake(bool unstake, uint16[] calldata tokenIds, uint32[] calldata blocknums, uint256[] calldata seeds, bytes calldata sig) external nonReentrant _updateEarnings { require(tx.origin == msg.sender, "eos"); require(isValidClaimSignature(msg.sender, tokenIds, unstake, blocknums, seeds, sig), "invalid signature"); require(tokenIds.length == blocknums.length && blocknums.length == seeds.length, "seed mismatch"); // Risk factors bool elevatedRisk = (corruptionStartDate != 0 && corruptionStartDate < block.timestamp) && // corrupted (barrelPurchaseDate[msg.sender] == 0); // does not have barrel // Calculate rewards for each token uint128 reward; mapping(uint16 => uint32) storage senderBlocks = _stakeClaimBlock[msg.sender][unstake ? UNSTAKE_AND_CLAIM_IDX : CLAIM_IDX]; Param memory params; for (uint8 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; // Confirm previous block matches seed generation require(senderBlocks[tokenId] == blocknums[i], "seed not match"); // Set new entropy for next claim (dont bother if unstaking) if (!unstake) { senderBlocks[tokenId] = uint32(block.number); } // NB: Param struct is a workaround for too many variables params.nftContract = getTokenContract(tokenId); params.tokenId = tokenId; params.unstake = unstake; params.seed = seeds[i]; IFoxGameNFT.Kind kind = _getKind(params.nftContract, params.tokenId); if (kind == IFoxGameNFT.Kind.RABBIT) { reward += _claimRabbitsFromKeep(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk); } else if (kind == IFoxGameNFT.Kind.FOX) { reward += _claimFoxFromDen(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk); } else { // HUNTER reward += _claimHunterFromCabin(params.nftContract, params.tokenId, params.unstake); } } // Disburse rewards if (reward != 0) { foxCrown.mint(msg.sender, reward); } } /** * realize $CARROT earnings for a single Rabbit and optionally unstake it * if not unstaking, pay a 20% tax to the staked foxes * if unstaking, there is a 50% chance all $CARROT is stolen * @param nftContract Contract belonging to the token * @param tokenId the ID of the Rabbit to claim earnings from * @param unstake whether or not to unstake the Rabbit * @param seed account seed * @param elevatedRisk true if the user is facing higher risk of losing their token * @return reward - the amount of $CARROT earned */ function _claimRabbitsFromKeep(IFoxGameNFT nftContract, uint16 tokenId, bool unstake, uint256 seed, bool elevatedRisk) internal returns (uint128 reward) { TimeStake storage stake = rabbitStakeByToken[tokenId]; require(stake.owner == msg.sender, "not owner"); uint48 time = uint48(block.timestamp); uint48 stakeStart = stake.time < divergenceTime ? divergenceTime : stake.time; // phase 2 reset require(!(unstake && time - stakeStart < RABBIT_MINIMUM_TO_EXIT), "needs 2 days of crown"); // $CROWN time-based rewards if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward = (time - stakeStart) * RABBIT_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { // stop earning additional $CROWN if it's all been earned reward = (lastCrownClaimTimestamp - stakeStart) * RABBIT_EARNING_RATE; } // Update reward based on game rules uint128 tax; if (unstake) { // Chance of all $CROWN stolen (normal=50% vs corrupted=75%) if (((seed >> 245) % 100) < (elevatedRisk ? 75 : 50)) { _payTaxToPredators(reward, true); tax = reward; reward = 0; } delete rabbitStakeByToken[tokenId]; totalRabbitsStaked -= 1; // send back Rabbit nftContract.safeTransferFrom(address(this), msg.sender, tokenId, ""); } else { // Pay foxes their tax tax = reward * RABBIT_CLAIM_TAX_PERCENTAGE / 100; _payTaxToPredators(tax, false); reward = reward * (100 - RABBIT_CLAIM_TAX_PERCENTAGE) / 100; // Update last earned time rabbitStakeByToken[tokenId] = TimeStake({ owner: msg.sender, tokenId: tokenId, time: time }); } emit CrownClaimed("RABBIT", tokenId, stake.owner, unstake, reward, tax, elevatedRisk); } /** * realize $CARROT earnings for a single Fox and optionally unstake it * foxes earn $CARROT proportional to their Alpha rank * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param unstake whether or not to unstake the Fox * @param seed account seed * @param elevatedRisk true if the user is facing higher risk of losing their token * @return reward - the amount of $CARROT earned */ function _claimFoxFromDen(IFoxGameNFT nftContract, uint16 tokenId, bool unstake, uint256 seed, bool elevatedRisk) internal returns (uint128 reward) { require(nftContract.ownerOf(tokenId) == address(this), "not staked"); uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]]; require(stake.owner == msg.sender, "not owner"); // Calculate advantage-based rewards uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? stake.earningRate : 0; // phase 2 reset if (crownPerCunningPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (crownPerCunningPoint - migratedEarningPoint); } if (unstake) { totalCunningPointsStaked -= cunningIndex; // Remove Alpha from total staked EarningStake storage lastStake = foxStakeByCunning[cunningIndex][foxStakeByCunning[cunningIndex].length - 1]; foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]] = lastStake; // Shuffle last Fox to current position foxHierarchy[lastStake.tokenId] = foxHierarchy[tokenId]; foxStakeByCunning[cunningIndex].pop(); // Remove duplicate delete foxHierarchy[tokenId]; // Delete old mapping totalFoxesStaked -= 1; // Determine if Fox should be stolen by hunter (normal=5% vs corrupted=20%) address recipient = msg.sender; if (((seed >> 245) % (elevatedRisk ? 5 : hunterStealFoxProbabilityMod)) == 0) { recipient = _randomHunterOwner(seed); if (recipient == address(0x0)) { recipient = msg.sender; } else if (recipient != msg.sender) { emit FoxStolen(tokenId, recipient, msg.sender); } } nftContract.safeTransferFrom(address(this), recipient, tokenId, ""); } else { // Update earning point foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]] = EarningStake({ owner: msg.sender, tokenId: tokenId, earningRate: crownPerCunningPoint }); hasRecentEarningPoint[tokenId] = true; } emit CrownClaimed("FOX", tokenId, stake.owner, unstake, reward, 0, elevatedRisk); } /** * realize $CARROT earnings for a single Fox and optionally unstake it * foxes earn $CARROT proportional to their Alpha rank * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param unstake whether or not to unstake the Fox * @return reward - the amount of $CARROT earned */ function _claimHunterFromCabin(IFoxGameNFT nftContract, uint16 tokenId, bool unstake) internal returns (uint128 reward) { require(foxNFTGen1.ownerOf(tokenId) == address(this), "not staked"); uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage earningStake = hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]]; require(earningStake.owner == msg.sender, "not owner"); uint48 time = uint48(block.timestamp); // Calculate advantage-based rewards uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? earningStake.earningRate : 0; // phase 2 reset if (crownPerMarksmanPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - marksmanIndex + MIN_ADVANTAGE) * (crownPerMarksmanPoint - migratedEarningPoint); } if (unstake) { totalMarksmanPointsStaked -= marksmanIndex; // Remove Alpha from total staked EarningStake storage lastStake = hunterStakeByMarksman[marksmanIndex][hunterStakeByMarksman[marksmanIndex].length - 1]; hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]] = lastStake; // Shuffle last Fox to current position hunterHierarchy[lastStake.tokenId] = hunterHierarchy[tokenId]; hunterStakeByMarksman[marksmanIndex].pop(); // Remove duplicate delete hunterHierarchy[tokenId]; // Delete old mapping } else { // Update earning point hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]] = EarningStake({ owner: msg.sender, tokenId: tokenId, earningRate: crownPerMarksmanPoint }); hasRecentEarningPoint[tokenId] = true; } // Calcuate time-based rewards TimeStake storage timeStake = hunterStakeByToken[tokenId]; require(timeStake.owner == msg.sender, "not owner"); uint48 stakeStart = timeStake.time < divergenceTime ? divergenceTime : timeStake.time; // phase 2 reset if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward += (time - stakeStart) * HUNTER_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { // stop earning additional $CARROT if it's all been earned reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE; } if (unstake) { delete hunterStakeByToken[tokenId]; totalHuntersStaked -= 1; // Unstake to owner foxNFTGen1.safeTransferFrom(address(this), msg.sender, tokenId, ""); } else { // Update last earned time hunterStakeByToken[tokenId] = TimeStake({ owner: msg.sender, tokenId: tokenId, time: time }); } emit CrownClaimed("HUNTER", tokenId, earningStake.owner, unstake, reward, 0, false); } // Struct to abstract away calculation of rewards from claiming rewards struct TokenReward { address owner; IFoxGameNFT.Kind kind; uint128 reward; uint128 corruptedCarrot; } /** * Realize $CARROT earnings. There's no risk nor tax involed other than corruption. * @param tokenId the token ID * @param time current time * @return claim reward information */ function getCarrotReward(uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { IFoxGameNFT nftContract = getTokenContract(tokenId); claim.kind = _getKind(nftContract, tokenId); if (claim.kind == IFoxGameNFT.Kind.RABBIT) { claim = _getCarrotForRabbit(tokenId, time); } else if (claim.kind == IFoxGameNFT.Kind.FOX) { claim = _getCarrotForFox(nftContract, tokenId, time); } else { // HUNTER claim = _getCarrotForHunter(nftContract, tokenId, time); } } /** * Calculate carrot rewards for the given tokens. * @param tokenIds list of tokens * @return claims list of reward objects */ function getCarrotRewards(uint16[] calldata tokenIds) external view returns (TokenReward[] memory claims) { uint48 time = uint48(block.timestamp); claims = new TokenReward[](tokenIds.length); for (uint8 i; i < tokenIds.length; i++) { if (!tokenCarrotClaimed[tokenIds[i]]) { claims[i] = getCarrotReward(tokenIds[i], time); } } } /** * Realize $CARROT earnings. There's no risk nor tax involed other than corruption. * @param tokenIds the IDs of the tokens to claim earnings from */ function claimCarrotRewards(uint16[] calldata tokenIds) external { require(tx.origin == msg.sender, "eos"); uint128 reward; TokenReward memory claim; uint48 time = uint48(block.timestamp); for (uint8 i; i < tokenIds.length; i++) { if (!tokenCarrotClaimed[tokenIds[i]]) { claim = getCarrotReward(tokenIds[i], time); require(claim.owner == msg.sender, "not owner"); reward += claim.reward; emit ClaimCarrot(claim.kind, tokenIds[i], claim.owner, claim.reward, claim.corruptedCarrot); tokenCarrotClaimed[tokenIds[i]] = true; } } // Disburse rewards if (reward != 0) { foxCarrot.mint(msg.sender, reward); } } /** * Calculate the carrot accumulated per token. * @param time current time */ function calculateCorruptedCarrot(address account, uint128 reward, uint48 time) private view returns (uint128 corruptedCarrot) { // If user has rewards and corruption has started if (reward > 0 && corruptionStartDate != 0 && time > corruptionStartDate) { // Calulate time that corruption was in effect uint48 barrelTime = barrelPurchaseDate[account]; uint128 unsafeElapsed = (barrelTime == 0 ? time - corruptionStartDate // never bought barrel : barrelTime > corruptionStartDate ? barrelTime - corruptionStartDate // bought after corruption : 0 // bought before corruption ); // Subtract from reward if (unsafeElapsed > 0) { corruptedCarrot = uint128((reward * unsafeElapsed * uint256(CORRUPTION_BURN_PERCENT_RATE)) / 1000000000000000000 /* 1eth */); } } } /** * Realize $CARROT earnings for a single Rabbit * @param tokenId the ID of the Rabbit to claim earnings from * @param time current time * @return claim carrot claim object */ function _getCarrotForRabbit(uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { // Carrot time-based rewards uint128 reward; TimeStake storage stake = rabbitStakeByToken[tokenId]; if (divergenceTime == 0 || time < divergenceTime) { // divergence has't yet started reward = (time - stake.time) * RABBIT_EARNING_RATE; } else if (stake.time < divergenceTime) { // last moment to accrue carrot reward = (divergenceTime - stake.time) * RABBIT_EARNING_RATE; } claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time); claim.reward = reward - claim.corruptedCarrot; claim.owner = stake.owner; } /** * Realize $CARROT earnings for a single Fox * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param time current time * @return claim carrot claim object */ function _getCarrotForFox(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]]; // Calculate advantage-based rewards uint128 reward; if (!hasRecentEarningPoint[tokenId] && carrotPerCunningPoint > stake.earningRate) { reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (carrotPerCunningPoint - stake.earningRate); } // Remove corrupted carrot claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time); claim.reward = reward - claim.corruptedCarrot; claim.owner = stake.owner; } /** * Realize $CARROT earnings for a single hunter * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param time current time * @return claim carrot claim object */ function _getCarrotForHunter(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { require(foxNFTGen1.ownerOf(tokenId) == address(this), "not staked"); uint8 marksman = _getAdvantagePoints(nftContract, tokenId); EarningStake storage earningStake = hunterStakeByMarksman[marksman][hunterHierarchy[tokenId]]; require(earningStake.owner == msg.sender, "not owner"); // Calculate advantage-based rewards uint128 reward; if (!hasRecentEarningPoint[tokenId] && carrotPerMarksmanPoint > earningStake.earningRate) { reward = marksman * (carrotPerMarksmanPoint - earningStake.earningRate); } // Carrot time-based rewards TimeStake storage timeStake = hunterStakeByToken[tokenId]; if (divergenceTime == 0 || time < divergenceTime) { reward += (time - timeStake.time) * HUNTER_EARNING_RATE; } else if (timeStake.time < divergenceTime) { reward += (divergenceTime - timeStake.time) * HUNTER_EARNING_RATE; } // Remove corrupted carrot claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time); claim.reward = reward - claim.corruptedCarrot; claim.owner = earningStake.owner; } /** * Add $CARROT claimable pots for hunters and foxes * @param amount $CARROT to add to the pot * @param includeHunters true if hunters take a cut of the spoils */ function _payTaxToPredators(uint128 amount, bool includeHunters) internal { uint128 amountDueFoxes = amount; // Hunters take their cut first if (includeHunters) { uint128 amountDueHunters = amount * hunterTaxCutPercentage / 100; amountDueFoxes -= amountDueHunters; // Update hunter pools if (totalMarksmanPointsStaked == 0) { unaccountedHunterRewards += amountDueHunters; } else { crownPerMarksmanPoint += (amountDueHunters + unaccountedHunterRewards) / totalMarksmanPointsStaked; unaccountedHunterRewards = 0; } } // Update fox pools if (totalCunningPointsStaked == 0) { unaccountedFoxRewards += amountDueFoxes; } else { // makes sure to include any unaccounted $CARROT crownPerCunningPoint += (amountDueFoxes + unaccountedFoxRewards) / totalCunningPointsStaked; unaccountedFoxRewards = 0; } } /** * Tracks $CARROT earnings to ensure it stops once 2.4 billion is eclipsed */ modifier _updateEarnings() { uint48 time = uint48(block.timestamp); // CROWN - Capped by supply if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { uint48 elapsed = time - lastCrownClaimTimestamp; totalCrownEarned += (elapsed * totalRabbitsStaked * RABBIT_EARNING_RATE) + (elapsed * totalHuntersStaked * HUNTER_EARNING_RATE); lastCrownClaimTimestamp = time; } _; } /** * Get token kind (rabbit, fox, hunter) * @param tokenId the ID of the token to check * @return kind */ function _getKind(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (IFoxGameNFT.Kind) { return nftContract.getTraits(tokenId).kind; } /** * gets the alpha score for a Fox * @param tokenId the ID of the Fox to get the alpha score for * @return the alpha score of the Fox (5-8) */ function _getAdvantagePoints(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (uint8) { return MAX_ADVANTAGE - nftContract.getTraits(tokenId).advantage; // alpha index is 0-3 } /** * chooses a random Fox thief when a newly minted token is stolen * @param seed a random value to choose a Fox from * @return the owner of the randomly selected Fox thief */ function randomFoxOwner(uint256 seed) external view returns (address) { if (totalCunningPointsStaked == 0) { return address(0x0); // use 0x0 to return to msg.sender } // choose a value from 0 to total alpha staked uint256 bucket = (seed & 0xFFFFFFFF) % totalCunningPointsStaked; uint256 cumulative; seed >>= 32; // loop through each cunning bucket of Foxes for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) { cumulative += foxStakeByCunning[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Fox with that alpha score return foxStakeByCunning[i][seed % foxStakeByCunning[i].length].owner; } return address(0x0); } /** * Chooses a random Hunter to steal a fox. * @param seed a random value to choose a Hunter from * @return the owner of the randomly selected Hunter thief */ function _randomHunterOwner(uint256 seed) internal view returns (address) { if (totalMarksmanPointsStaked == 0) { return address(0x0); // use 0x0 to return to msg.sender } // choose a value from 0 to total alpha staked uint256 bucket = (seed & 0xFFFFFFFF) % totalMarksmanPointsStaked; uint256 cumulative; seed >>= 32; // loop through each cunning bucket of Foxes for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) { cumulative += hunterStakeByMarksman[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Fox with that alpha score return hunterStakeByMarksman[i][seed % hunterStakeByMarksman[i].length].owner; } return address(0x0); } /** * Realize $CROWN earnings * @param tokenIds the IDs of the tokens to claim earnings from */ function calculateRewards(uint16[] calldata tokenIds) external view returns (TokenReward[] memory tokenRewards) { require(tx.origin == msg.sender, "eos only"); IFoxGameNFT.Kind kind; IFoxGameNFT nftContract; tokenRewards = new TokenReward[](tokenIds.length); uint48 time = uint48(block.timestamp); for (uint8 i = 0; i < tokenIds.length; i++) { nftContract = getTokenContract(tokenIds[i]); kind = _getKind(nftContract, tokenIds[i]); if (kind == IFoxGameNFT.Kind.RABBIT) { tokenRewards[i] = _calculateRabbitReward(tokenIds[i], time); } else if (kind == IFoxGameNFT.Kind.FOX) { tokenRewards[i] = _calculateFoxReward(nftContract, tokenIds[i]); } else { // HUNTER tokenRewards[i] = _calculateHunterReward(nftContract, tokenIds[i], time); } } } /** * Calculate rabbit reward. * @param tokenId the ID of the Rabbit to claim earnings from * @param time currnet block time * @return tokenReward token reward response */ function _calculateRabbitReward(uint16 tokenId, uint48 time) internal view returns (TokenReward memory tokenReward) { TimeStake storage stake = rabbitStakeByToken[tokenId]; uint48 stakeStart = stake.time < divergenceTime ? divergenceTime : stake.time; // phase 2 reset // Calcuate time-based rewards uint128 reward; if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward = (time - stakeStart) * RABBIT_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { // stop earning additional $CROWN if it's all been earned reward = (lastCrownClaimTimestamp - stakeStart) * RABBIT_EARNING_RATE; } // Compose reward object tokenReward.owner = stake.owner; tokenReward.reward = reward * (100 - RABBIT_CLAIM_TAX_PERCENTAGE) / 100; } /** * Calculate fox reward. * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @return tokenReward token reward response */ function _calculateFoxReward(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (TokenReward memory tokenReward) { uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]]; // Calculate advantage-based rewards uint128 reward; uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? stake.earningRate : 0; // phase 2 reset if (crownPerCunningPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (crownPerCunningPoint - migratedEarningPoint); } // Compose reward object tokenReward.owner = stake.owner; tokenReward.reward = reward; } /** * Calculate hunter reward. * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param time currnet block time * @return tokenReward token reward response */ function _calculateHunterReward(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) internal view returns (TokenReward memory tokenReward) { uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage earningStake = hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]]; // Calculate advantage-based rewards uint128 reward; uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? earningStake.earningRate : 0; // phase 2 reset if (crownPerMarksmanPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - marksmanIndex + MIN_ADVANTAGE) * (crownPerMarksmanPoint - migratedEarningPoint); } // Calcuate time-based rewards TimeStake storage timeStake = hunterStakeByToken[tokenId]; uint48 stakeStart = timeStake.time < divergenceTime ? divergenceTime : timeStake.time; // phase 2 reset require(timeStake.owner == msg.sender, "not owner"); if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward += (time - stakeStart) * HUNTER_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE; } // Compose reward object tokenReward.owner = earningStake.owner; tokenReward.reward = reward; } /** * Interface support to allow player staking. */ function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4) { require(from == address(0x0)); return IERC721ReceiverUpgradeable.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // 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 ECDSAUpgradeable { 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)); } } // 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; 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.10; interface IFoxGame { function stakeTokens(address, uint16[] calldata) external; function randomFoxOwner(uint256) external view returns (address); function isValidMintSignature(address, uint8, uint32, uint256, bytes memory) external view returns (bool); function ownsBarrel(address) external view returns (bool); function getCorruptionEnabled() external view returns (bool); } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameCarrot { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameCrown { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameNFT { enum Kind { RABBIT, FOX, HUNTER } enum Coin { CARROT, CROWN } struct Traits { Kind kind; uint8 advantage; uint8[7] traits; } function getMaxGEN0Players() external pure returns (uint16); function getTraits(uint16) external view returns (Traits memory); function ownerOf(uint256) external view returns (address owner); function transferFrom(address, address, uint256) external; function safeTransferFrom(address, address, uint256, bytes memory) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } } }
stop earning additional $CARROT if it's all been earned
if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward += (time - stakeStart) * HUNTER_EARNING_RATE; reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE; }
14,423,413
[ 1, 5681, 425, 9542, 3312, 271, 39, 985, 1457, 56, 309, 518, 1807, 777, 2118, 425, 1303, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 309, 261, 4963, 39, 26253, 41, 1303, 329, 411, 4552, 18605, 67, 20402, 67, 39, 1457, 5665, 13, 288, 203, 1377, 19890, 1011, 261, 957, 300, 384, 911, 1685, 13, 380, 670, 5321, 654, 67, 41, 6343, 67, 24062, 31, 203, 1377, 19890, 1011, 261, 2722, 39, 26253, 9762, 4921, 300, 384, 911, 1685, 13, 380, 670, 5321, 654, 67, 41, 6343, 67, 24062, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface ILiquidityGauge { struct Reward { address token; address distributor; uint256 period_finish; uint256 rate; uint256 last_update; uint256 integral; } // solhint-disable-next-line function deposit_reward_token(address _rewardToken, uint256 _amount) external; // solhint-disable-next-line function claim_rewards_for(address _user, address _recipient) external; // // solhint-disable-next-line // function claim_rewards_for(address _user) external; // solhint-disable-next-line function deposit(uint256 _value, address _addr) external; // solhint-disable-next-line function reward_tokens(uint256 _i) external view returns(address); // solhint-disable-next-line function reward_data(address _tokenReward) external view returns(Reward memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ILocker { function createLock(uint256, uint256) external; function increaseAmount(uint256) external; function increaseUnlockTime(uint256) external; function release() external; function claimRewards(address,address) external; function claimFXSRewards(address) external; function execute( address, uint256, bytes calldata ) external returns (bool, bytes memory); function setGovernance(address) external; function voteGaugeWeight(address, uint256) external; function setAngleDepositor(address) external; function setFxsDepositor(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ISdToken { function setOperator(address _operator) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ITokenMinter { function mint(address, uint256) external; function burn(address, uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/ITokenMinter.sol"; import "../interfaces/ILocker.sol"; import "../interfaces/ISdToken.sol"; import "../interfaces/ILiquidityGauge.sol"; /// @title Contract that accepts tokens and locks them /// @author StakeDAO contract Depositor { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address public token; uint256 private constant MAXTIME = 4 * 364 * 86400; uint256 private constant WEEK = 7 * 86400; uint256 public lockIncentive = 10; //incentive to users who spend gas to lock token uint256 public constant FEE_DENOMINATOR = 10000; address public gauge; address public governance; address public immutable locker; address public immutable minter; uint256 public incentiveToken = 0; uint256 public unlockTime; bool public relock = true; /* ========== EVENTS ========== */ event Deposited(address indexed caller, address indexed user, uint256 amount, bool lock, bool stake); event IncentiveReceived(address indexed caller, uint256 amount); event TokenLocked(address indexed user, uint256 amount); event GovernanceChanged(address indexed newGovernance); event SdTokenOperatorChanged(address indexed newSdToken); event FeesChanged(uint256 newFee); /* ========== CONSTRUCTOR ========== */ constructor( address _token, address _locker, address _minter ) { governance = msg.sender; token = _token; locker = _locker; minter = _minter; } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Set the new governance /// @param _governance governance address function setGovernance(address _governance) external { require(msg.sender == governance, "!auth"); governance = _governance; emit GovernanceChanged(_governance); } /// @notice Set the new operator for minting sdToken /// @param _operator operator address function setSdTokenOperator(address _operator) external { require(msg.sender == governance, "!auth"); ISdToken(minter).setOperator(_operator); emit SdTokenOperatorChanged(_operator); } /// @notice Enable the relock or not /// @param _relock relock status function setRelock(bool _relock) external { require(msg.sender == governance, "!auth"); relock = _relock; } /// @notice Set the gauge to deposit token yielded /// @param _gauge gauge address function setGauge(address _gauge) external { require(msg.sender == governance, "!auth"); gauge = _gauge; } /// @notice set the fees for locking incentive /// @param _lockIncentive contract must have tokens to lock function setFees(uint256 _lockIncentive) external { require(msg.sender == governance, "!auth"); if (_lockIncentive >= 0 && _lockIncentive <= 30) { lockIncentive = _lockIncentive; emit FeesChanged(_lockIncentive); } } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Locks the tokens held by the contract /// @dev The contract must have tokens to lock function _lockToken() internal { uint256 tokenBalance = IERC20(token).balanceOf(address(this)); // If there is Token available in the contract transfer it to the locker if (tokenBalance > 0) { IERC20(token).safeTransfer(locker, tokenBalance); emit TokenLocked(msg.sender, tokenBalance); } uint256 tokenBalanceStaker = IERC20(token).balanceOf(locker); // If the locker has no tokens then return if (tokenBalanceStaker == 0) { return; } ILocker(locker).increaseAmount(tokenBalanceStaker); if (relock) { uint256 unlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = (unlockAt / WEEK) * WEEK; // it means that a 1 week + at least 1 second has been passed // since last increased unlock time if (unlockInWeeks - unlockTime > 1) { ILocker(locker).increaseUnlockTime(unlockAt); unlockTime = unlockInWeeks; } } } /// @notice Lock tokens held by the contract /// @dev The contract must have Token to lock function lockToken() external { _lockToken(); // If there is incentive available give it to the user calling lockToken if (incentiveToken > 0) { ITokenMinter(minter).mint(msg.sender, incentiveToken); emit IncentiveReceived(msg.sender, incentiveToken); incentiveToken = 0; } } /// @notice Deposit & Lock Token /// @dev User needs to approve the contract to transfer the token /// @param _amount The amount of token to deposit /// @param _lock Whether to lock the token /// @param _stake Whether to stake the token /// @param _user User to deposit for function deposit( uint256 _amount, bool _lock, bool _stake, address _user ) public { require(_amount > 0, "!>0"); require(_user != address(0), "!user"); // If User chooses to lock Token if (_lock) { IERC20(token).safeTransferFrom(msg.sender, locker, _amount); _lockToken(); if (incentiveToken > 0) { _amount = _amount + incentiveToken; emit IncentiveReceived(msg.sender, incentiveToken); incentiveToken = 0; } } else { //move tokens here IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); //defer lock cost to another user uint256 callIncentive = (_amount * lockIncentive) / FEE_DENOMINATOR; _amount = _amount - callIncentive; incentiveToken = incentiveToken + callIncentive; } if (_stake && gauge != address(0)) { ITokenMinter(minter).mint(address(this), _amount); IERC20(minter).safeApprove(gauge, 0); IERC20(minter).safeApprove(gauge, _amount); ILiquidityGauge(gauge).deposit(_amount, _user); } else { ITokenMinter(minter).mint(_user, _amount); } emit Deposited(msg.sender, _user, _amount, _lock, _stake); } /// @notice Deposits all the token of a user & locks them based on the options choosen /// @dev User needs to approve the contract to transfer Token tokens /// @param _lock Whether to lock the token /// @param _stake Whether to stake the token /// @param _user User to deposit for function depositAll( bool _lock, bool _stake, address _user ) external { uint256 tokenBal = IERC20(token).balanceOf(msg.sender); deposit(tokenBal, _lock, _stake, _user); } }
incentive to users who spend gas to lock token
uint256 public lockIncentive = 10;
1,563,672
[ 1, 267, 2998, 688, 358, 3677, 10354, 17571, 16189, 358, 2176, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 11890, 5034, 1071, 2176, 382, 2998, 688, 273, 1728, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x14fa9FA3b4Ec9fE639a9E04B5D02ee2Ea65bd3F9/sources/home/user/Documents/git-repos/0x/protocol/contracts/zero-ex/contracts/src/external/FlashWallet.sol
@dev Allows this contract to receive ERC223 tokens.
) external pure {}
11,563,193
[ 1, 19132, 333, 6835, 358, 6798, 4232, 39, 3787, 23, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 3903, 16618, 2618, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xB94613518f0EB4a898beD151F201EEB2Bf3BaE1a/sources/Kudos.sol
1.20% from total supply maxWallet
maxWallet = 120000 * 1e18;
8,450,923
[ 1, 21, 18, 3462, 9, 628, 2078, 14467, 943, 16936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 16936, 273, 2593, 2787, 380, 404, 73, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; interface IORGovernor{ function getAccountInfo(address account) external view returns(bool governorFlag, bool suspendedFlag, uint256 power) ; function getSuspendReason(address account) external view returns(string memory reason); function userHasWrongVoting(address account, address[] calldata markets) external returns (bool); } contract DummyORGovernor is IORGovernor{ function getAccountInfo(address ) external view returns(bool governorFlag, bool suspendedFlag, uint256 power){ return (true,false, 100); } function getSuspendReason(address ) external view returns(string memory reason){ return ""; } //////// mapping(address => uint256) powerPerUser; // todo: not a real function, just to mimic the Governance power function setAccountPower(address account, uint256 power) public { powerPerUser[account] = power; } // todo: not a real function, just to mimic the Governance power function setPower(address account, uint256 power) public{ powerPerUser[account] = power; } }
todo: not a real function, just to mimic the Governance power
function setPower(address account, uint256 power) public{ powerPerUser[account] = power; }
12,748,292
[ 1, 9012, 30, 486, 279, 2863, 445, 16, 2537, 358, 20369, 335, 326, 611, 1643, 82, 1359, 7212, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 13788, 12, 2867, 2236, 16, 2254, 5034, 7212, 13, 1071, 95, 203, 3639, 7212, 2173, 1299, 63, 4631, 65, 273, 7212, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42161/0x3543488F480bDb42075283Bc354Cf5B0F58e8204/sources/project_/src/active/MemepadProject.sol
Set public sale time. - For holder duration = _publicTimeHolder - _publicTime - For everyone: after _publicTimeHolder
function setPublicTime(uint256 _publicTime, uint256 _publicTimeHolder) external onlyOwner { publicTime = _publicTime; publicTimeHolder = _publicTimeHolder; }
16,300,940
[ 1, 694, 1071, 272, 5349, 813, 18, 300, 2457, 10438, 3734, 273, 389, 482, 950, 6064, 300, 389, 482, 950, 300, 2457, 3614, 476, 30, 1839, 389, 482, 950, 6064, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 27467, 950, 12, 11890, 5034, 389, 482, 950, 16, 2254, 5034, 389, 482, 950, 6064, 13, 3903, 1338, 5541, 288, 203, 565, 1071, 950, 273, 389, 482, 950, 31, 203, 565, 1071, 950, 6064, 273, 389, 482, 950, 6064, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x0a5851524e638EDF1652010c7E6fB50c81d70977/sources/src/BaseConditionalOrder.sol
* @dev Set the visibility of this function to `public` to allow `verify` to call it. @inheritdoc IConditionalOrderGenerator/* @inheritdoc IERC165/
function getTradeableOrder(address owner, address sender, bytes calldata staticInput, bytes calldata offchainInput) public view virtual override returns (GPv2Order.Data memory); function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) { return interfaceId == type(IConditionalOrderGenerator).interfaceId || interfaceId == type(IERC165).interfaceId; }
14,285,382
[ 1, 694, 326, 9478, 434, 333, 445, 358, 1375, 482, 68, 358, 1699, 1375, 8705, 68, 358, 745, 518, 18, 632, 10093, 467, 14132, 2448, 3908, 19, 632, 10093, 467, 654, 39, 28275, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 22583, 429, 2448, 12, 2867, 3410, 16, 1758, 5793, 16, 1731, 745, 892, 760, 1210, 16, 1731, 745, 892, 3397, 5639, 1210, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 9681, 90, 22, 2448, 18, 751, 3778, 1769, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 3903, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 14132, 2448, 3908, 2934, 5831, 548, 747, 1560, 548, 422, 618, 12, 45, 654, 39, 28275, 2934, 5831, 548, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Based on https://github.com/HausDAO/Molochv2.1 // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // import "hardhat/console.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // 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; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Moloch is ReentrancyGuard { /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period bool private initialized; // internally tracks deployment under eip-1167 proxy pattern address public depositToken; // deposit token contract reference; default = wETH uint256 public spamPrevention; address public spamPreventionAddr; // can have multiple shamans mapping(address => bool) public shamans; // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // *************** // EVENTS // *************** event SummonComplete( address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); event SubmitProposal( address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string details, bool[6] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress ); event SponsorProposal( address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod ); event SubmitVote( uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote ); event ProcessProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event ProcessWhitelistProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event ProcessGuildKickProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event Ragequit( address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn ); event TokensCollected(address indexed token, uint256 amountToCollect); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey( address indexed memberAddress, address newDelegateKey ); event Withdraw( address indexed memberAddress, address token, uint256 amount ); event Shaman( address indexed memberAddress, uint256 shares, uint256 loot, bool mint ); event SetSpamPrevention(address spamPreventionAddr, uint256 spamPrevention); event SetShaman(address indexed shaman, bool isEnabled); event SetConfig( uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalLoot = 0; // total loot across all members uint256 public totalGuildBankTokens = 0; // total tokens with non-zero balance in guild bank address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping(address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } mapping(uint256 => mapping(address => Vote)) voteHistory; // maps voting decisions on proposals proposal => member => voted mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; // TODO: whats this for? address[] public memberList; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember() { require( members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member" ); _; } modifier onlyShareholder() { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate() { require( members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate" ); _; } modifier onlyDelegateOrShaman() { require( members[memberAddressByDelegateKey[msg.sender]].shares > 0 || shamans[msg.sender], "!delegate || !shaman" ); _; } modifier onlyShaman() { require(shamans[msg.sender], "!shaman"); _; } function setShaman(address _shaman, bool _enable) public onlyShaman { shamans[_shaman] = _enable; emit SetShaman(_shaman, _enable); } function setConfig(address _spamPreventionAddr, uint256 _spamPrevention) public onlyShaman { spamPreventionAddr = _spamPreventionAddr; spamPrevention = _spamPrevention; emit SetSpamPrevention(_spamPreventionAddr, _spamPrevention); } // allow member to do this if no active props function setSharesLoot( address[] memory _applicants, uint256[] memory _applicantShares, uint256[] memory _applicantLoot, bool mint ) public onlyShaman { require(_applicants.length == _applicantShares.length, "mismatch"); require(_applicants.length == _applicantLoot.length, "mismatch"); for (uint256 i = 0; i < _applicants.length; i++) { _setSharesLoot( _applicants[i], _applicantShares[i], _applicantLoot[i], mint ); // TODO: maybe emit only once in the future emit Shaman( _applicants[i], _applicantShares[i], _applicantLoot[i], mint ); } } function setSingleSharesLoot( address _applicant, uint256 _applicantShares, uint256 _applicantLoot, bool mint ) public onlyShaman { _setSharesLoot( _applicant, _applicantShares, _applicantLoot, mint ); // TODO: maybe emit only once in the future emit Shaman(_applicant, _applicantShares, _applicantLoot, mint); } function _setSharesLoot( address applicant, uint256 shares, uint256 loot, bool mint ) internal { if (mint) { if (members[applicant].exists) { members[applicant].shares = members[applicant].shares + shares; members[applicant].loot = members[applicant].loot + loot; // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[ applicant ]; memberAddressByDelegateKey[ memberToOverride ] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[applicant] = Member( applicant, shares, loot, true, 0, 0 ); memberAddressByDelegateKey[applicant] = applicant; } totalShares = totalShares + shares; totalLoot = totalLoot + loot; } else { members[applicant].shares = members[applicant].shares - shares; members[applicant].loot = members[applicant].loot - loot; totalShares = totalShares - shares; totalLoot = totalLoot - loot; } require( (totalShares + shares + loot) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); } function _setConfig( uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) internal { require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require( _votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit" ); require( _gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit" ); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require( _dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit" ); require( _proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward" ); periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; } function init( // address _summoner, address _shaman, address[] calldata _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) external { require(!initialized, "initialized"); require(_approvedTokens.length > 0, "need at least one approved token"); require( _approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens" ); _setConfig( _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); summoningTime = block.timestamp; initialized = true; depositToken = _approvedTokens[0]; shamans[_shaman] = true; require( totalShares <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); for (uint256 i = 0; i < _approvedTokens.length; i++) { require( _approvedTokens[i] != address(0), "_approvedToken cannot be 0" ); require( !tokenWhitelist[_approvedTokens[i]], "duplicate approved token" ); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public nonReentrant returns (uint256 proposalId) { require( (sharesRequested + lootRequested) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); require( tokenWhitelist[tributeToken], "tributeToken is not whitelisted" ); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require( applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved" ); require( members[applicant].jailed == 0, "proposal applicant must not be jailed" ); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require( totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "cannot submit more tribute proposals for new tokens - guildbank is full" ); } // collect tribute from proposer and store it in the Moloch until the proposal is processed require( IERC20(tributeToken).transferFrom( msg.sender, address(this), tributeOffered ), "tribute token transfer failed" ); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] _submitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags ); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitWhitelistProposal( address tokenToWhitelist, string memory details ) public nonReentrant returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require( !tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token" ); require( approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals" ); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[4] = true; // whitelist _submitProposal( address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags ); return proposalCount - 1; } function submitGuildKickProposal( address memberToKick, string memory details ) public nonReentrant returns (uint256 proposalId) { Member memory member = members[memberToKick]; require( member.shares > 0 || member.loot > 0, "member must have at least one share or one loot" ); require( members[memberToKick].jailed == 0, "member must not already be jailed" ); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[5] = true; // guild kick _submitProposal( memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags ); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details, bool[6] memory flags ) internal { require(msg.value >= spamPrevention, "spam prevention on"); if (spamPrevention > 0 && !shamans[msg.sender]) { (bool success, ) = spamPreventionAddr.call{value: msg.value}(""); require(success, "failed"); } Proposal memory proposal = Proposal({ applicant: applicant, proposer: msg.sender, sponsor: address(0), sharesRequested: sharesRequested, lootRequested: lootRequested, tributeOffered: tributeOffered, tributeToken: tributeToken, paymentRequested: paymentRequested, paymentToken: paymentToken, startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAndLootAtYesVote: 0 }); proposals[proposalCount] = proposal; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, proposalCount, msg.sender, memberAddress ); proposalCount += 1; } function sponsorProposal(uint256 proposalId) public nonReentrant onlyDelegate { // collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed require( IERC20(depositToken).transferFrom( msg.sender, address(this), proposalDeposit ), "proposal deposit token transfer failed" ); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require( proposal.proposer != address(0), "proposal must have been proposed" ); require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has been cancelled"); require( members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed" ); if ( proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 ) { require( totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "cannot sponsor more tribute proposals for new tokens - guildbank is full" ); } // whitelist proposal if (proposal.flags[4]) { require( !tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token" ); require( !proposedToWhitelist[address(proposal.tributeToken)], "already proposed to whitelist" ); require( approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals" ); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5]) { require( !proposedToKick[proposal.applicant], "already proposed to kick" ); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]] .startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; proposal.flags[0] = true; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal( msg.sender, memberAddress, proposalId, proposalQueue.length - 1, startingPeriod ); } // NOTE: In MolochV2 proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require( proposalIndex < proposalQueue.length, "proposal does not exist" ); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require( getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started" ); require( !hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired" ); require( voteHistory[proposalIndex][memberAddress] == Vote.Null, "member has already voted" ); require( vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No" ); voteHistory[proposalIndex][memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes + member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if ( (totalShares + totalLoot) > proposal.maxTotalSharesAndLootAtYesVote ) { proposal.maxTotalSharesAndLootAtYesVote = totalShares + totalLoot; } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes + member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote( proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote ); } function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require( !proposal.flags[4] && !proposal.flags[5], "must be a standard proposal" ); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if ( (totalShares + totalLoot + proposal.sharesRequested + proposal.lootRequested) > MAX_NUMBER_OF_SHARES_AND_LOOT ) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if ( proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken] ) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if ( proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT ) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass _setSharesLoot( proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true ); // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if ( userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0 ) { totalGuildBankTokens += 1; } unsafeInternalTransfer( ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered ); unsafeInternalTransfer( GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested ); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if ( userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0 ) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer( ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4], "must be a whitelist proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = true; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5], "must be a guild kick proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = true; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot + member.shares; totalShares = totalShares - member.shares; totalLoot = totalLoot + member.shares; member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; didPass = proposal.yesVotes > proposal.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ( (totalShares + totalLoot) * (dilutionBound) < proposal.maxTotalSharesAndLootAtYesVote ) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require( proposalIndex < proposalQueue.length, "proposal does not exist" ); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require( getCurrentPeriod() >= (proposal.startingPeriod + votingPeriodLength + gracePeriodLength), "proposal is not ready to be processed" ); require( proposal.flags[1] == false, "proposal has already been processed" ); require( proposalIndex == 0 || proposals[proposalQueue[proposalIndex - 1]].flags[1], "previous proposal must be processed" ); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer( ESCROW, msg.sender, depositToken, processingReward ); unsafeInternalTransfer( ESCROW, sponsor, depositToken, proposalDeposit - processingReward ); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) public nonReentrant onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit( address memberAddress, uint256 sharesToBurn, uint256 lootToBurn ) internal { uint256 initialTotalSharesAndLoot = totalShares + totalLoot; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require( canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed" ); uint256 sharesAndLootToBurn = sharesToBurn + lootToBurn; // burn shares and loot _setSharesLoot(memberAddress, sharesToBurn, lootToBurn, false); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare( userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot ); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][ approvedTokens[i] ] += amountToRagequit; } } emit Ragequit(memberAddress, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public nonReentrant { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require( canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed" ); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) public nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances( address[] memory tokens, uint256[] memory amounts, bool shouldWithdrawMax ) public nonReentrant { require( tokens.length == amounts.length, "tokens and amounts arrays must be matching lengths" ); for (uint256 i = 0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (shouldWithdrawMax) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require( userTokenBalances[msg.sender][token] >= amount, "insufficient balance" ); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegateOrShaman nonReentrant { uint256 amountToCollect = IERC20(token).balanceOf(address(this)) - userTokenBalances[TOTAL][token]; // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, "no tokens to collect"); require(tokenWhitelist[token], "token to collect must be whitelisted"); require( userTokenBalances[GUILD][token] > 0 || totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "token to collect must have non-zero guild bank balance" ); if (userTokenBalances[GUILD][token] == 0) { totalGuildBankTokens += 1; } unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) public nonReentrant { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has already been cancelled"); require( msg.sender == proposal.proposer, "solely the proposer can cancel" ); proposal.flags[3] = true; // cancelled unsafeInternalTransfer( ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public nonReentrant onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require( !members[newDelegateKey].exists, "cannot overwrite existing members" ); require( !members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys" ); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { // TODO: fixed to allow ragequit before any proposals, write test if(proposalQueue.length == 0){ return true; } require( highestIndexYesVote < proposalQueue.length, "proposal does not exist" ); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= (startingPeriod + votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return (block.timestamp - summoningTime) / (periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getProposalFlags(uint256 proposalId) public view returns (bool[6] memory) { return proposals[proposalId].flags; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require( proposalIndex < proposalQueue.length, "proposal does not exist" ); return voteHistory[proposalIndex][memberAddress]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance( address user, address token, uint256 amount ) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance( address user, address token, uint256 amount ) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer( address from, address to, address token, uint256 amount ) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare( uint256 balance, uint256 shares, uint256 _totalShares ) internal pure returns (uint256) { require(_totalShares != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / _totalShares; } return (balance / _totalShares) * shares; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract CloneFactory { // implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } } contract MolochSummoner is CloneFactory { address public template; mapping(uint256 => address) public daos; uint256 public daoIdx = 0; // Moloch private moloch; // moloch contract constructor(address _template) { template = _template; } event SummonComplete( address indexed moloch, address _summoner, address _shaman, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); function summonMoloch( address _summoner, address _shaman, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) public returns (address) { Moloch moloch = Moloch(createClone(template)); moloch.init( // _summoner, _shaman, _approvedTokens, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); daoIdx = daoIdx + 1; daos[daoIdx] = address(moloch); emit SummonComplete( address(moloch), _summoner, _shaman, _approvedTokens, block.timestamp, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); return address(moloch); } }
TODO: whats this for?
address[] public memberList;
32,936
[ 1, 6241, 30, 600, 2323, 333, 364, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 8526, 1071, 3140, 682, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /// @author Jan Turk /// @title Administration contract Administration { mapping (address => bool) private registered; mapping (address => mapping (address => bool)) private owners; mapping (address => mapping (address => bool)) private admins; mapping (address => mapping (address => bool)) private registeredUsers; /// @notice Event to notify listeners of new contract that will use the administration /// @param smartContract the contract that started using the administration /// @param owner the owner of the contract event NewContractRegistration( address indexed smartContract, address indexed owner ); /// @notice Event to notify listeners of ownership trandfer of one of the contracts /// @param smartContract the contract of which the ownership was transferred /// @param oldOwner the old owner of the contract /// @param newOwner the new owner of the contract event OwnershipTransfer( address indexed smartContract, address indexed oldOwner, address indexed newOwner ); /// @notice Event to notify listeners that one of the contracts had an admin appointed /// @param smartContract the contract which got new administrator appointed /// @param administrator the new administrator of the contract event AdministratorAppointed( address indexed smartContract, address indexed administrator ); /// @notice Event to notify listeners that one of the contracts had an admin demoted /// @param smartContract the contract which got an administrator demoted /// @param administrator the administrator of the contract that got demoted event AdministratorDemoted( address indexed smartContract, address indexed administrator ); /// @notice Event to notify listeners that one of the contracts had a new user registered /// @param smartContract the contract which got new user registered /// @param user the new user of the contract event UserRegistered( address indexed smartContract, address indexed user ); /// @notice Event to notify listeners that one of the contracts had a user unregistered /// @param smartContract the contract which got user unregistered /// @param user the user of the contract that was unregistered event UserUnregistered( address indexed smartContract, address indexed user ); constructor() public { } /// @notice Checks wether the smart contract is registered in Administration /// @dev Used so that the owner can be set by anyone the first time the owner is set for the contract modifier onlyRegistered{ require(registered[msg.sender]); _; } /// @notice Checks whether the caller is the owner of the contract /// @param _caller The address to be checked for permissions modifier onlyContractOwner(address _caller){ require(owners[msg.sender][_caller]); _; } /// @notice Checks wether the caller is the owner or the administrator of the contract /// @param _caller The address to be checked for permissions modifier onlyContractAdmin(address _caller){ require(admins[msg.sender][_caller] || owners[msg.sender][_caller]); _; } /// @notice Checks wether the caller is the owner, administrator or the registered user of the contract /// @param _contract The address to be checked for permissions function checkRegistrationStatus(address _contract) external view returns(bool){ return registered[_contract]; } /// @notice Checks wether the caller is the owner /// @param _tenant The address to be checked for permissions /// @return Confirmation of restriction of the permissions function checkOwnership(address _tenant) external view returns(bool){ return owners[msg.sender][_tenant]; } /// @notice Checks wether the caller is the owneror administrator of the contract /// @param _tenant The address to be checked for permissions /// @return Confirmation of restriction of the permissions function checkAdministatorship(address _tenant) external view returns(bool){ return (owners[msg.sender][_tenant] || admins[msg.sender][_tenant]); } /// @notice Checks wether the caller is the owner, administrator or the registered user of the contract /// @param _tenant The address to be checked for permissions /// @return Confirmation of restriction of the permissions function checkRegisteredUser(address _tenant) external view returns(bool){ return ( owners[msg.sender][_tenant] || admins[msg.sender][_tenant] || registeredUsers[msg.sender][_tenant] ); } /// @notice Seths the owner and registered the contract to Administration /// @param _initialOwner The address of the owner of the smart contract being registered /// @return Confirmation of successful execution function initialRegistration(address _initialOwner) external returns(bool){ require(!registered[msg.sender]); owners[msg.sender][_initialOwner] = true; registered[msg.sender] = true; emit NewContractRegistration(msg.sender, _initialOwner); return false; } /// @notice Transfer the ownershp of the contract /// @param _caller The address that initiated the transfer of ownership /// @param _newOwner The address to receive ownership of the contract /// @return Confirmation of successful execution function transferOwnership( address _caller, address _newOwner ) external onlyRegistered onlyContractOwner(_caller) returns(bool) { owners[msg.sender][_caller] = false; owners[msg.sender][_newOwner] = true; emit OwnershipTransfer(msg.sender, _caller, _newOwner); return true; } /// @notice Appoint admin of the contract /// @param _caller The address that initiated the appointment /// @param _admin The address to receive administratorship of the contract /// @return Confirmation of successful execution function appointAdmin( address _caller, address _admin ) external onlyRegistered onlyContractOwner(_caller) returns(bool) { require(!admins[msg.sender][_admin]); require(changeAdminStatus(_admin, true)); emit AdministratorAppointed(msg.sender, _admin); return true; } /// @notice Demote admin of the contract /// @param _caller The address that initiated the demotion /// @param _admin The address to have administratorship of the contract revoked /// @return Confirmation of successful execution function demoteAdmin( address _caller, address _admin ) external onlyRegistered onlyContractOwner(_caller) returns(bool) { require(admins[msg.sender][_admin]); require(changeAdminStatus(_admin, false)); emit AdministratorDemoted(msg.sender, _admin); return true; } /// @notice Register user of the contract /// @param _caller The address that initiated the registration /// @param _user The address to be a registered user of the contract /// @return Confirmation of successful execution function registerUser( address _caller, address _user ) external onlyRegistered onlyContractAdmin(_caller) returns(bool) { require(!registeredUsers[msg.sender][_user]); require(changeRegisteredUsers(_user, true)); emit UserRegistered(msg.sender, _user); return true; } /// @notice Register user of the contract /// @param _caller The address that initiated the registration /// @param _user The address to be unregistered as a user of the contract /// @return Confirmation of successful execution function unregisterUser( address _caller, address _user ) external onlyRegistered onlyContractAdmin(_caller) returns(bool) { require(registeredUsers[msg.sender][_user]); require(changeRegisteredUsers(_user, false)); emit UserUnregistered(msg.sender, _user); return true; } /// @notice Change state of the administrator rights /// @dev This is an internal function so that the external calls coming in are easier to discern /// @param _admin The address to have admin rights changed /// @param _rights The bool that marks _admin as administrator or not /// @return Confirmation of successful execution function changeAdminStatus(address _admin, bool _rights) internal returns(bool){ admins[msg.sender][_admin] = _rights; return true; } /// @notice Change state of the registered user rights /// @dev This is an internal function so that the external calls coming in are easier to discern /// @param _user The address to have user rights changed /// @param _rights The bool that marks _user as registered or not /// @return Confirmation of successful execution function changeRegisteredUsers(address _user, bool _rights) internal returns(bool){ registeredUsers[msg.sender][_user] = _rights; return true; } }
@notice Checks wether the caller is the owner, administrator or the registered user of the contract @param _tenant The address to be checked for permissions @return Confirmation of restriction of the permissions
function checkRegisteredUser(address _tenant) external view returns(bool){ return ( owners[msg.sender][_tenant] || admins[msg.sender][_tenant] || registeredUsers[msg.sender][_tenant] ); }
971,475
[ 1, 4081, 341, 2437, 326, 4894, 353, 326, 3410, 16, 22330, 578, 326, 4104, 729, 434, 326, 6835, 225, 389, 20115, 1021, 1758, 358, 506, 5950, 364, 4371, 327, 17580, 367, 434, 9318, 434, 326, 4371, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 866, 10868, 1299, 12, 2867, 389, 20115, 13, 3903, 1476, 1135, 12, 6430, 15329, 203, 565, 327, 261, 203, 1377, 25937, 63, 3576, 18, 15330, 6362, 67, 20115, 65, 747, 203, 1377, 31116, 63, 3576, 18, 15330, 6362, 67, 20115, 65, 747, 203, 1377, 4104, 6588, 63, 3576, 18, 15330, 6362, 67, 20115, 65, 203, 565, 11272, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; } // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } contract DFSExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); if (originationFee > 0) { ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee); } approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x7b856af5753a9f80968EA002641E69AdF1d795aB; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint) { uint compBalance = 0; for(uint i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)}); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta); } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)}); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta); } } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (_exData.srcAddr != KYBER_ETH_ADDRESS) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.offchainData.callData, 36, _exData.destAmount); } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); } else { success = false; } uint256 tokensSwaped = 0; if (success) { // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1800000; uint public BOOST_GAS_COST = 1800000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = _closeData.daiAmount; (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address user = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(_cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address user = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (feeAmount > _amount / 10) { feeAmount = _amount / 10; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); return feeAmount; } return 0; } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy); exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxyInterface proxy = DSProxyInterface(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function logEvent( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { (, uint sellAmount) = _sell(exchangeData); getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: cAddresses[0], cDebtAddr: cAddresses[1] }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } }
convert weth -> eth and send back
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } sendLeftOver(srcAddr); return srcAmount; }
7,334,170
[ 1, 6283, 341, 546, 317, 13750, 471, 1366, 1473, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 12, 2867, 389, 4816, 3178, 16, 1758, 389, 10488, 3178, 16, 2254, 389, 10488, 6275, 16, 1731, 3778, 389, 13996, 751, 13, 3903, 3849, 8843, 429, 1135, 12, 11890, 13, 288, 203, 203, 3639, 1758, 1705, 3178, 273, 13750, 774, 59, 546, 3178, 24899, 4816, 3178, 1769, 203, 203, 3639, 1758, 1570, 3178, 273, 13750, 774, 59, 546, 3178, 24899, 10488, 3178, 1769, 203, 203, 203, 203, 3639, 4232, 39, 3462, 12, 4816, 3178, 2934, 4626, 12053, 537, 12, 1974, 39, 67, 15140, 16, 2254, 19236, 21, 10019, 203, 203, 203, 203, 3639, 2254, 1705, 6275, 273, 531, 17247, 1358, 12, 1974, 39, 67, 15140, 2934, 70, 9835, 1595, 6275, 12, 10488, 3178, 16, 389, 10488, 6275, 16, 1705, 3178, 16, 2254, 19236, 21, 10019, 203, 203, 203, 203, 203, 3639, 309, 261, 10488, 3178, 422, 678, 1584, 44, 67, 15140, 13, 288, 203, 203, 5411, 29938, 12, 59, 1584, 44, 67, 15140, 2934, 1918, 9446, 24899, 10488, 6275, 1769, 203, 203, 5411, 1234, 18, 15330, 18, 13866, 24899, 10488, 6275, 1769, 203, 203, 203, 5411, 4232, 39, 3462, 12, 10488, 3178, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 389, 10488, 6275, 1769, 203, 203, 3639, 289, 203, 203, 203, 203, 3639, 1366, 3910, 4851, 12, 4816, 3178, 1769, 203, 203, 203, 203, 3639, 327, 1705, 6275, 31, 203, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x59df07Af93fd66373813476E79fd9649A15C46A7/sources/project_/contracts/BNB247.sol
When investment finished
uint256 finishTime = users[userAddress].deposits[i].start.add(plans[currentPlan].time.mul(1 days));
3,259,052
[ 1, 9434, 2198, 395, 475, 6708, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 9506, 202, 11890, 5034, 4076, 950, 273, 3677, 63, 1355, 1887, 8009, 323, 917, 1282, 63, 77, 8009, 1937, 18, 1289, 12, 412, 634, 63, 2972, 5365, 8009, 957, 18, 16411, 12, 21, 4681, 10019, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.11; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract ShibMonk is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; address public PCS; address deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _antibot; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Shib Monk"; string private _symbol = "SM"; uint8 private _decimals = 9; uint256 public _burnFee = 2; uint256 private _previousburnFee = _burnFee; uint256 public _speedbrakeFee = 86; uint256 private _previousspeedbrakeFee = _speedbrakeFee; uint256 public _taxFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 9; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public marketingDivisor = 9; uint256 public _maxTxAmount = _tTotal; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } bool speedbrake_bool = false; constructor () { marketingAddress = payable(owner()); _rOwned[owner()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; emit Transfer(address(0), owner(), _tTotal); swapAndLiquifyEnabled = true; _maxTxAmount = _maxTxAmount.div(100); minimumTokensBeforeSwap = _tTotal.div(1000); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludelp_FromReward(address account) public onlyOwner() { if(_rOwned[account] > 0) { _tOwned[account] = _tTotal.add(tokenFromReflection(_rOwned[account])); _tTotal = _tTotal + _tTotal; } _isExcluded[account] = true; _excluded.push(account); } function total_speedbrake_sell_fee()public view returns (uint256){ uint256 total_sell_tax = _taxFee.add(_burnFee).add(_liquidityFee).add(_speedbrakeFee); return uint256(total_sell_tax); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(_antibot[from] != true); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; if (!inSwapAndLiquify && swapAndLiquifyEnabled && to == uniswapV2Pair) { if (overMinimumTokenBalance) { contractTokenBalance = minimumTokensBeforeSwap; swapTokens(contractTokenBalance); } } bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance; //Send to Marketing address transferToAddressETH(marketingAddress, transferredBalance); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if(recipient == PCS && !_isExcludedFromFee[sender]){speedbrake_bool=true;} // If selling to pcs turn speedbrake on if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); speedbrake_bool = false; // Always make sure speedbrake is turned off when done } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity,tAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity,tAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity,tAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (,,uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _takeLiquidity(tLiquidity,tAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256 ,uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity, uint256 _amount) private { uint256 currentRate = _getRate(); uint256 tliqfee = _amount.mul(_liquidityFee).div(10**2); uint256 rLiquidity = tliqfee.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) {_tOwned[address(this)] = _tOwned[address(this)].add(tliqfee);} uint256 tburn = tLiquidity - tliqfee; uint256 rburn = tburn.mul(currentRate); _rOwned[address(deadAddress)] = _rOwned[address(deadAddress)].add(rburn); if(_isExcluded[address(deadAddress)]) {_tOwned[address(deadAddress)] = _tOwned[address(deadAddress)].add(tburn);} } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256 _totalamount) { uint256 liqfee = _amount.mul(_liquidityFee).div(10**2); uint256 cbfee = _amount.mul(_burnFee).div(10**2); uint256 sbamt; if(speedbrake_bool == true){sbamt = (_amount.mul(_speedbrakeFee)).div(10**2);} else{sbamt = 0;} return _totalamount.add(liqfee).add(sbamt).add(cbfee); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousspeedbrakeFee = _speedbrakeFee; _previousLiquidityFee = _liquidityFee; _previousburnFee = _burnFee; _taxFee = 0; _liquidityFee = 0; _burnFee = 0; _speedbrakeFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _speedbrakeFee = _previousspeedbrakeFee; _liquidityFee = _previousLiquidityFee; _burnFee = _previousburnFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } // Management Functions ***Owner Only*** // function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } //True blocks the bots address function set_antibot(address account, bool active) public onlyOwner() { _antibot[account] = active; } function setFees(uint256 burnfee, uint256 taxfee, uint256 liquidityFee, uint256 _marketingDivisor, uint256 _speedbrake) external onlyOwner() { _burnFee = burnfee; _taxFee = taxfee; _liquidityFee = liquidityFee; marketingDivisor = _marketingDivisor; _speedbrakeFee = _speedbrake; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() { minimumTokensBeforeSwap = _minimumTokensBeforeSwap; } function setMarketingAddress(address _marketingAddress, address _PCS, IUniswapV2Router02 _uniswapV2Router) external onlyOwner() { marketingAddress = payable(_marketingAddress); //Where bnb will be sent. PCS = _PCS; //So you can change what address speedbrake watches. Use exchange with greatest lp. uniswapV2Router = _uniswapV2Router; //For the router itself } function setUniswapAddress_forspeedbrake(address _PCS) external onlyOwner() { PCS = _PCS; //So you can change what address speedbrake watches. Use exchange with greatest lp. excludeFromReward(_PCS); //Lets go ahead and make sure that the lp pair doesn't get reflections excludeFromReward(deadAddress); //While we are at it, let's exclude the dead address from reflections as well. } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner() { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //If swap and liquify stops working, example Uniswap upgrade. You can use this to get the dev/marketing tokens. function emergency_token(uint256 total) public onlyOwner() { bool takeFEE = false; _tokenTransfer(address(this),marketingAddress,total,takeFEE); } //If someone sends ETH to contract on accident use this to get it out for them. function emergency_ETH(address payable recipient, uint256 amount) public onlyOwner { recipient.transfer(amount); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
Lets go ahead and make sure that the lp pair doesn't get reflections
excludeFromReward(_PCS);
6,129,232
[ 1, 48, 2413, 1960, 17510, 471, 1221, 3071, 716, 326, 12423, 3082, 3302, 1404, 336, 5463, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 4433, 1265, 17631, 1060, 24899, 3513, 55, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x95AB62FDA46949872e20b8726063721B52865857/sources/SushiToken.sol
SushiToken with Governance.
contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } mapping(address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); address indexed delegate, uint256 previousBalance, uint256 newBalance ); mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; mapping(address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = bytes32 public constant DELEGATION_TYPEHASH = mapping(address => uint256) public nonces; event DelegateChanged( event DelegateVotesChanged( function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint256 nonce, uint256 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), "SUSHI::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce" ); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _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)) { 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)) { 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 _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { 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)) { 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 _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { 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)) { 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 _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { 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)) { 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, "SUSHI::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32( block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
9,069,079
[ 1, 55, 1218, 77, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 1218, 77, 1345, 353, 4232, 39, 3462, 2932, 55, 1218, 77, 1345, 3113, 315, 6639, 2664, 45, 6, 3631, 14223, 6914, 288, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 3639, 417, 24410, 581, 5034, 12, 203, 5411, 315, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 203, 3639, 11272, 203, 203, 3639, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 203, 203, 3639, 1758, 8808, 11158, 639, 16, 203, 3639, 1758, 8808, 628, 9586, 16, 203, 3639, 1758, 8808, 358, 9586, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 7152, 16, 203, 3639, 2254, 5034, 2416, 13937, 16, 203, 3639, 2254, 5034, 394, 13937, 203, 565, 11272, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 12, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 2 ]
./full_match/1/0x71757da56B307c592A5e45c9B4CAB129bba8aD17/sources/src/token/Token.sol
Get the pointer to store the founder
Founder storage newFounder = founder[founderId];
2,955,417
[ 1, 967, 326, 4407, 358, 1707, 326, 284, 465, 765, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 478, 465, 765, 2502, 394, 42, 465, 765, 273, 284, 465, 765, 63, 74, 465, 765, 548, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.2; interface ILendingPoolAddressesProviderV2 { /** * @notice Get the current address for Aave LendingPool * @dev Lending pool is the core contract on which to call deposit */ function getLendingPool() external view returns (address); } interface IAaveATokenV2 { /** * @notice returns the current total aToken balance of _user all interest collected included. * To obtain the user asset principal balance with interests excluded , ERC20 non-standard * method principalBalanceOf() can be used. */ function balanceOf(address _user) external view returns(uint256); } interface IAaveLendingPoolV2 { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param reserve the address of the reserve * @param amount the amount to be deposited * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed * @param to address that will receive the underlying **/ function withdraw( address reserve, uint256 amount, address to ) external; } /** * @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 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); } } } } 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"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } 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; } } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; // keccak256("InterestValidator"); bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _liquidator() internal view returns (address) { return nexus.getModule(KEY_LIQUIDATOR); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } } 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; } } abstract contract AbstractIntegration is IPlatformIntegration, Initializable, ImmutableModule, ReentrancyGuard { event PTokenAdded(address indexed _bAsset, address _pToken); event Deposit(address indexed _bAsset, address _pToken, uint256 _amount); event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount); event PlatformWithdrawal( address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount ); // LP has write access address public immutable lpAddress; // bAsset => pToken (Platform Specific Token Address) mapping(address => address) public override bAssetToPToken; // Full list of all bAssets supported here address[] internal bAssetsMapped; /** * @param _nexus Address of the Nexus * @param _lp Address of LP */ constructor(address _nexus, address _lp) ReentrancyGuard() ImmutableModule(_nexus) { require(_lp != address(0), "Invalid LP address"); lpAddress = _lp; } /** * @dev Simple initializer to set first bAsset/pTokens */ function initialize(address[] calldata _bAssets, address[] calldata _pTokens) public initializer { uint256 len = _bAssets.length; require(len == _pTokens.length, "Invalid inputs"); for (uint256 i = 0; i < len; i++) { _setPTokenAddress(_bAssets[i], _pTokens[i]); } } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyLP() { require(msg.sender == lpAddress, "Only the LP can execute"); _; } /*************************************** CONFIG ****************************************/ /** * @dev Provide support for bAsset by passing its pToken address. * This method can only be called by the system Governor * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _bAsset, address _pToken) external onlyGovernor { _setPTokenAddress(_bAsset, _pToken); } /** * @dev Provide support for bAsset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _bAsset, address _pToken) internal { require(bAssetToPToken[_bAsset] == address(0), "pToken already set"); require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses"); bAssetToPToken[_bAsset] = _pToken; bAssetsMapped.push(_bAsset); emit PTokenAdded(_bAsset, _pToken); _abstractSetPToken(_bAsset, _pToken); } function _abstractSetPToken(address _bAsset, address _pToken) internal virtual; /** * @dev Simple helper func to get the min of two values */ function _min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } } interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later /** * @title PAaveIntegration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave on Polygon * @dev VERSION: 1.0 * DATE: 2020-16-11 */ contract PAaveIntegration is AaveV2Integration { event RewardsClaimed(address[] assets, uint256 amount); IAaveIncentivesController public immutable rewardController; /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any * @param _rewardController AaveIncentivesController */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken, address _rewardController ) AaveV2Integration(_nexus, _lp, _platformAddress, _rewardToken) { require(_rewardController != address(0), "Invalid controller address"); rewardController = IAaveIncentivesController(_rewardController); } /** * @dev Claims outstanding rewards from market */ function claimRewards() external { uint256 len = bAssetsMapped.length; address[] memory pTokens = new address[](len); for (uint256 i = 0; i < len; i++) { pTokens[i] = bAssetToPToken[bAssetsMapped[i]]; } uint256 rewards = rewardController.claimRewards(pTokens, type(uint256).max, address(this)); emit RewardsClaimed(pTokens, rewards); } }
* @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. @param _bAsset Address of the bAsset @return aToken Corresponding to this bAsset/
function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); }
139,958
[ 1, 967, 326, 293, 1345, 5805, 316, 326, 467, 37, 836, 789, 969, 1560, 364, 333, 324, 6672, 16, 358, 999, 1377, 364, 598, 9446, 310, 578, 11013, 6728, 18, 8911, 87, 309, 326, 293, 1345, 3302, 1404, 1005, 316, 3134, 7990, 18, 225, 389, 70, 6672, 225, 5267, 434, 326, 324, 6672, 327, 279, 1345, 225, 9557, 17863, 310, 358, 333, 324, 6672, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 789, 969, 1290, 12, 2867, 389, 70, 6672, 13, 2713, 1476, 1135, 261, 15188, 836, 789, 969, 58, 22, 13, 288, 203, 3639, 1758, 279, 1345, 273, 324, 6672, 774, 52, 1345, 63, 67, 70, 6672, 15533, 203, 3639, 2583, 12, 69, 1345, 480, 1758, 12, 20, 3631, 315, 69, 1345, 1552, 486, 1005, 8863, 203, 3639, 327, 467, 37, 836, 789, 969, 58, 22, 12, 69, 1345, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x434bAc5efbE635d1bA4284Cf9Fb0938c489C468F/sources/contracts/protocol/libraries/types/DataTypes.sol
Map of reserves and their data (underlyingAssetOfReserve => reserveData) Map of users address and their configuration data (userAddress => userConfiguration) List of reserves as a map (reserveId => reserve). It is structured as a mapping for gas savings reasons, using the reserve id as index Maximum number of active reserves there have been in the protocol. It is the upper bound of the reserves list Auction recovery health factor
struct PoolStorage { mapping(address => ReserveData) _reserves; mapping(address => UserConfigurationMap) _usersConfig; mapping(uint256 => address) _reservesList; uint16 _reservesCount; uint64 _auctionRecoveryHealthFactor; }
8,328,452
[ 1, 863, 434, 400, 264, 3324, 471, 3675, 501, 261, 9341, 6291, 6672, 951, 607, 6527, 516, 20501, 751, 13, 1635, 434, 3677, 1758, 471, 3675, 1664, 501, 261, 1355, 1887, 516, 729, 1750, 13, 987, 434, 400, 264, 3324, 487, 279, 852, 261, 455, 6527, 548, 516, 20501, 2934, 2597, 353, 19788, 487, 279, 2874, 364, 16189, 4087, 899, 14000, 16, 1450, 326, 20501, 612, 487, 770, 18848, 1300, 434, 2695, 400, 264, 3324, 1915, 1240, 2118, 316, 326, 1771, 18, 2597, 353, 326, 3854, 2489, 434, 326, 400, 264, 3324, 666, 432, 4062, 11044, 8437, 5578, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 8828, 3245, 288, 203, 3639, 2874, 12, 2867, 516, 1124, 6527, 751, 13, 389, 455, 264, 3324, 31, 203, 3639, 2874, 12, 2867, 516, 2177, 1750, 863, 13, 389, 5577, 809, 31, 203, 3639, 2874, 12, 11890, 5034, 516, 1758, 13, 389, 455, 264, 3324, 682, 31, 203, 3639, 2254, 2313, 389, 455, 264, 3324, 1380, 31, 203, 3639, 2254, 1105, 389, 69, 4062, 11548, 7802, 6837, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-18 */ // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @rari-capital/solmate/src/tokens/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // File @rari-capital/solmate/src/auth/[email protected] pragma solidity >=0.8.0; /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) abstract contract Auth { event OwnerUpdated(address indexed user, address indexed newOwner); event AuthorityUpdated(address indexed user, Authority indexed newAuthority); address public owner; Authority public authority; constructor(address _owner, Authority _authority) { owner = _owner; authority = _authority; emit OwnerUpdated(msg.sender, _owner); emit AuthorityUpdated(msg.sender, _authority); } modifier requiresAuth() { require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED"); _; } function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) { Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas. // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be // aware that this makes protected functions uncallable even to the owner if the authority is out of order. return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner; } function setAuthority(Authority newAuthority) public virtual { // We check if the caller is the owner first because we want to ensure they can // always swap out the authority even if it's reverting or using up a lot of gas. require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig)); authority = newAuthority; emit AuthorityUpdated(msg.sender, newAuthority); } function setOwner(address newOwner) public virtual requiresAuth { owner = newOwner; emit OwnerUpdated(msg.sender, newOwner); } } /// @notice A generic interface for a contract which provides authorization data to an Auth instance. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) interface Authority { function canCall( address user, address target, bytes4 functionSig ) external view returns (bool); } // File @rari-capital/solmate/src/utils/[email protected] pragma solidity >=0.8.0; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // File @rari-capital/solmate/src/utils/[email protected] pragma solidity >=0.8.0; /// @notice Safe unsigned integer casting library that reverts on overflow. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeCastLib.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol) library SafeCastLib { function safeCastTo248(uint256 x) internal pure returns (uint248 y) { require(x <= type(uint248).max); y = uint248(x); } function safeCastTo128(uint256 x) internal pure returns (uint128 y) { require(x <= type(uint128).max); y = uint128(x); } function safeCastTo96(uint256 x) internal pure returns (uint96 y) { require(x <= type(uint96).max); y = uint96(x); } function safeCastTo64(uint256 x) internal pure returns (uint64 y) { require(x <= type(uint64).max); y = uint64(x); } function safeCastTo32(uint256 x) internal pure returns (uint32 y) { require(x <= type(uint32).max); y = uint32(x); } } // File @rari-capital/solmate/src/utils/[email protected] pragma solidity >=0.8.0; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) library FixedPointMathLib { /*/////////////////////////////////////////////////////////////// COMMON BASE UNITS //////////////////////////////////////////////////////////////*/ uint256 internal constant YAD = 1e8; uint256 internal constant WAD = 1e18; uint256 internal constant RAY = 1e27; uint256 internal constant RAD = 1e45; /*/////////////////////////////////////////////////////////////// FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function fmul( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(x == 0 || (x * y) / x == y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } // If baseUnit is zero this will return zero instead of reverting. z := div(z, baseUnit) } } function fdiv( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { // Store x * baseUnit in z for now. z := mul(x, baseUnit) // Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit)) if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) { revert(0, 0) } // We ensure y is not zero above, so there is never division by zero here. z := div(z, y) } } function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := baseUnit } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store baseUnit in z for now. z := baseUnit } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, baseUnit) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, baseUnit) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, baseUnit) } } } } } /*/////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { // Start off with z at 1. z := 1 // Used below to help find a nearby power of 2. let y := x // Find the lowest power of 2 that is at least sqrt(x). if iszero(lt(y, 0x100000000000000000000000000000000)) { y := shr(128, y) // Like dividing by 2 ** 128. z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { y := shr(64, y) // Like dividing by 2 ** 64. z := shl(32, z) } if iszero(lt(y, 0x100000000)) { y := shr(32, y) // Like dividing by 2 ** 32. z := shl(16, z) } if iszero(lt(y, 0x10000)) { y := shr(16, y) // Like dividing by 2 ** 16. z := shl(8, z) } if iszero(lt(y, 0x100)) { y := shr(8, y) // Like dividing by 2 ** 8. z := shl(4, z) } if iszero(lt(y, 0x10)) { y := shr(4, y) // Like dividing by 2 ** 4. z := shl(2, z) } if iszero(lt(y, 0x8)) { // Equivalent to 2 ** z. z := shl(1, z) } // Shifting right by 1 is like dividing by 2. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // Compute a rounded down version of z. let zRoundDown := div(x, z) // If zRoundDown is smaller, use it. if lt(zRoundDown, z) { z := zRoundDown } } } } // File srcBuild/interfaces/vader/IVaderMinter.sol pragma solidity ^0.8.11; interface IVaderMinter { struct Limits { uint256 fee; uint256 mintLimit; uint256 burnLimit; } event PublicMintCapChanged( uint256 previousPublicMintCap, uint256 publicMintCap ); event PublicMintFeeChanged( uint256 previousPublicMintFee, uint256 publicMintFee ); event PartnerMintCapChanged( uint256 previousPartnerMintCap, uint256 partnerMintCap ); event PartnerMintFeeChanged( uint256 previousPartnercMintFee, uint256 partnerMintFee ); event DailyLimitsChanged(Limits previousLimits, Limits nextLimits); event WhitelistPartner( address partner, uint256 mintLimit, uint256 burnLimit, uint256 fee ); function lbt() external view returns (address); // The 24 hour limits on USDV mints that are available for public minting and burning as well as the fee. function dailyLimits() external view returns (Limits memory); // The current cycle end timestamp function cycleTimestamp() external view returns (uint); // The current cycle cumulative mints function cycleMints() external view returns (uint); // The current cycle cumulative burns function cycleBurns() external view returns (uint); function partnerLimits(address) external view returns (Limits memory); // USDV Contract for Mint / Burn Operations function usdv() external view returns (address); function partnerMint(uint256 vAmount, uint256 uAmountMinOut) external returns (uint256 uAmount); function partnerBurn(uint256 uAmount, uint256 vAmountMinOut) external returns (uint256 vAmount); } // File srcBuild/VaderGateway.sol pragma solidity ^0.8.11; contract VaderGateway is Auth, IVaderMinter { using SafeTransferLib for ERC20; using FixedPointMathLib for uint256; using SafeCastLib for uint256; IVaderMinter public immutable VADERMINTER; ERC20 public immutable VADER; ERC20 public immutable USDV; constructor( address VADERMINTER_, address GOVERNANCE_, Authority AUTHORITY_, address VADER_, address USDV_ ) Auth(GOVERNANCE_, Authority(AUTHORITY_)) { VADERMINTER = IVaderMinter(VADERMINTER_); VADER = ERC20(VADER_); USDV = ERC20(USDV_); //set approvals VADER.safeApprove(VADERMINTER_, type(uint256).max); VADER.safeApprove(address(USDV), type(uint256).max); USDV.safeApprove(VADERMINTER_, type(uint256).max); } function lbt() external view returns (address) { return VADERMINTER.lbt(); } // The 24 hour limits on USDV mints that are available for public minting and burning as well as the fee. function dailyLimits() external view returns (Limits memory) { return VADERMINTER.dailyLimits(); } // The current cycle end timestamp function cycleTimestamp() external view returns (uint) { return VADERMINTER.cycleTimestamp(); } // The current cycle cumulative mints function cycleMints() external view returns (uint) { return VADERMINTER.cycleMints(); } // The current cycle cumulative burns function cycleBurns() external view returns (uint){ return VADERMINTER.cycleBurns(); } function partnerLimits(address partner) external view returns (Limits memory){ return VADERMINTER.partnerLimits(partner); } // USDV Contract for Mint / Burn Operations function usdv() external view returns (address) { return VADERMINTER.usdv(); } /* * @dev Partner mint function that receives Vader and mints USDV. * @param vAmount Vader amount to burn. * @returns uAmount in USDV, represents the USDV amount received from the mint. * * Requirements: * - Can only be called by whitelisted partners. **/ function partnerMint(uint256 vAmount, uint256 uMinOut) external requiresAuth returns (uint256 uAmount) { VADER.transferFrom(msg.sender, address(this), vAmount); uAmount = VADERMINTER.partnerMint(vAmount, uMinOut); USDV.safeTransfer(msg.sender, uAmount); } /* * @dev Partner burn function that receives USDV and mints Vader. * @param uAmount USDV amount to burn. * @returns vAmount in Vader, represents the Vader amount received from the mint. * * Requirements: * - Can only be called by whitelisted partners. **/ function partnerBurn(uint256 uAmount, uint256 vMinOut) external requiresAuth returns (uint256 vAmount) { USDV.transferFrom(msg.sender, address(this), uAmount); vAmount = VADERMINTER.partnerBurn(uAmount, vMinOut); VADER.safeTransfer(msg.sender, vAmount); } }
@notice Arithmetic library with operations for fixed-point numbers. @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib { COMMON BASE UNITS uint256 internal constant YAD = 1e8; uint256 internal constant WAD = 1e18; uint256 internal constant RAY = 1e27; uint256 internal constant RAD = 1e45; FIXED POINT OPERATIONS function fmul( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { z := mul(x, y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } } } ) internal pure returns (uint256 z) { assembly { z := mul(x, y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } } } ) internal pure returns (uint256 z) { assembly { z := mul(x, y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } } } z := div(z, baseUnit) function fdiv( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { z := mul(x, baseUnit) if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) { revert(0, 0) } } } function fdiv( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { z := mul(x, baseUnit) if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) { revert(0, 0) } } } function fdiv( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { z := mul(x, baseUnit) if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) { revert(0, 0) } } } z := div(z, y) function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES let half := shr(1, baseUnit) function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES } n { } { function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES let xx := mul(x, x) let xxRound := add(xx, half) function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES x := div(xxRound, baseUnit) function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES let zxRound := add(zx, half) function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := baseUnit } default { z := 0 } } default { switch mod(n, 2) case 0 { z := baseUnit } default { z := x } for { n := shr(1, n) n := shr(1, n) if shr(128, x) { revert(0, 0) } if lt(xxRound, xx) { revert(0, 0) } if mod(n, 2) { let zx := mul(z, x) if iszero(eq(div(zx, x), z)) { if iszero(iszero(x)) { revert(0, 0) } } if lt(zxRound, zx) { revert(0, 0) } } } } } } GENERAL NUMBER UTILITIES z := div(zxRound, baseUnit) function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } z := shr(1, add(z, div(x, z))) let zRoundDown := div(x, z) function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { z := 1 let y := x if iszero(lt(y, 0x100000000000000000000000000000000)) { z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { z := shl(32, z) } if iszero(lt(y, 0x100000000)) { z := shl(16, z) } if iszero(lt(y, 0x10000)) { z := shl(8, z) } if iszero(lt(y, 0x100)) { z := shl(4, z) } if iszero(lt(y, 0x10)) { z := shl(2, z) } if iszero(lt(y, 0x8)) { z := shl(1, z) } z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) if lt(zRoundDown, z) { z := zRoundDown } } } }
6,790,213
[ 1, 686, 16368, 5313, 598, 5295, 364, 5499, 17, 1153, 5600, 18, 225, 348, 355, 81, 340, 261, 4528, 2207, 6662, 18, 832, 19, 54, 12954, 17, 4664, 7053, 19, 18281, 81, 340, 19, 10721, 19, 5254, 19, 4816, 19, 5471, 19, 7505, 2148, 10477, 5664, 18, 18281, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 15038, 2148, 10477, 5664, 288, 203, 18701, 5423, 17667, 10250, 5019, 10158, 203, 203, 565, 2254, 5034, 2713, 5381, 1624, 1880, 273, 404, 73, 28, 31, 203, 565, 2254, 5034, 2713, 5381, 678, 1880, 273, 404, 73, 2643, 31, 203, 565, 2254, 5034, 2713, 5381, 534, 5255, 273, 404, 73, 5324, 31, 203, 565, 2254, 5034, 2713, 5381, 534, 1880, 273, 404, 73, 7950, 31, 203, 203, 7682, 26585, 13803, 3217, 17205, 15297, 203, 203, 565, 445, 10940, 332, 12, 203, 3639, 2254, 5034, 619, 16, 203, 3639, 2254, 5034, 677, 16, 203, 3639, 2254, 5034, 1026, 2802, 203, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 19931, 288, 203, 5411, 998, 519, 14064, 12, 92, 16, 677, 13, 203, 203, 5411, 309, 353, 7124, 12, 280, 12, 291, 7124, 12, 92, 3631, 7555, 12, 2892, 12, 94, 16, 619, 3631, 677, 20349, 288, 203, 7734, 15226, 12, 20, 16, 374, 13, 203, 5411, 289, 203, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 19931, 288, 203, 5411, 998, 519, 14064, 12, 92, 16, 677, 13, 203, 203, 5411, 309, 353, 7124, 12, 280, 12, 291, 7124, 12, 92, 3631, 7555, 12, 2892, 12, 94, 16, 619, 3631, 677, 20349, 288, 203, 7734, 15226, 12, 20, 16, 374, 13, 203, 5411, 289, 203, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 2 ]
pragma solidity ^0.4.24; import "../Markets/Market.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "../Events/Event.sol"; import "../MarketMakers/MarketMaker.sol"; contract StandardMarketData { /* * Constants */ uint24 public constant FEE_RANGE = 1000000; // 100% } contract StandardMarketProxy is Proxy, MarketData, StandardMarketData { constructor(address proxy, address _creator, Event _eventContract, MarketMaker _marketMaker, uint24 _fee) Proxy(proxy) public { // Validate inputs require(address(_eventContract) != 0 && address(_marketMaker) != 0 && _fee < FEE_RANGE); creator = _creator; createdAtBlock = block.number; eventContract = _eventContract; netOutcomeTokensSold = new int[](eventContract.getOutcomeCount()); fee = _fee; marketMaker = _marketMaker; stage = Stages.MarketCreated; } } /// @title Standard market contract - Backed implementation of standard markets /// @author Stefan George - <stefan@gnosis.pm> contract StandardMarket is Proxied, Market, StandardMarketData { using SafeMath for *; /* * Modifiers */ modifier isCreator() { // Only creator is allowed to proceed require(msg.sender == creator); _; } modifier atStage(Stages _stage) { // Contract has to be in given stage require(stage == _stage); _; } /* * Public functions */ /// @dev Allows to fund the market with collateral tokens converting them into outcome tokens /// @param _funding Funding amount function fund(uint _funding) public isCreator atStage(Stages.MarketCreated) { // Request collateral tokens and allow event contract to transfer them to buy all outcomes require( eventContract.collateralToken().transferFrom(msg.sender, this, _funding) && eventContract.collateralToken().approve(eventContract, _funding)); eventContract.buyAllOutcomes(_funding); funding = _funding; stage = Stages.MarketFunded; emit MarketFunding(funding); } /// @dev Allows market creator to close the markets by transferring all remaining outcome tokens to the creator function close() public isCreator atStage(Stages.MarketFunded) { uint8 outcomeCount = eventContract.getOutcomeCount(); for (uint8 i = 0; i < outcomeCount; i++) require(eventContract.outcomeTokens(i).transfer(creator, eventContract.outcomeTokens(i).balanceOf(this))); stage = Stages.MarketClosed; emit MarketClosing(); } /// @dev Allows market creator to withdraw fees generated by trades /// @return Fee amount function withdrawFees() public isCreator returns (uint fees) { fees = eventContract.collateralToken().balanceOf(this); // Transfer fees require(eventContract.collateralToken().transfer(creator, fees)); emit FeeWithdrawal(fees); } /// @dev Allows to trade outcome tokens and collateral with the market maker /// @param outcomeTokenAmounts Amounts of each outcome token to buy or sell. If positive, will buy this amount of outcome token from the market. If negative, will sell this amount back to the market instead. /// @param collateralLimit If positive, this is the limit for the amount of collateral tokens which will be sent to the market to conduct the trade. If negative, this is the minimum amount of collateral tokens which will be received from the market for the trade. If zero, there is no limit. /// @return If positive, the amount of collateral sent to the market. If negative, the amount of collateral received from the market. If zero, no collateral was sent or received. function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); // Calculate net cost for executing trade int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); } else { require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { // This is safe since // 0x8000000000000000000000000000000000000000000000000000000000000000 == // uint(-int(-0x8000000000000000000000000000000000000000000000000000000000000000)) eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } /// @dev Calculates fee to be paid to market maker /// @param outcomeTokenCost Cost for buying outcome tokens /// @return Fee for trade function calcMarketFee(uint outcomeTokenCost) public view returns (uint) { return outcomeTokenCost * fee / FEE_RANGE; } }
@title Standard market contract - Backed implementation of standard markets @author Stefan George - <stefan@gnosis.pm>
contract StandardMarket is Proxied, Market, StandardMarketData { using SafeMath for *; modifier isCreator() { require(msg.sender == creator); _; } modifier atStage(Stages _stage) { require(stage == _stage); _; } function fund(uint _funding) public isCreator atStage(Stages.MarketCreated) { require( eventContract.collateralToken().transferFrom(msg.sender, this, _funding) && eventContract.collateralToken().approve(eventContract, _funding)); eventContract.buyAllOutcomes(_funding); funding = _funding; stage = Stages.MarketFunded; emit MarketFunding(funding); } function close() public isCreator atStage(Stages.MarketFunded) { uint8 outcomeCount = eventContract.getOutcomeCount(); for (uint8 i = 0; i < outcomeCount; i++) require(eventContract.outcomeTokens(i).transfer(creator, eventContract.outcomeTokens(i).balanceOf(this))); stage = Stages.MarketClosed; emit MarketClosing(); } function withdrawFees() public isCreator returns (uint fees) { fees = eventContract.collateralToken().balanceOf(this); require(eventContract.collateralToken().transfer(creator, fees)); emit FeeWithdrawal(fees); } function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } } else { function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } function trade(int[] outcomeTokenAmounts, int collateralLimit) public atStage(Stages.MarketFunded) returns (int netCost) { uint8 outcomeCount = eventContract.getOutcomeCount(); require(outcomeTokenAmounts.length == outcomeCount); int outcomeTokenNetCost = marketMaker.calcNetCost(this, outcomeTokenAmounts); int fees; if(outcomeTokenNetCost < 0) fees = int(calcMarketFee(uint(-outcomeTokenNetCost))); else fees = int(calcMarketFee(uint(outcomeTokenNetCost))); require(fees >= 0); netCost = outcomeTokenNetCost.add(fees); require( (collateralLimit != 0 && netCost <= collateralLimit) || collateralLimit == 0 ); if(outcomeTokenNetCost > 0) { require( eventContract.collateralToken().transferFrom(msg.sender, this, uint(netCost)) && eventContract.collateralToken().approve(eventContract, uint(outcomeTokenNetCost)) ); eventContract.buyAllOutcomes(uint(outcomeTokenNetCost)); } for (uint8 i = 0; i < outcomeCount; i++) { if(outcomeTokenAmounts[i] != 0) { if(outcomeTokenAmounts[i] < 0) { require(eventContract.outcomeTokens(i).transferFrom(msg.sender, this, uint(-outcomeTokenAmounts[i]))); require(eventContract.outcomeTokens(i).transfer(msg.sender, uint(outcomeTokenAmounts[i]))); } netOutcomeTokensSold[i] = netOutcomeTokensSold[i].add(outcomeTokenAmounts[i]); } } if(outcomeTokenNetCost < 0) { eventContract.sellAllOutcomes(uint(-outcomeTokenNetCost)); if(netCost < 0) { require(eventContract.collateralToken().transfer(msg.sender, uint(-netCost))); } } emit OutcomeTokenTrade(msg.sender, outcomeTokenAmounts, outcomeTokenNetCost, uint(fees)); } function calcMarketFee(uint outcomeTokenCost) public view returns (uint) { return outcomeTokenCost * fee / FEE_RANGE; } }
12,533,793
[ 1, 8336, 13667, 6835, 300, 4297, 329, 4471, 434, 4529, 2267, 2413, 225, 7780, 74, 304, 15391, 280, 908, 300, 411, 334, 10241, 304, 36, 1600, 538, 291, 18, 7755, 34, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8263, 3882, 278, 353, 1186, 92, 2092, 16, 6622, 278, 16, 8263, 3882, 278, 751, 288, 203, 565, 1450, 14060, 10477, 364, 380, 31, 203, 203, 565, 9606, 353, 10636, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 11784, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 622, 8755, 12, 31359, 389, 12869, 13, 288, 203, 3639, 2583, 12, 12869, 422, 389, 12869, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 284, 1074, 12, 11890, 389, 74, 14351, 13, 203, 3639, 1071, 203, 3639, 353, 10636, 203, 3639, 622, 8755, 12, 31359, 18, 3882, 278, 6119, 13, 203, 565, 288, 203, 3639, 2583, 12, 282, 871, 8924, 18, 12910, 2045, 287, 1345, 7675, 13866, 1265, 12, 3576, 18, 15330, 16, 333, 16, 389, 74, 14351, 13, 203, 7734, 597, 871, 8924, 18, 12910, 2045, 287, 1345, 7675, 12908, 537, 12, 2575, 8924, 16, 389, 74, 14351, 10019, 203, 3639, 871, 8924, 18, 70, 9835, 1595, 1182, 10127, 24899, 74, 14351, 1769, 203, 3639, 22058, 273, 389, 74, 14351, 31, 203, 3639, 6009, 273, 934, 1023, 18, 3882, 278, 42, 12254, 31, 203, 3639, 3626, 6622, 278, 42, 14351, 12, 74, 14351, 1769, 203, 565, 289, 203, 203, 565, 445, 1746, 1435, 203, 3639, 1071, 203, 3639, 353, 10636, 203, 3639, 622, 8755, 12, 31359, 18, 3882, 278, 42, 12254, 13, 203, 565, 288, 203, 3639, 2254, 28, 12884, 1380, 273, 871, 8924, 18, 588, 19758, 1380, 5621, 203, 3639, 364, 261, 11890, 28, 2 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol // pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and 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/ERC721/extensions/IERC721Enumerable.sol // pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol // pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // File: @chainlink/contracts/src/v0.8/VRFRequestIDBase.sol // pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: @chainlink/contracts/src/v0.8/VRFConsumerBase.sol // pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // File: src/contracts/Tierra.sol // pragma solidity ^0.8.6; // Imports // Tierra abstract contract Tierra is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard, VRFConsumerBase { // The total supply. uint256 public maxSupply; // The min/max number of NFTs that a user can purchase in one order. uint256 public minQuantity = 1; uint256 public maxQuantity = 100; // Metadata URI. string public baseURI = ""; string public fileEXT = ".json"; // The price of a single NFT token. uint256 public price = 0.055 ether; // The sale status. bool public isSaleActive = false; // The competition status. bool public isCompetitionActive = true; // The competition amount - 100 ETH!. uint256 public constant competitionAmount = 100 ether; // The competition's random number generator properties. bytes32 internal keyHash; uint256 public oracleFee; bytes32 internal requestId; uint256 public randomResult; // Contract data. struct ContractData { uint256 maxSupply; uint256 totalSupply; uint256 remainingTokens; address contractAddress; bool isSaleActive; bool isCompetitionActive; uint256 competitionAmount; uint256 price; string baseURI; uint256 oracleFee; uint256 randomResult; } /** * @dev Constructor. * @param name: The contract name. * @param symbol: The contract symbol. * @param _maxSupply: The maximum token supply. * @param _baseTokenURI: The base URI for token metadata. * @param _isCompetitionEnabled: Enable the competition for this contract. * @param vrfCoordinator: The Chainlink VRF coordinator address for the current network. * @param linkContractAddress: The Chainlink token's contract address for the current network. * @param _keyHash: The Chainlink oracle's keyhash for the current network. * @param _oracleFee: The Chainlink oracle's transaction fee. */ constructor( string memory name, string memory symbol, uint256 _maxSupply, string memory _baseTokenURI, bool _isCompetitionEnabled, address vrfCoordinator, address linkContractAddress, bytes32 _keyHash, uint256 _oracleFee ) ERC721(name, symbol) VRFConsumerBase(vrfCoordinator, linkContractAddress) { maxSupply = _maxSupply; baseURI = _baseTokenURI; isCompetitionActive = _isCompetitionEnabled; keyHash = _keyHash; oracleFee = _oracleFee; } /** * @dev Mint tokens. * @param quantity: The number of tokens to mint. */ function mint(uint256 quantity) public payable { require(!isSoldOut(), "Sold out."); require(isSaleActive, "The sale is not active."); require(quantity >= minQuantity, "Quantity must be at least 1."); require(quantity <= maxQuantity, "Maximum quantity exceeded."); require((totalSupply() + quantity) <= maxSupply, "Purchase exceeds remaining tokens."); require(msg.value >= (price * quantity), "Incorrect amount sent."); // Mint tokens. for(uint256 i = 0; i < quantity; ++i) { uint256 tokenIndex = totalSupply(); if (tokenIndex < maxSupply) { _safeMint(msg.sender, tokenIndex); } } // Trigger the competition payout when the last token is sold. if (isSoldOut() && isCompetitionActive && ownerOf(maxSupply-1) == msg.sender) { requestRandomness(); } } /** * @dev Return all public contract data. */ function getData() public view virtual returns (ContractData memory) { return ContractData( maxSupply, totalSupply(), remainingTokens(), address(this), isSaleActive, isCompetitionActive, competitionAmount, price, baseURI, oracleFee, randomResult ); } /** * @dev Return true if all tokens have been sold. */ function isSoldOut() public view virtual returns (bool) { return totalSupply() >= maxSupply; } /** * @dev Return the number of remaining tokens. */ function remainingTokens() public view virtual returns (uint256) { return maxSupply - totalSupply(); } /** * @dev Set the flag isSaleActive. * @param active: The sale's new active status. */ function setSaleActive(bool active) public onlyOwner { isSaleActive = active; } /** * @dev Call base class: ERC721Enumerable._beforeTokenTransfer(). */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev Call base class: ERC721Enumerable.supportsInterface(). */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Return the metadata URI for a token. * @param tokenId: The id of the token to get the URI for. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory uri = _baseURI(); return bytes(uri).length > 0 ? string(abi.encodePacked(uri, Strings.toString(tokenId), fileEXT)) : ""; } /** * @dev Return the base URI for token metadata. */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Set the base URI for token metadata. * @param uri: The new base URI. */ function setBaseURI(string memory uri) public onlyOwner { baseURI = uri; } /** * @dev Set the metadata URI file extension. * @param ext: The new file extension. */ function setBaseEXT(string memory ext) public onlyOwner { fileEXT = ext; } /** * @dev Set the NFT token sale price. * @param value: The new token price. */ function setPrice(uint256 value) public onlyOwner { require(value > 0, "Price must be greater than 0."); price = value; } /** * @dev Set the max number of tokens that can be purchased in one order. * @param value: The new max quantity. */ function setMaxQuantity(uint256 value) public onlyOwner { require(value > 0, "Max quantity must be greater than 0."); maxQuantity = value; } /** * @dev Set the oracle fee for the chainlink network. * @param value: The new oracle fee. */ function setOracleFee(uint256 value) public onlyOwner { require(value > 0, "Oracle fee must be greater than 0."); oracleFee = value; } /** * @dev Return the contract's current ETH balance. */ function balance() public view virtual returns (uint256) { return address(this).balance; } /** * @dev Return the contract's current LINK balance. */ function linkBalance() public view virtual returns (uint256) { return LINK.balanceOf(address(this)); } /** * @dev Withdraw the current ETH balance (minus the competition payout) to the owner's wallet. */ function withdraw() public payable onlyOwner { uint256 amount = balance() - (isCompetitionActive ? competitionAmount : 0); require(amount > 0, "Insufficient balance."); payable(msg.sender).transfer(amount); } /** * @dev Withdraw the current LINK balance to the owner's wallet. */ function linkWithdraw() public payable onlyOwner { uint256 amount = linkBalance(); require(amount > 0, "Insufficient LINK balance."); LINK.transfer(msg.sender, amount); } /** * @dev Random number generator (requestRandomness()) callback function. * @dev Send 100 ETH to a random address. */ function fulfillRandomness(bytes32 _requestId, uint256 randomness) internal override nonReentrant { require(requestId == _requestId); require(isSoldOut(), "The sale is not complete."); require(isCompetitionActive, "The competition is over."); isCompetitionActive = false; randomResult = randomness % maxSupply; payable(ownerOf(randomResult)).transfer(competitionAmount); } /** * @dev Trigger the competition payout (internally). */ function requestRandomness() internal nonReentrant { require(LINK.balanceOf(address(this)) >= oracleFee, "Insufficient LINK balance."); requestId = requestRandomness(keyHash, oracleFee); } /** * @dev Trigger the competition payout (externally). */ function competitionPayout() public payable onlyOwner { require(isSoldOut(), "The sale is not complete."); require(isCompetitionActive, "The competition is over."); requestRandomness(); } /** * @dev Return the address of the competition winner (or 0x0 if the competition has not finished). */ function competitionWinner() public view virtual returns (address) { return isCompetitionActive ? address(0) : ownerOf(randomResult); } } // File: src/contracts/TierraPart2.sol // pragma solidity ^0.8.6; // Imports // Tierra Part 2 contract TierraPart2 is Tierra { /** * @dev Constructor * @param name: The contract name. * @param symbol: The contract symbol. * @param maxSupply: The maximum token supply. * @param baseURI: The base URI for all NFT tokens. * @param vrfCoordinator: The Chainlink VRF coordinator address for the current network. * @param linkContractAddress: The Chainlink token's contract address for the current network. * @param keyHash: The Chainlink oracle's keyhash for the current network. */ constructor( string memory name, string memory symbol, uint256 maxSupply, string memory baseURI, address vrfCoordinator, address linkContractAddress, bytes32 keyHash, uint256 oracleFee ) Tierra( name, symbol, maxSupply, baseURI, true, vrfCoordinator, linkContractAddress, keyHash, oracleFee ) { } }
* @dev Return the contract's current LINK balance./
function linkBalance() public view virtual returns (uint256) { return LINK.balanceOf(address(this)); }
10,052,400
[ 1, 990, 326, 6835, 1807, 783, 22926, 11013, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1692, 13937, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 22926, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; interface token { function transferFrom (address _from,address _to, uint256 _value) external returns (bool success); function approve (address _spender,uint256 _value) external; function transfer(address _to, uint256 _value) external; } contract TrinityEvent{ event Deposit(bytes32 channleId, address partnerA, uint256 amountA,address partnerB, uint256 amountB); event UpdateDeposit(bytes32 channleId, address partnerA, uint256 amountA, address partnerB, uint256 amountB); event QuickCloseChannel(bytes32 channleId, address closer, uint256 amount1, address partner, uint256 amount2); event CloseChannel(bytes32 channleId, address closer, address partner); event UpdateTransaction(bytes32 channleId, address partnerA, uint256 amountA, address partnerB, uint256 amountB); event Settle(bytes32 channleId, address partnerA, uint256 amountA, address partnerB, uint256 amountB); event Withdraw(bytes32 channleId, bytes32 hashLock); event WithdrawUpdate(bytes32 channleId, bytes32 hashLock, uint256 balance); event WithdrawSettle(bytes32 channleId, bytes32 hashLock, uint256 balance); event SetSettleTimeout(uint256 timeoutBlock); event SetToken(address tokenValue); } contract Owner{ address public owner; bool paused; constructor() public{ owner = msg.sender; paused = false; } modifier onlyOwner(){ require(owner == msg.sender); _; } modifier whenNotPaused(){ require(!paused); _; } modifier whenPaused(){ require(paused); _; } //disable contract setting funciton function pause() external onlyOwner whenNotPaused { paused = true; } //enable contract setting funciton function unpause() public onlyOwner whenPaused { paused = false; } } contract VerifySignature{ function verifyTimelock(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockPeriod , uint256 lockAmount, bytes32 lockHash, bytes partnerAsignature, bytes partnerBsignature) internal pure returns(bool) { address recoverA = verifyLockSignature(channelId, nonce, sender, receiver, lockPeriod, lockAmount,lockHash, partnerAsignature); address recoverB = verifyLockSignature(channelId, nonce, sender, receiver, lockPeriod, lockAmount,lockHash, partnerBsignature); if ((recoverA == sender && recoverB == receiver) || (recoverA == receiver && recoverB == sender)){ return true; } return false; } function verifyLockSignature(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockPeriod , uint256 lockAmount, bytes32 lockHash, bytes signature) internal pure returns(address) { bytes32 data_hash; address recover_addr; data_hash=keccak256(channelId, nonce, sender, receiver, lockPeriod, lockAmount,lockHash); recover_addr=_recoverAddressFromSignature(signature,data_hash); return recover_addr; } /* * Funcion: parse both signature for check whether the transaction is valid * Parameters: * addressA: node address that deployed on same channel; * addressB: node address that deployed on same channel; * balanceA : nodaA assets amount; * balanceB : nodaB assets assets amount; * nonce: transaction nonce; * signatureA: A signature for this transaction; * signatureB: B signature for this transaction; * Return: * result: if both signature is valid, return TRUE, or return False. */ function verifyTransaction( bytes32 channelId, uint256 nonce, address addressA, uint256 balanceA, address addressB, uint256 balanceB, bytes signatureA, bytes signatureB) internal pure returns(bool result){ address recoverA; address recoverB; recoverA = recoverAddressFromSignature(channelId, nonce, addressA, balanceA, addressB, balanceB, signatureA); recoverB = recoverAddressFromSignature(channelId, nonce, addressA, balanceA, addressB, balanceB, signatureB); if ((recoverA == addressA && recoverB == addressB) || (recoverA == addressB && recoverB == addressA)){ return true; } return false; } function recoverAddressFromSignature( bytes32 channelId, uint256 nonce, address addressA, uint256 balanceA, address addressB, uint256 balanceB, bytes signature ) internal pure returns(address) { bytes32 data_hash; address recover_addr; data_hash=keccak256(channelId, nonce, addressA, balanceA, addressB, balanceB); recover_addr=_recoverAddressFromSignature(signature,data_hash); return recover_addr; } function _recoverAddressFromSignature(bytes signature,bytes32 dataHash) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; (r,s,v)=signatureSplit(signature); return ecrecoverDecode(dataHash,v, r, s); } function signatureSplit(bytes signature) pure internal returns (bytes32 r, bytes32 s, uint8 v) { assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := and(mload(add(signature, 65)), 0xff) } v=v+27; require((v == 27 || v == 28), "check v value"); } function ecrecoverDecode(bytes32 datahash,uint8 v,bytes32 r,bytes32 s) internal pure returns(address addr){ addr=ecrecover(datahash,v,r,s); return addr; } function computeMerkleRoot(bytes lock, bytes merkle_proof) pure internal returns (bytes32) { require(merkle_proof.length % 32 == 0); uint i; bytes32 h; bytes32 el; h = keccak256(lock); for (i = 32; i <= merkle_proof.length; i += 32) { assembly { el := mload(add(merkle_proof, i)) } if (h < el) { h = keccak256(h, el); } else { h = keccak256(el, h); } } return h; } } library SafeMath{ function add256(uint256 addend, uint256 augend) internal pure returns(uint256 result){ uint256 sum = addend + augend; assert(sum >= addend); return sum; } function sub256(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } contract TrinityContract is Owner, VerifySignature, TrinityEvent{ /* * Define public data interface * Mytoken: ERC20 standard token contract address * trinityData: story channel status and balance, support multiple channel; */ using SafeMath for uint256; enum status {None, Opening, Closing, Locking} struct ChannelData{ //data storage for RSMC transaction address channelCloser; /* closer address that closed channel first */ address channelSettler; address partner1; address partner2; uint256 channelTotalBalance; /*total balance that both participators deposit together*/ uint256 closingNonce; /* transaction nonce that channel closer */ uint256 expectedSettleBlock; /* the closing time for final settlement for RSMC */ uint256 closerSettleBalance; /* the balance that closer want to withdraw */ uint256 partnerSettleBalance; /* the balance that closer provided for partner can withdraw */ status channelStatus; /* channel current status */ bool channelExist; // data storage for HTLC transaction uint256 withdrawNonce; mapping(bytes32 => address) timeLockVerifier; mapping(bytes32 => address) timeLockWithdrawer; mapping(bytes32 => uint256) lockAmount; mapping(bytes32 => uint256) lockTime; mapping(bytes32 => bool) withdrawn_locks; } struct Data { mapping(bytes32 => ChannelData)channelInfo; uint8 channelNumber; uint256 settleTimeout; } token public Mytoken; Data public trinityData; // constructor function function TrinityContract(address token_address, uint256 Timeout) payable public { Mytoken=token(token_address); trinityData.settleTimeout = Timeout; trinityData.channelNumber = 0; } function getChannelCount() external view returns (uint256){ return trinityData.channelNumber; } function getChannelBalance(bytes32 channelId) external view returns (uint256){ ChannelData memory channelInfo = trinityData.channelInfo[channelId]; return channelInfo.channelTotalBalance; } function getChannelById(bytes32 channelId) external view returns(address channelCloser, address channelSettler, address partner1, address partner2, uint256 channelTotalBalance, uint256 closingNonce, uint256 expectedSettleBlock, uint256 closerSettleBalance, uint256 partnerSettleBalance, status channelStatus){ ChannelData memory channelInfo = trinityData.channelInfo[channelId]; channelCloser = channelInfo.channelCloser; channelSettler = channelInfo.channelSettler; partner1 = channelInfo.partner1; partner2 = channelInfo.partner2; channelTotalBalance = channelInfo.channelTotalBalance; closingNonce = channelInfo.closingNonce; expectedSettleBlock = channelInfo.expectedSettleBlock; closerSettleBalance = channelInfo.closerSettleBalance; partnerSettleBalance = channelInfo.partnerSettleBalance; channelStatus = channelInfo.channelStatus; } /* * Function: Set settle timeout value by contract owner only */ function setSettleTimeout(uint256 blockNumber) public onlyOwner{ trinityData.settleTimeout = blockNumber; emit SetSettleTimeout(blockNumber); } /* * Function: Set asset token address by contract owner only */ function setToken(address tokenAddress) external onlyOwner{ Mytoken=token(tokenAddress); emit SetToken(tokenAddress); } function createChannel(bytes32 channelId) internal { trinityData.channelInfo[channelId] = ChannelData(address(0), address(0), address(0), address(0), 0, 0, 0, 0, 0, status.Opening, true, 0); trinityData.channelNumber += 1; } /* * Function: 1. Lock both participants assets to the contract * 2. setup channel. * Before lock assets,both participants must approve contract can spend special amout assets. * Parameters: * partnerA: partner that deployed on same channel; * partnerB: partner that deployed on same channel; * amountA : partnerA will lock assets amount; * amountB : partnerB will lock assets amount; * signedStringA: partnerA signature for this transaction; * signedStringB: partnerB signature for this transaction; * Return: * Null; */ function deposit(bytes32 channelId, uint256 nonce, address funderAddress, uint256 funderAmount, address partnerAddress, uint256 partnerAmount, bytes funderSignature, bytes partnerSignature) payable external whenNotPaused{ //verify both signature to check the behavious is valid. require(verifyTransaction(channelId, nonce, funderAddress, funderAmount, partnerAddress, partnerAmount, funderSignature, partnerSignature) == true, "verify signature"); //if channel have existed, can not create it again require(trinityData.channelInfo[channelId].channelExist == false, "check whether channel exist"); //transfer both special assets to this contract. require(Mytoken.transferFrom(funderAddress,this,funderAmount) == true, "deposit from funder"); require(Mytoken.transferFrom(partnerAddress,this,partnerAmount) == true, "deposit from partner"); createChannel(channelId); emit Deposit(channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); } function updateDeposit(bytes32 channelId, uint256 nonce, address funderAddress, uint256 funderAmount, address partnerAddress, uint256 partnerAmount, bytes funderSignature, bytes partnerSignature) payable external whenNotPaused{ //verify both signature to check the behavious is valid. require(verifyTransaction(channelId, nonce, funderAddress, funderAmount, partnerAddress, partnerAmount, funderSignature, partnerSignature) == true, "verify signature"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; require(channelInfo.channelStatus == status.Opening, "check channel status"); //transfer both special assets to this contract. require(Mytoken.transferFrom(funderAddress,this,funderAmount) == true, "deposit from funder"); require(Mytoken.transferFrom(partnerAddress,this,partnerAmount) == true, "deposit from partner"); uint256 detlaBalance = funderAmount.add256(partnerAmount); channelInfo.channelTotalBalance = channelInfo.channelTotalBalance.add256(detlaBalance); emit UpdateDeposit(channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); } function quickCloseChannel(bytes32 channelId, uint256 nonce, address closer, uint256 closerBalance, address partner, uint256 partnerBalance, bytes closerSignature, bytes partnerSignature) payable external whenNotPaused{ uint256 closeTotalBalance = 0; //verify both signatures to check the behavious is valid require(verifyTransaction(channelId, nonce, closer, closerBalance, partner, partnerBalance, closerSignature, partnerSignature) == true, "verify signature"); require(nonce == 0, "check nonce"); require((msg.sender == closer || msg.sender == partner), "verify caller"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; //channel should be opening require(channelInfo.channelStatus == status.Opening, "check channel status"); //sum of both balance should not larger than total deposited assets closeTotalBalance = closerBalance.add256(partnerBalance); require(closeTotalBalance == channelInfo.channelTotalBalance); Mytoken.transfer(closer, closerBalance); Mytoken.transfer(partner, partnerBalance); trinityData.channelNumber -= 1; delete trinityData.channelInfo[channelId]; emit QuickCloseChannel(channelId, closer, closerBalance, partner, partnerBalance); } /* * Funcion: 1. set channel status as closing 2. withdraw assets for partner against closer 3. freeze closer settle assets untill setelement timeout or partner confirmed the transaction; * Parameters: * partnerA: partner that deployed on same channel; * partnerB: partner that deployed on same channel; * settleBalanceA : partnerA will withdraw assets amount; * settleBalanceB : partnerB will withdraw assets amount; * signedStringA: partnerA signature for this transaction; * signedStringB: partnerB signature for this transaction; * settleNonce: closer provided nonce for settlement; * Return: * Null; */ function closeChannel(bytes32 channelId, uint256 nonce, address closer, uint256 closeBalance, address partner, uint256 partnerBalance, bytes closerSignature, bytes partnerSignature) external whenNotPaused{ uint256 closeTotalBalance = 0; //verify both signatures to check the behavious is valid require(verifyTransaction(channelId, nonce, closer, closeBalance, partner, partnerBalance, closerSignature, partnerSignature) == true, "verify signature"); require(nonce != 0, "check nonce"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; //channel should be opening require(channelInfo.channelStatus == status.Opening, "check channel status"); //sum of both balance should not larger than total deposited assets closeTotalBalance = closeBalance.add256(partnerBalance); require(closeTotalBalance == channelInfo.channelTotalBalance, "check total balance"); require((msg.sender == closer || msg.sender == partner), "check caller"); channelInfo.channelStatus = status.Closing; channelInfo.channelCloser = msg.sender; channelInfo.closingNonce = nonce; if (msg.sender == closer){ //sender want close channel actively, withdraw partner balance firstly channelInfo.closerSettleBalance = closeBalance; channelInfo.partnerSettleBalance = partnerBalance; channelInfo.channelSettler = partner; } else if(msg.sender == partner) { channelInfo.closerSettleBalance = partnerBalance; channelInfo.partnerSettleBalance = closeBalance; channelInfo.channelSettler = closer; } channelInfo.expectedSettleBlock = block.number + trinityData.settleTimeout; emit CloseChannel(channelId, closer, partner); } /* * Funcion: After closer apply closed channle, partner update owner final transaction to check whether closer submitted invalid information * 1. if bothe nonce is same, the submitted settlement is valid, withdraw closer assets 2. if partner nonce is larger than closer, then jugement closer have submitted invalid data, withdraw closer assets to partner; 3. if partner nonce is less than closer, then jugement closer submitted data is valid, withdraw close assets. * Parameters: * partnerA: partner that deployed on same channel; * partnerB: partner that deployed on same channel; * updateBalanceA : partnerA will withdraw assets amount; * updateBalanceB : partnerB will withdraw assets amount; * signedStringA: partnerA signature for this transaction; * signedStringB: partnerB signature for this transaction; * settleNonce: closer provided nonce for settlement; * Return: * Null; */ function updateTransaction(bytes32 channelId, uint256 nonce, address partnerA, uint256 updateBalanceA, address partnerB, uint256 updateBalanceB, bytes signedStringA, bytes signedStringB) payable external whenNotPaused{ uint256 updateTotalBalance = 0; require(verifyTransaction(channelId, nonce, partnerA, updateBalanceA, partnerB, updateBalanceB, signedStringA, signedStringB) == true, "verify signature"); require(nonce != 0, "check nonce"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; // only when channel status is closing, node can call it require(channelInfo.channelStatus == status.Closing, "check channel status"); require((msg.sender == partnerA || msg.sender == partnerB), "check caller"); // channel closer can not call it require(msg.sender == channelInfo.channelSettler, "check settler"); //sum of both balance should not larger than total deposited assets updateTotalBalance = updateBalanceA.add256(updateBalanceB); require(updateTotalBalance == channelInfo.channelTotalBalance, "check total balance"); channelInfo.channelStatus = status.None; // if updated nonce is less than (or equal to) closer provided nonce, folow closer provided balance allocation if (nonce <= channelInfo.closingNonce){ Mytoken.transfer(channelInfo.channelCloser, channelInfo.closerSettleBalance); Mytoken.transfer(channelInfo.channelSettler, channelInfo.partnerSettleBalance); emit UpdateTransaction(channelId, channelInfo.channelCloser, channelInfo.closerSettleBalance, channelInfo.channelSettler, channelInfo.partnerSettleBalance); } // if updated nonce is equal to nonce+1 that closer provided nonce, folow partner provided balance allocation else if (nonce == (channelInfo.closingNonce + 1)){ Mytoken.transfer(partnerA, updateBalanceA); Mytoken.transfer(partnerB, updateBalanceB); emit UpdateTransaction(channelId, partnerA, updateBalanceA, partnerB, updateBalanceB); } // if updated nonce is larger than nonce+1 that closer provided nonce, determine closer provided invalid transaction, partner will also get closer assets else if (nonce > (channelInfo.closingNonce + 1)){ Mytoken.transfer(channelInfo.channelSettler, channelInfo.channelTotalBalance); emit UpdateTransaction(channelId, channelInfo.channelSettler, channelInfo.channelTotalBalance, channelInfo.channelCloser, 0); } delete trinityData.channelInfo[channelId]; trinityData.channelNumber -= 1; } /* * Function: after apply close channnel, closer can withdraw assets until special settle window period time over * Parameters: * partner: partner address that setup in same channel with sender; * Return: Null */ function settleTransaction(bytes32 channelId) payable external whenNotPaused{ ChannelData storage channelInfo = trinityData.channelInfo[channelId]; // only chanel closer can call the function and channel status must be closing require(msg.sender == channelInfo.channelCloser, "check closer"); require(channelInfo.channelStatus == status.Closing, "check channel status"); uint256 currentBlockHight = block.number; require(channelInfo.expectedSettleBlock < currentBlockHight, "check settle time"); channelInfo.channelStatus = status.None; // settle period have over and partner didn't provide final transaction information, contract will withdraw closer assets Mytoken.transfer(channelInfo.channelCloser, channelInfo.closerSettleBalance); Mytoken.transfer(channelInfo.channelSettler, channelInfo.partnerSettleBalance); // delete channel trinityData.channelNumber -= 1; delete trinityData.channelInfo[channelId]; emit Settle(channelId, channelInfo.channelCloser, channelInfo.closerSettleBalance, channelInfo.channelSettler, channelInfo.partnerSettleBalance); } function withdraw(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockTime , uint256 lockAmount, bytes32 lockHash, bytes partnerAsignature, bytes partnerBsignature, bytes32 secret) external{ require(verifyTimelock(channelId, nonce, sender, receiver, lockTime,lockAmount,lockHash,partnerAsignature,partnerBsignature) == true, "verify signature"); require(nonce != 0, "check nonce"); require(lockTime > block.number, "check lock time"); require(lockHash == keccak256(secret), "verify hash"); require((msg.sender == receiver), "check caller"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; require(channelInfo.withdrawn_locks[lockHash] == false, "check withdraw status"); require(nonce >= channelInfo.withdrawNonce); channelInfo.withdrawNonce = nonce; channelInfo.lockTime[lockHash] = lockTime; channelInfo.lockAmount[lockHash] = lockAmount; channelInfo.timeLockVerifier[lockHash] = sender; channelInfo.timeLockWithdrawer[lockHash] = receiver; channelInfo.withdrawn_locks[lockHash] = true; emit Withdraw(channelId, lockHash); } function withdrawUpdate(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockTime , uint256 lockAmount, bytes32 lockHash, bytes partnerAsignature, bytes partnerBsignature) external payable whenNotPaused{ require(verifyTimelock(channelId, nonce, sender, receiver, lockTime,lockAmount,lockHash,partnerAsignature,partnerBsignature) == true, "verify signature"); require(nonce != 0, "check nonce"); require(lockTime > block.number, "check lock time"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; require(channelInfo.withdrawn_locks[lockHash] == true, "check withdraw status"); require(msg.sender == channelInfo.timeLockVerifier[lockHash], "check verifier"); if (nonce <= channelInfo.withdrawNonce){ channelInfo.channelTotalBalance = channelInfo.channelTotalBalance.sub256(lockAmount); Mytoken.transfer(receiver, lockAmount); channelInfo.timeLockVerifier[lockHash] = address(0); channelInfo.timeLockWithdrawer[lockHash] = address(0); channelInfo.lockAmount[lockHash] = 0; channelInfo.lockTime[lockHash] = 0; emit WithdrawUpdate(channelId, lockHash, channelInfo.channelTotalBalance); } else if(nonce > channelInfo.withdrawNonce){ Mytoken.transfer(msg.sender, channelInfo.channelTotalBalance); // delete channel delete trinityData.channelInfo[channelId]; trinityData.channelNumber -= 1; emit WithdrawUpdate(channelId, lockHash, 0); } } function withdrawSettle(bytes32 channelId, bytes32 lockHash, bytes32 secret) external payable whenNotPaused{ address withdrawer; uint256 lockAmount; require(lockHash == keccak256(secret), "verify hash"); ChannelData storage channelInfo = trinityData.channelInfo[channelId]; require(channelInfo.withdrawn_locks[lockHash] == true, "check withdraw status"); require(channelInfo.lockTime[lockHash] < block.number, "check time lock"); withdrawer = channelInfo.timeLockWithdrawer[lockHash]; require(withdrawer == msg.sender, "check withdrawer"); lockAmount = channelInfo.lockAmount[lockHash]; channelInfo.channelTotalBalance = channelInfo.channelTotalBalance.sub256(lockAmount); Mytoken.transfer(withdrawer, lockAmount); channelInfo.timeLockVerifier[lockHash] = address(0); channelInfo.timeLockWithdrawer[lockHash] = address(0); channelInfo.lockAmount[lockHash] = 0; channelInfo.lockTime[lockHash] = 0; emit WithdrawSettle(channelId, lockHash, channelInfo.channelTotalBalance); } function () public { revert(); } }
enable contract setting funciton
function unpause() public onlyOwner whenPaused { paused = false; }
13,044,826
[ 1, 7589, 6835, 3637, 1326, 26949, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 19476, 1435, 1071, 1338, 5541, 1347, 28590, 288, 203, 3639, 17781, 273, 629, 31, 203, 565, 289, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.12; // SPDX-License-Identifier: MIT /* * @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 * {ReentrancMINTuard} 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 { } } // MineTokenContract with Governance. contract MineTokenContract is ERC20("MineToken", "MINT"), Ownable { /// @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); } } contract MINTChef 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 MINTs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accMINTPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accMINTPerShare` (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. MINTs to distribute per block. uint256 lastRewardBlock; // Last block number that MINTs distribution occurs. uint256 accMINTPerShare; // Accumulated MINTs per share, times 1e12. See below. } // The MINT TOKEN! MineTokenContract public MINT; // Dev address. address public devaddr; // Block number when bonus MINT period ends. uint256 public bonusEndBlock; // MINT tokens created per block. uint256 public MINTPerBlock; // Bonus muliplier for early MINT makers. uint256 public constant BONUS_MULTIPLIER = 1; // no bonus // No of blocks in a day - 6000 uint256 public constant perDayBlocks = 6000; // 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 poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when MINT 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( MineTokenContract _MINT, address _devaddr, uint256 _MINTPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { MINT = _MINT; devaddr = _devaddr; MINTPerBlock = _MINTPerBlock; 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, accMINTPerShare: 0 })); } // Update the given pool's MINT 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) ); } } // reward prediction at specific block function getRewardPerBlock(uint blockNumber) public view returns (uint256) { if (blockNumber >= startBlock){ uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks); if(blockDaysPassed <= 0){ return MINTPerBlock; } } } // View function to see pending MINTs on frontend. function pendingMINT(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMINTPerShare = pool.accMINTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rewardThisBlock = getRewardPerBlock(block.number); uint256 MINTReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint); accMINTPerShare = accMINTPerShare.add(MINTReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accMINTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables 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 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 rewardThisBlock = getRewardPerBlock(block.number); uint256 MINTReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint); MINT.mint(devaddr, MINTReward.div(24)); // 4% MINT.mint(address(this), MINTReward); pool.accMINTPerShare = pool.accMINTPerShare.add(MINTReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for MINT 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.accMINTPerShare).div(1e12).sub(user.rewardDebt); safeMINTTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accMINTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMINTPerShare).div(1e12).sub(user.rewardDebt); safeMINTTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accMINTPerShare).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 MINT transfer function, just in case if rounding error causes pool to not have enough MINTs. function safeMINTTransfer(address _to, uint256 _amount) internal { uint256 MINTBal = MINT.balanceOf(address(this)); if (_amount > MINTBal) { MINT.transfer(_to, MINTBal); } else { MINT.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
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 rewardThisBlock = getRewardPerBlock(block.number); uint256 MINTReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint); MINT.mint(address(this), MINTReward); pool.accMINTPerShare = pool.accMINTPerShare.add(MINTReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
11,781,016
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 2254, 5034, 19890, 2503, 1768, 273, 4170, 359, 1060, 2173, 1768, 12, 2629, 18, 2696, 1769, 203, 3639, 2254, 5034, 490, 3217, 17631, 1060, 273, 15027, 18, 16411, 12, 266, 2913, 2503, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 3639, 490, 3217, 18, 81, 474, 12, 2867, 12, 2211, 3631, 490, 3217, 17631, 1060, 1769, 203, 3639, 2845, 18, 8981, 49, 3217, 2173, 9535, 273, 2845, 18, 8981, 49, 3217, 2173, 9535, 18, 1289, 12, 49, 3217, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xdE874ad7cE27b6A01a996a03e5E1b81305aC6837/sources/contracts/FodlRewards/RewardsDistributor.sol
@dev Added to support recovering tokens sent by mistake or from airdrops
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { IERC20(tokenAddress).safeTransfer(owner(), tokenAmount); }
9,643,274
[ 1, 8602, 358, 2865, 5910, 310, 2430, 3271, 635, 27228, 911, 578, 628, 279, 6909, 16703, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 654, 39, 3462, 12, 2867, 1147, 1887, 16, 2254, 5034, 1147, 6275, 13, 3903, 1338, 5541, 288, 203, 3639, 467, 654, 39, 3462, 12, 2316, 1887, 2934, 4626, 5912, 12, 8443, 9334, 1147, 6275, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint 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 (uint); /** * @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, uint 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, uint 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, uint 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, uint value); } // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "TimeLoans::SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapOracleRouter { function quote(address tokenIn, address tokenOut, uint amountIn) external view returns (uint amountOut); } contract TimeLoanPair { using SafeMath for uint; /// @notice EIP-20 token name for this token string public constant name = "Time Loan Pair LP"; /// @notice EIP-20 token symbol for this token string public symbol; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Uniswap V2 Router used for all swaps and liquidity management IUniswapV2Router02 public constant UNI = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /// @notice Uniswap Oracle Router used for all 24 hour TWAP price metrics IUniswapOracleRouter public constant ORACLE = IUniswapOracleRouter(0x0b5A6b318c39b60e7D8462F888e7fbA89f75D02F); /// @notice The underlying Uniswap Pair used for loan liquidity address public pair; /// @notice The token0 of the Uniswap Pair address public token0; /// @notice The token1 of the Uniswap Pair address public token1; /// @notice Deposited event for creditor/LP event Deposited(address indexed creditor, address indexed collateral, uint shares, uint credit); /// @notice Withdawn event for creditor/LP event Withdrew(address indexed creditor, address indexed collateral, uint shares, uint credit); /// @notice The borrow event for any borrower event Borrowed(uint id, address indexed borrower, address indexed collateral, address indexed borrowed, uint creditIn, uint amountOut, uint created, uint expire); /// @notice The close loan event when processing expired loans event Repaid(uint id, address indexed borrower, address indexed collateral, address indexed borrowed, uint creditIn, uint amountOut, uint created, uint expire); /// @notice The close loan event when processing expired loans event Closed(uint id, address indexed borrower, address indexed collateral, address indexed borrowed, uint creditIn, uint amountOut, uint created, uint expire); /// @notice 0.6% initiation fee for all loans uint public constant FEE = 600; // 0.6% loan initiation fee /// @notice 105% liquidity buffer on withdrawing liquidity uint public constant BUFFER = 105000; // 105% liquidity buffer /// @notice 80% loan to value ratio uint public constant LTV = 80000; // 80% loan to value ratio /// @notice base for all % based calculations uint public constant BASE = 100000; /// @notice the delay for a position to be closed uint public constant DELAY = 6600; // ~24 hours till position is closed struct position { address owner; address collateral; address borrowed; uint creditIn; uint amountOut; uint liquidityInUse; uint created; uint expire; bool open; } /// @notice array of all loan positions position[] public positions; /// @notice the tip index of the positions array uint public nextIndex; /// @notice the last index processed by the contract uint public processedIndex; /// @notice mapping of loans assigned to users mapping(address => uint[]) public loans; /// @notice constructor takes a uniswap pair as an argument to set its 2 borrowable assets constructor(IUniswapV2Pair _pair) public { symbol = string(abi.encodePacked(IUniswapV2Pair(_pair.token0()).symbol(), "-", IUniswapV2Pair(_pair.token1()).symbol())); pair = address(_pair); token0 = _pair.token0(); token1 = _pair.token1(); } /// @notice total liquidity deposited uint public liquidityDeposits; /// @notice total liquidity withdrawn uint public liquidityWithdrawals; /// @notice total liquidity added via addLiquidity uint public liquidityAdded; /// @notice total liquidity removed via removeLiquidity uint public liquidityRemoved; /// @notice total liquidity currently in use by pending loans uint public liquidityInUse; /// @notice total liquidity freed up from closed loans uint public liquidityFreed; /** * @notice the current net liquidity positions * @return the net liquidity sum */ function liquidityBalance() public view returns (uint) { return liquidityDeposits .sub(liquidityWithdrawals) .add(liquidityAdded) .sub(liquidityRemoved) .add(liquidityFreed) .sub(liquidityInUse); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { // burn the amount totalSupply = totalSupply.sub(amount, "TimeLoans::_burn: underflow"); // transfer the amount to the recipient balances[dst] = balances[dst].sub(amount, "TimeLoans::_burn: underflow"); emit Transfer(dst, address(0), amount); } /** * @notice withdraw all liquidity from msg.sender shares * @return success/failure */ function withdrawAll() external returns (bool) { return withdraw(balances[msg.sender]); } /** * @notice withdraw `_shares` amount of liquidity for user * @param _shares the amount of shares to burn for liquidity * @return success/failure */ function withdraw(uint _shares) public returns (bool) { uint r = liquidityBalance().mul(_shares).div(totalSupply); _burn(msg.sender, _shares); require(IERC20(pair).balanceOf(address(this)) > r, "TimeLoans::withdraw: insufficient liquidity to withdraw, try depositLiquidity()"); IERC20(pair).transfer(msg.sender, r); liquidityWithdrawals = liquidityWithdrawals.add(r); emit Withdrew(msg.sender, pair, _shares, r); return true; } /** * @notice deposit all liquidity from msg.sender * @return success/failure */ function depositAll() external returns (bool) { return deposit(IERC20(pair).balanceOf(msg.sender)); } /** * @notice deposit `amount` amount of liquidity for user * @param amount the amount of liquidity to add for shares * @return success/failure */ function deposit(uint amount) public returns (bool) { IERC20(pair).transferFrom(msg.sender, address(this), amount); uint _shares = 0; if (liquidityBalance() == 0) { _shares = amount; } else { _shares = amount.mul(totalSupply).div(liquidityBalance()); } _mint(msg.sender, _shares); liquidityDeposits = liquidityDeposits.add(amount); emit Deposited(msg.sender, pair, _shares, amount); return true; } /** * @notice batch close any pending open loans that have expired * @param size the maximum size of batch to execute * @return the last index processed */ function closeInBatches(uint size) external returns (uint) { uint i = processedIndex; for (; i < size; i++) { close(i); } processedIndex = i; return processedIndex; } /** * @notice iterate through all open loans and close * @return the last index processed */ function closeAllOpen() external returns (uint) { uint i = processedIndex; for (; i < nextIndex; i++) { close(i); } processedIndex = i; return processedIndex; } /** * @notice close a specific loan based on id * @param id the `id` of the given loan to close * @return success/failure */ function close(uint id) public returns (bool) { position storage _pos = positions[id]; if (_pos.owner == address(0x0)) { return false; } if (!_pos.open) { return false; } if (_pos.expire > block.number) { return false; } _pos.open = false; liquidityInUse = liquidityInUse.sub(_pos.liquidityInUse, "TimeLoans::close: liquidityInUse overflow"); liquidityFreed = liquidityFreed.add(_pos.liquidityInUse); emit Closed(id, _pos.owner, _pos.collateral, _pos.borrowed, _pos.creditIn, _pos.amountOut, _pos.created, _pos.expire); return true; } /** * @notice returns the available liquidity (including LP tokens) for a given asset * @param asset the asset to calculate liquidity for * @return the amount of liquidity available */ function liquidityOf(address asset) public view returns (uint) { return IERC20(asset).balanceOf(address(this)). add(IERC20(asset).balanceOf(pair) .mul(IERC20(pair).balanceOf(address(this))) .div(IERC20(pair).totalSupply())); } /** * @notice calculates the amount of liquidity to burn to get the amount of asset * @param amount the amount of asset required as output * @return the amount of liquidity to burn */ function calculateLiquidityToBurn(address asset, uint amount) public view returns (uint) { return IERC20(pair).totalSupply() .mul(amount) .div(IERC20(asset).balanceOf(pair)); } /** * @notice withdraw liquidity to get the amount of tokens required to borrow * @param asset the asset output required * @param amount the amount of asset required as output */ function _withdrawLiquidity(address asset, uint amount) internal returns (uint withdrew) { withdrew = calculateLiquidityToBurn(asset, amount); withdrew = withdrew.mul(BUFFER).div(BASE); uint _amountAMin = 0; uint _amountBMin = 0; if (asset == token0) { _amountAMin = amount; } else if (asset == token1) { _amountBMin = amount; } IERC20(pair).approve(address(UNI), withdrew); UNI.removeLiquidity(token0, token1, withdrew, _amountAMin, _amountBMin, address(this), now.add(1800)); liquidityRemoved = liquidityRemoved.add(withdrew); } /** * @notice Provides a quote of how much output can be expected given the inputs * @param collateral the asset being used as collateral * @param borrow the asset being borrowed * @param amount the amount of collateral being provided * @return minOut the minimum amount of liquidity to borrow */ function quote(address collateral, address borrow, uint amount) external view returns (uint minOut) { uint _received = (amount.sub(amount.mul(FEE).div(BASE))).mul(LTV).div(BASE); return ORACLE.quote(collateral, borrow, _received); } /** * @notice deposit available liquidity in the system into the Uniswap Pair, manual for now, require keepers in later iterations */ function depositLiquidity() external { require(msg.sender == tx.origin, "TimeLoans::depositLiquidity: not an EOA keeper"); IERC20(token0).approve(address(UNI), IERC20(token0).balanceOf(address(this))); IERC20(token1).approve(address(UNI), IERC20(token1).balanceOf(address(this))); (,,uint _added) = UNI.addLiquidity(token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now.add(1800)); liquidityAdded = liquidityAdded.add(_added); } /** * @notice Returns greater than `outMin` amount of `borrow` based on `amount` of `collateral supplied * @param collateral the asset being used as collateral * @param borrow the asset being borrowed * @param amount the amount of collateral being provided * @param outMin the minimum amount of liquidity to borrow */ function loan(address collateral, address borrow, uint amount, uint outMin) external returns (uint) { uint _before = IERC20(collateral).balanceOf(address(this)); IERC20(collateral).transferFrom(msg.sender, address(this), amount); uint _after = IERC20(collateral).balanceOf(address(this)); uint _received = _after.sub(_before); uint _fee = _received.mul(FEE).div(BASE); _received = _received.sub(_fee); uint _ltv = _received.mul(LTV).div(BASE); uint _amountOut = ORACLE.quote(collateral, borrow, _ltv); require(_amountOut >= outMin, "TimeLoans::loan: slippage"); require(liquidityOf(borrow) > _amountOut, "TimeLoans::loan: insufficient liquidity"); uint _available = IERC20(borrow).balanceOf(address(this)); uint _withdrew = 0; if (_available < _amountOut) { _withdrew = _withdrawLiquidity(borrow, _amountOut.sub(_available)); liquidityInUse = liquidityInUse.add(_withdrew); } positions.push(position(msg.sender, collateral, borrow, _received, _amountOut, _withdrew, block.number, block.number.add(DELAY), true)); loans[msg.sender].push(nextIndex); IERC20(borrow).transfer(msg.sender, _amountOut); emit Borrowed(nextIndex, msg.sender, collateral, borrow, _received, _amountOut, block.number, block.number.add(DELAY)); return nextIndex++; } /** * @notice Repay a pending loan with `id` anyone can repay, no owner check * @param id the id of the loan to close * @return true/false if loan was successfully closed */ function repay(uint id) external returns (bool) { position storage _pos = positions[id]; require(_pos.open, "TimeLoans::repay: position is already closed"); require(_pos.expire < block.number, "TimeLoans::repay: position already expired"); IERC20(_pos.borrowed).transferFrom(msg.sender, address(this), _pos.amountOut); uint _available = IERC20(_pos.collateral).balanceOf(address(this)); if (_available < _pos.creditIn) { _withdrawLiquidity(_pos.collateral, _pos.creditIn.sub(_available)); } IERC20(_pos.collateral).transfer(msg.sender, _pos.creditIn); _pos.open = false; positions[id] = _pos; emit Repaid(id, _pos.owner, _pos.collateral, _pos.borrowed, _pos.creditIn, _pos.amountOut, _pos.created, _pos.expire); return true; } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TimeLoans::permit: invalid signature"); require(signatory == owner, "TimeLoans::permit: unauthorized"); require(now <= deadline, "TimeLoans::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "TimeLoans::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "TimeLoans::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "TimeLoans::_transferTokens: cannot transfer to the zero address"); balances[src] = balances[src].sub(amount, "TimeLoans::_transferTokens: transfer amount exceeds balance"); balances[dst] = balances[dst].add(amount, "TimeLoans::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); } function getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } contract TimeLoanPairFactory { mapping(address => address) public pairs; address[] public deployed; function deploy(IUniswapV2Pair _pair) external returns (address) { require(pairs[address(_pair)] == address(0x0), "TimeLoanPairFactory::deploy: pair already created"); pairs[address(_pair)] = address(new TimeLoanPair(_pair)); deployed.push(address(_pair)); return pairs[address(_pair)]; } }
* @notice deposit `amount` amount of liquidity for user @param amount the amount of liquidity to add for shares @return success/failure/
function deposit(uint amount) public returns (bool) { IERC20(pair).transferFrom(msg.sender, address(this), amount); uint _shares = 0; if (liquidityBalance() == 0) { _shares = amount; _shares = amount.mul(totalSupply).div(liquidityBalance()); } _mint(msg.sender, _shares); liquidityDeposits = liquidityDeposits.add(amount); emit Deposited(msg.sender, pair, _shares, amount); return true; }
466,153
[ 1, 323, 1724, 1375, 8949, 68, 3844, 434, 4501, 372, 24237, 364, 729, 225, 3844, 326, 3844, 434, 4501, 372, 24237, 358, 527, 364, 24123, 327, 2216, 19, 12251, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 467, 654, 39, 3462, 12, 6017, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 2254, 389, 30720, 273, 374, 31, 203, 3639, 309, 261, 549, 372, 24237, 13937, 1435, 422, 374, 13, 288, 203, 5411, 389, 30720, 273, 3844, 31, 203, 5411, 389, 30720, 273, 3844, 18, 16411, 12, 4963, 3088, 1283, 2934, 2892, 12, 549, 372, 24237, 13937, 10663, 203, 3639, 289, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 30720, 1769, 203, 3639, 4501, 372, 24237, 758, 917, 1282, 273, 4501, 372, 24237, 758, 917, 1282, 18, 1289, 12, 8949, 1769, 203, 3639, 3626, 4019, 538, 16261, 12, 3576, 18, 15330, 16, 3082, 16, 389, 30720, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x8Ce305f5469A1df3Fec330d53EcF72657B97A95c/sources/lib/base58-solidity/contracts/Base58.sol
* @notice slice is used to slice the given byte, returns the bytes in the range of [start_, end_) @param data_ raw data, passed in as bytes. @param start_ start index. @param end_ end index. @return slice data/
function slice( bytes memory data_, uint256 start_, uint256 end_ ) public pure returns (bytes memory) { unchecked { bytes memory ret = new bytes(end_ - start_); for (uint256 i = 0; i < end_ - start_; i++) { ret[i] = data_[i + start_]; } return ret; } }
3,826,866
[ 1, 6665, 353, 1399, 358, 2788, 326, 864, 1160, 16, 1135, 326, 1731, 316, 326, 1048, 434, 306, 1937, 67, 16, 679, 67, 13, 225, 501, 67, 1831, 501, 16, 2275, 316, 487, 1731, 18, 225, 787, 67, 787, 770, 18, 225, 679, 67, 679, 770, 18, 327, 2788, 501, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2788, 12, 203, 3639, 1731, 3778, 501, 67, 16, 203, 3639, 2254, 5034, 787, 67, 16, 203, 3639, 2254, 5034, 679, 67, 203, 565, 262, 1071, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 22893, 288, 203, 5411, 1731, 3778, 325, 273, 394, 1731, 12, 409, 67, 300, 787, 67, 1769, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 679, 67, 300, 787, 67, 31, 277, 27245, 288, 203, 7734, 325, 63, 77, 65, 273, 501, 67, 63, 77, 397, 787, 67, 15533, 203, 5411, 289, 203, 5411, 327, 325, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; import "./IRegistry.sol"; contract Registry is IRegistry, ERC165 { struct OrganizationRegistration { bytes32 organizationName; address owner; // member indexing note: // case (members[someAddress]) of // 0 -> not a member of this org // n -> member of this org, and memberKeys[n-1] == someAddress address[] memberKeys; mapping(address => uint) members; bytes32[] serviceKeys; bytes32[] typeRepoKeys; mapping(bytes32 => ServiceRegistration) servicesByName; mapping(bytes32 => TypeRepositoryRegistration) typeReposByName; uint globalOrgIndex; } struct ServiceRegistration { bytes32 serviceName; bytes32 servicePath; address agentAddress; bytes metadataIPFSHash; // IPFSHash of service metadata (in the case of MPE payment system) bytes32[] tags; mapping(bytes32 => Tag) tagsByName; uint orgServiceIndex; } struct TypeRepositoryRegistration { bytes32 repositoryName; bytes32 repositoryPath; bytes repositoryURI; bytes32[] tags; mapping(bytes32 => Tag) tagsByName; uint orgTypeRepoIndex; } struct Tag { bytes32 tagName; uint itemTagIndex; uint globalTagIndex; } struct ServiceOrTypeRepositoryList { bool valid; bytes32[] orgNames; bytes32[] itemNames; } bytes32[] orgKeys; mapping(bytes32 => OrganizationRegistration) orgsByName; bytes32[] serviceTags; bytes32[] typeRepoTags; mapping(bytes32 => ServiceOrTypeRepositoryList) servicesByTag; mapping(bytes32 => ServiceOrTypeRepositoryList) typeReposByTag; /** * @dev Guard function that forces a revert if the tx sender is unauthorized. * Always authorizes org owner. Can also authorize org members. * * @param membersAllowed if true, revert when sender is non-owner and non-member, else revert when sender is non-owner */ function requireAuthorization(bytes32 orgName, bool membersAllowed) internal view { require(msg.sender == orgsByName[orgName].owner || (membersAllowed && orgsByName[orgName].members[msg.sender] > 0) , "unauthorized invocation"); } /** * @dev Guard function that forces a revert if the referenced org does not meet an existence criteria. * * @param exists if true, revert when org does not exist, else revert when org exists */ function requireOrgExistenceConstraint(bytes32 orgName, bool exists) internal view { if (exists) { require(orgsByName[orgName].organizationName != bytes32(0x0), "org does not exist"); } else { require(orgsByName[orgName].organizationName == bytes32(0x0), "org already exists"); } } /** * @dev Guard function that forces a revert if the referenced service does not meet an existence criteria. * * @param exists if true, revert when service does not exist, else revert when service exists */ function requireServiceExistenceConstraint(bytes32 orgName, bytes32 serviceName, bool exists) internal view { if (exists) { require(orgsByName[orgName].servicesByName[serviceName].serviceName != bytes32(0x0), "service does not exist"); } else { require(orgsByName[orgName].servicesByName[serviceName].serviceName == bytes32(0x0), "service already exists"); } } /** * @dev Guard function that forces a revert if the referenced type repository does not meet an existence criteria. * * @param exists if true, revert when type repo does not exist, else revert when type repo exists */ function requireTypeRepositoryExistenceConstraint(bytes32 orgName, bytes32 repositoryName, bool exists) internal view { if (exists) { require(orgsByName[orgName].typeReposByName[repositoryName].repositoryName != bytes32(0x0), "type repo does not exist"); } else { require(orgsByName[orgName].typeReposByName[repositoryName].repositoryName == bytes32(0x0), "type repo already exists"); } } // ___ _ _ _ __ __ _ // / _ \ _ __ __ _ __ _ _ __ (_)______ _| |_(_) ___ _ __ | \/ | __ _ _ __ ___ | |_ // | | | | '__/ _` |/ _` | '_ \| |_ / _` | __| |/ _ \| '_ \ | |\/| |/ _` | '_ ` _ \| __| // | |_| | | | (_| | (_| | | | | |/ / (_| | |_| | (_) | | | | | | | | (_| | | | | | | |_ // \___/|_| \__, |\__,_|_| |_|_/___\__,_|\__|_|\___/|_| |_| |_| |_|\__, |_| |_| |_|\__| // |___/ |___/ function createOrganization(bytes32 orgName, address[] members) external { requireOrgExistenceConstraint(orgName, false); OrganizationRegistration memory organization; orgsByName[orgName] = organization; orgsByName[orgName].organizationName = orgName; orgsByName[orgName].owner = msg.sender; orgsByName[orgName].globalOrgIndex = orgKeys.length; orgKeys.push(orgName); addOrganizationMembersInternal(orgName, members); emit OrganizationCreated(orgName, orgName); } function changeOrganizationOwner(bytes32 orgName, address newOwner) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, false); orgsByName[orgName].owner = newOwner; emit OrganizationModified(orgName, orgName); } function addOrganizationMembers(bytes32 orgName, address[] newMembers) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); addOrganizationMembersInternal(orgName, newMembers); emit OrganizationModified(orgName, orgName); } function addOrganizationMembersInternal(bytes32 orgName, address[] newMembers) internal { for (uint i = 0; i < newMembers.length; i++) { if (orgsByName[orgName].members[newMembers[i]] == 0) { orgsByName[orgName].memberKeys.push(newMembers[i]); orgsByName[orgName].members[newMembers[i]] = orgsByName[orgName].memberKeys.length; } } } function removeOrganizationMembers(bytes32 orgName, address[] existingMembers) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); for (uint i = 0; i < existingMembers.length; i++) { removeOrganizationMemberInternal(orgName, existingMembers[i]); } emit OrganizationModified(orgName, orgName); } function removeOrganizationMemberInternal(bytes32 orgName, address existingMember) internal { // see "member indexing note" if (orgsByName[orgName].members[existingMember] != 0) { uint storedIndexToRemove = orgsByName[orgName].members[existingMember]; address memberToMove = orgsByName[orgName].memberKeys[orgsByName[orgName].memberKeys.length - 1]; // no-op if we are deleting the last entry if (orgsByName[orgName].memberKeys[storedIndexToRemove - 1] != memberToMove) { // swap lut entries orgsByName[orgName].memberKeys[storedIndexToRemove - 1] = memberToMove; orgsByName[orgName].members[memberToMove] = storedIndexToRemove; } // shorten keys array orgsByName[orgName].memberKeys.length--; // delete the mapping entry delete orgsByName[orgName].members[existingMember]; } } function deleteOrganization(bytes32 orgName) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, false); for (uint serviceIndex = orgsByName[orgName].serviceKeys.length; serviceIndex > 0; serviceIndex--) { deleteServiceRegistrationInternal(orgName, orgsByName[orgName].serviceKeys[serviceIndex-1]); } for (uint repoIndex = orgsByName[orgName].typeRepoKeys.length; repoIndex > 0; repoIndex--) { deleteTypeRepositoryRegistrationInternal(orgName, orgsByName[orgName].typeRepoKeys[repoIndex-1]); } for (uint memberIndex = orgsByName[orgName].memberKeys.length; memberIndex > 0; memberIndex--) { removeOrganizationMemberInternal(orgName, orgsByName[orgName].memberKeys[memberIndex-1]); } // swap lut entries uint indexToUpdate = orgsByName[orgName].globalOrgIndex; bytes32 orgToUpdate = orgKeys[orgKeys.length-1]; if (orgKeys[indexToUpdate] != orgToUpdate) { orgKeys[indexToUpdate] = orgToUpdate; orgsByName[orgToUpdate].globalOrgIndex = indexToUpdate; } // shorten keys array orgKeys.length--; // delete contents of organization registration delete orgsByName[orgName]; emit OrganizationDeleted(orgName, orgName); } // ____ _ __ __ _ // / ___| ___ _ ____ ___) ___ ___ | \/ | __ _ _ __ ___ | |_ // \___ \ / _ \ '__\ \ / / |/ __/ _ \ | |\/| |/ _` | '_ ` _ \| __| // ___) | __/ | \ V /| | (__ __/ | | | | (_| | | | | | | |_ // |____/ \___|_| \_/ |_|\___\___| |_| |_|\__, |_| |_| |_|\__| // |___/ function createServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes32 servicePath, address agentAddress, bytes32[] tags) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireServiceExistenceConstraint(orgName, serviceName, false); ServiceRegistration memory service; orgsByName[orgName].servicesByName[serviceName] = service; orgsByName[orgName].servicesByName[serviceName].serviceName = serviceName; orgsByName[orgName].servicesByName[serviceName].servicePath = servicePath; orgsByName[orgName].servicesByName[serviceName].agentAddress = agentAddress; orgsByName[orgName].servicesByName[serviceName].orgServiceIndex = orgsByName[orgName].serviceKeys.length; orgsByName[orgName].serviceKeys.push(serviceName); for (uint i = 0; i < tags.length; i++) { addTagToServiceRegistration(orgName, serviceName, tags[i]); } emit ServiceCreated(orgName, serviceName, orgName, serviceName); } function updateServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes32 servicePath, address agentAddress) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireServiceExistenceConstraint(orgName, serviceName, true); // update the servicePath and agentAddress orgsByName[orgName].servicesByName[serviceName].servicePath = servicePath; orgsByName[orgName].servicesByName[serviceName].agentAddress = agentAddress; emit ServiceModified(orgName, serviceName, orgName, serviceName); } function addTagsToServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes32[] tags) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireServiceExistenceConstraint(orgName, serviceName, true); for (uint i = 0; i < tags.length; i++) { addTagToServiceRegistration(orgName, serviceName, tags[i]); } emit ServiceModified(orgName, serviceName, orgName, serviceName); } function addTagToServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes32 tagName) internal { // no-op if tag already exists if (orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].tagName == bytes32(0x0)) { // add the tag to the service level tag index Tag memory tagObj; orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName] = tagObj; orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].tagName = tagName; orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].itemTagIndex = orgsByName[orgName].servicesByName[serviceName].tags.length; orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].globalTagIndex = servicesByTag[tagName].orgNames.length; orgsByName[orgName].servicesByName[serviceName].tags.push(tagName); // add the service to the global tag index creating a list object for this tag if it does not already exist if (!servicesByTag[tagName].valid) { ServiceOrTypeRepositoryList memory listObj; listObj.valid = true; servicesByTag[tagName] = listObj; serviceTags.push(tagName); } servicesByTag[tagName].orgNames.push(orgName); servicesByTag[tagName].itemNames.push(serviceName); } } function setMetadataIPFSHashInServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes metadataIPFSHash) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireServiceExistenceConstraint(orgName, serviceName, true); orgsByName[orgName].servicesByName[serviceName].metadataIPFSHash = metadataIPFSHash; } function removeTagsFromServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes32[] tags) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireServiceExistenceConstraint(orgName, serviceName, true); for (uint i = 0; i < tags.length; i++) { removeTagFromServiceRegistration(orgName, serviceName, tags[i]); } emit ServiceModified(orgName, serviceName, orgName, serviceName); } function removeTagFromServiceRegistration(bytes32 orgName, bytes32 serviceName, bytes32 tagName) internal { // no-op if tag does not exist if (orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].tagName != bytes32(0x0)) { // swap service registration lut entries uint tagIndexToReplace = orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].itemTagIndex; bytes32 tagNameToMove = orgsByName[orgName].servicesByName[serviceName].tags[orgsByName[orgName].servicesByName[serviceName].tags.length-1]; // no-op if we are deleting the last item if (tagIndexToReplace != orgsByName[orgName].servicesByName[serviceName].tags.length-1) { orgsByName[orgName].servicesByName[serviceName].tags[tagIndexToReplace] = tagNameToMove; orgsByName[orgName].servicesByName[serviceName].tagsByName[tagNameToMove].itemTagIndex = tagIndexToReplace; } orgsByName[orgName].servicesByName[serviceName].tags.length--; // swap global tag index lut entries tagIndexToReplace = orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName].globalTagIndex; uint tagIndexToMove = servicesByTag[tagName].orgNames.length-1; // no-op if we are deleting the last item if (tagIndexToMove != tagIndexToReplace) { bytes32 orgNameToMove = servicesByTag[tagName].orgNames[tagIndexToMove]; bytes32 itemNameToMove = servicesByTag[tagName].itemNames[tagIndexToMove]; servicesByTag[tagName].orgNames[tagIndexToReplace] = orgNameToMove; servicesByTag[tagName].itemNames[tagIndexToReplace] = itemNameToMove; orgsByName[orgNameToMove].servicesByName[itemNameToMove].tagsByName[tagName].globalTagIndex = tagIndexToReplace; } servicesByTag[tagName].orgNames.length--; servicesByTag[tagName].itemNames.length--; // delete contents of the tag entry delete orgsByName[orgName].servicesByName[serviceName].tagsByName[tagName]; } } function deleteServiceRegistration(bytes32 orgName, bytes32 serviceName) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireServiceExistenceConstraint(orgName, serviceName, true); deleteServiceRegistrationInternal(orgName, serviceName); emit ServiceDeleted(orgName, serviceName, orgName, serviceName); } function deleteServiceRegistrationInternal(bytes32 orgName, bytes32 serviceName) internal { // delete the tags associated with the service for (uint i = orgsByName[orgName].servicesByName[serviceName].tags.length; i > 0; i--) { removeTagFromServiceRegistration(orgName, serviceName, orgsByName[orgName].servicesByName[serviceName].tags[i-1]); } // swap lut entries uint indexToUpdate = orgsByName[orgName].servicesByName[serviceName].orgServiceIndex; bytes32 serviceToUpdate = orgsByName[orgName].serviceKeys[orgsByName[orgName].serviceKeys.length-1]; if (orgsByName[orgName].serviceKeys[indexToUpdate] != serviceToUpdate) { orgsByName[orgName].serviceKeys[indexToUpdate] = serviceToUpdate; orgsByName[orgName].servicesByName[serviceToUpdate].orgServiceIndex = indexToUpdate; } orgsByName[orgName].serviceKeys.length--; // delete contents of service registration delete orgsByName[orgName].servicesByName[serviceName]; } // _____ ____ __ __ _ // |_ _| _ _ __ ___ | _ \ ___ _ __ ___ | \/ | __ _ _ __ ___ | |_ // | || | | | '_ \ / _ \ | |_) / _ \ '_ \ / _ \ | |\/| |/ _` | '_ ` _ \| __| // | || |_| | |_) | __/ | _ < __/ |_) | (_) | | | | | (_| | | | | | | |_ // |_| \__, | .__/ \___| |_| \_\___| .__/ \___/ |_| |_|\__, |_| |_| |_|\__| // |___/|_| |_| |___/ function createTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName, bytes32 repositoryPath, bytes repositoryURI, bytes32[] tags) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireTypeRepositoryExistenceConstraint(orgName, repositoryName, false); TypeRepositoryRegistration memory typeRepo; orgsByName[orgName].typeReposByName[repositoryName] = typeRepo; orgsByName[orgName].typeReposByName[repositoryName].repositoryName = repositoryName; orgsByName[orgName].typeReposByName[repositoryName].repositoryPath = repositoryPath; orgsByName[orgName].typeReposByName[repositoryName].repositoryURI = repositoryURI; orgsByName[orgName].typeReposByName[repositoryName].orgTypeRepoIndex = orgsByName[orgName].typeRepoKeys.length; orgsByName[orgName].typeRepoKeys.push(repositoryName); for (uint i = 0; i < tags.length; i++) { addTagToTypeRepositoryRegistration(orgName, repositoryName, tags[i]); } emit TypeRepositoryCreated(orgName, repositoryName, orgName, repositoryName); } function updateTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName, bytes32 repositoryPath, bytes repositoryURI) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireTypeRepositoryExistenceConstraint(orgName, repositoryName, true); orgsByName[orgName].typeReposByName[repositoryName].repositoryPath = repositoryPath; orgsByName[orgName].typeReposByName[repositoryName].repositoryURI = repositoryURI; emit TypeRepositoryModified(orgName, repositoryName, orgName, repositoryName); } function addTagsToTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName, bytes32[] tags) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireTypeRepositoryExistenceConstraint(orgName, repositoryName, true); for (uint i = 0; i < tags.length; i++) { addTagToTypeRepositoryRegistration(orgName, repositoryName, tags[i]); } emit TypeRepositoryModified(orgName, repositoryName, orgName, repositoryName); } function addTagToTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName, bytes32 tagName) internal { // no-op if tag already exists if (orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].tagName == bytes32(0x0)) { // add the tag to the type repository level tag index Tag memory tagObj; orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName] = tagObj; orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].tagName = tagName; orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].itemTagIndex = orgsByName[orgName].typeReposByName[repositoryName].tags.length; orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].globalTagIndex = typeReposByTag[tagName].orgNames.length; orgsByName[orgName].typeReposByName[repositoryName].tags.push(tagName); // add the type repository to the global tag index creating a list object for this tag if it does not already exist if (!typeReposByTag[tagName].valid) { ServiceOrTypeRepositoryList memory listObj; listObj.valid = true; typeReposByTag[tagName] = listObj; typeRepoTags.push(tagName); } typeReposByTag[tagName].orgNames.push(orgName); typeReposByTag[tagName].itemNames.push(repositoryName); } } function removeTagsFromTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName, bytes32[] tags) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireTypeRepositoryExistenceConstraint(orgName, repositoryName, true); for (uint i = 0; i < tags.length; i++) { removeTagFromTypeRepositoryRegistration(orgName, repositoryName, tags[i]); } emit TypeRepositoryModified(orgName, repositoryName, orgName, repositoryName); } function removeTagFromTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName, bytes32 tagName) internal { // no-op if tag doesnt exist if (orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].tagName != bytes32(0x0)) { // swap type repository registration lut entries uint tagIndexToReplace = orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].itemTagIndex; bytes32 tagNameToMove = orgsByName[orgName].typeReposByName[repositoryName].tags[orgsByName[orgName].typeReposByName[repositoryName].tags.length-1]; // no-op if we are deleting the last item if (tagIndexToReplace != orgsByName[orgName].typeReposByName[repositoryName].tags.length-1) { orgsByName[orgName].typeReposByName[repositoryName].tags[tagIndexToReplace] = tagNameToMove; orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagNameToMove].itemTagIndex = tagIndexToReplace; } orgsByName[orgName].typeReposByName[repositoryName].tags.length--; // swap global tag index lut entries tagIndexToReplace = orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName].globalTagIndex; uint tagIndexToMove = typeReposByTag[tagName].orgNames.length-1; // no-op if we are deleting the last item if (tagIndexToMove != tagIndexToReplace) { bytes32 orgNameToMove = typeReposByTag[tagName].orgNames[tagIndexToMove]; bytes32 repoNameToMove = typeReposByTag[tagName].itemNames[tagIndexToMove]; typeReposByTag[tagName].orgNames[tagIndexToReplace] = orgNameToMove; typeReposByTag[tagName].itemNames[tagIndexToReplace] = repoNameToMove; orgsByName[orgNameToMove].typeReposByName[repoNameToMove].tagsByName[tagName].globalTagIndex = tagIndexToReplace; } typeReposByTag[tagName].orgNames.length--; typeReposByTag[tagName].itemNames.length--; // delete contents of the tag entry delete orgsByName[orgName].typeReposByName[repositoryName].tagsByName[tagName]; } } function deleteTypeRepositoryRegistration(bytes32 orgName, bytes32 repositoryName) external { requireOrgExistenceConstraint(orgName, true); requireAuthorization(orgName, true); requireTypeRepositoryExistenceConstraint(orgName, repositoryName, true); deleteTypeRepositoryRegistrationInternal(orgName, repositoryName); emit TypeRepositoryDeleted(orgName, repositoryName, orgName, repositoryName); } function deleteTypeRepositoryRegistrationInternal(bytes32 orgName, bytes32 repositoryName) internal { // delete the tags associated with the type repo for (uint i = orgsByName[orgName].typeReposByName[repositoryName].tags.length; i > 0; i--) { removeTagFromTypeRepositoryRegistration(orgName, repositoryName, orgsByName[orgName].typeReposByName[repositoryName].tags[i-1]); } // swap lut entries uint indexToUpdate = orgsByName[orgName].typeReposByName[repositoryName].orgTypeRepoIndex; bytes32 typeRepoToUpdate = orgsByName[orgName].typeRepoKeys[orgsByName[orgName].typeRepoKeys.length-1]; // no-op if we are deleting the last item if (orgsByName[orgName].typeRepoKeys[indexToUpdate] != typeRepoToUpdate) { orgsByName[orgName].typeRepoKeys[indexToUpdate] = typeRepoToUpdate; orgsByName[orgName].typeReposByName[typeRepoToUpdate].orgTypeRepoIndex = indexToUpdate; } orgsByName[orgName].typeRepoKeys.length--; // delete contents of repo registration delete orgsByName[orgName].typeReposByName[repositoryName]; } // ____ _ _ // / ___| ___| |_| |_ ___ _ __ ___ // | | _ / _ \ __| __/ _ \ '__/ __| // | |_| | __/ |_| |_ __/ | \__ \ // \____|\___|\__|\__\___|_| |___/ // function listOrganizations() external view returns (bytes32[] orgNames) { return orgKeys; } function getOrganizationByName(bytes32 orgName) external view returns(bool found, bytes32 name, address owner, address[] members, bytes32[] serviceNames, bytes32[] repositoryNames) { // check to see if this organization exists if(orgsByName[orgName].organizationName == bytes32(0x0)) { found = false; return; } found = true; name = orgsByName[orgName].organizationName; owner = orgsByName[orgName].owner; members = orgsByName[orgName].memberKeys; serviceNames = orgsByName[orgName].serviceKeys; repositoryNames = orgsByName[orgName].typeRepoKeys; } function listServicesForOrganization(bytes32 orgName) external view returns (bool found, bytes32[] serviceNames) { // check to see if this organization exists if(orgsByName[orgName].organizationName == bytes32(0x0)) { found = false; return; } found = true; serviceNames = orgsByName[orgName].serviceKeys; } function getServiceRegistrationByName(bytes32 orgName, bytes32 serviceName) external view returns (bool found, bytes32 name, bytes32 path, address agentAddress, bytes32[] tags) { // check to see if this organization exists if(orgsByName[orgName].organizationName == bytes32(0x0)) { found = false; return; } // check to see if this repo exists if(orgsByName[orgName].servicesByName[serviceName].serviceName == bytes32(0x0)) { found = false; return; } found = true; name = orgsByName[orgName].servicesByName[serviceName].serviceName; path = orgsByName[orgName].servicesByName[serviceName].servicePath; agentAddress = orgsByName[orgName].servicesByName[serviceName].agentAddress; tags = orgsByName[orgName].servicesByName[serviceName].tags; } function getMetadataIPFSHash(bytes32 orgName, bytes32 serviceName) external view returns (bool found, bytes metadataIPFSHash) { // check to see if this organization exists if(orgsByName[orgName].organizationName == bytes32(0x0)) { found = false; return; } // check to see if this repo exists if(orgsByName[orgName].servicesByName[serviceName].serviceName == bytes32(0x0)) { found = false; return; } found = true; metadataIPFSHash = orgsByName[orgName].servicesByName[serviceName].metadataIPFSHash; } function listTypeRepositoriesForOrganization(bytes32 orgName) external view returns (bool found, bytes32[] repositoryNames) { // check to see if this organization exists if(orgsByName[orgName].organizationName == bytes32(0x0)) { found = false; return; } found = true; repositoryNames = orgsByName[orgName].typeRepoKeys; } function getTypeRepositoryByName(bytes32 orgName, bytes32 repositoryName) external view returns (bool found, bytes32 name, bytes32 path, bytes uri, bytes32[] tags) { // check to see if this organization exists if(orgsByName[orgName].organizationName == bytes32(0x0)) { found = false; return; } // check to see if this repo exists if(orgsByName[orgName].typeReposByName[repositoryName].repositoryName == bytes32(0x0)) { found = false; return; } found = true; name = repositoryName; path = orgsByName[orgName].typeReposByName[repositoryName].repositoryPath; uri = orgsByName[orgName].typeReposByName[repositoryName].repositoryURI; tags = orgsByName[orgName].typeReposByName[repositoryName].tags; } function listServiceTags() external view returns (bytes32[] tags) { return serviceTags; } function listServicesForTag(bytes32 tag) external view returns (bytes32[] orgNames, bytes32[] serviceNames) { orgNames = servicesByTag[tag].orgNames; serviceNames = servicesByTag[tag].itemNames; } function listTypeRepositoryTags() external view returns (bytes32[] tags) { return typeRepoTags; } function listTypeRepositoriesForTag(bytes32 tag) external view returns (bytes32[] orgNames, bytes32[] repositoryNames) { orgNames = typeReposByTag[tag].orgNames; repositoryNames = typeReposByTag[tag].itemNames; } // ERC165: https://eips.ethereum.org/EIPS/eip-165 function supportsInterface(bytes4 interfaceID) external view returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0xbd523993; // IRegistry } }
* @dev Guard function that forces a revert if the referenced service does not meet an existence criteria. @param exists if true, revert when service does not exist, else revert when service exists/
function requireServiceExistenceConstraint(bytes32 orgName, bytes32 serviceName, bool exists) internal view { if (exists) { require(orgsByName[orgName].servicesByName[serviceName].serviceName != bytes32(0x0), "service does not exist"); require(orgsByName[orgName].servicesByName[serviceName].serviceName == bytes32(0x0), "service already exists"); } }
12,630,365
[ 1, 16709, 445, 716, 26376, 279, 15226, 309, 326, 8042, 1156, 1552, 486, 18721, 392, 15782, 3582, 18, 225, 1704, 309, 638, 16, 15226, 1347, 1156, 1552, 486, 1005, 16, 469, 15226, 1347, 1156, 1704, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2583, 1179, 4786, 802, 5806, 12, 3890, 1578, 2358, 461, 16, 1731, 1578, 6773, 16, 1426, 1704, 13, 2713, 1476, 288, 203, 3639, 309, 261, 1808, 13, 288, 203, 5411, 2583, 12, 280, 564, 5911, 63, 3341, 461, 8009, 8387, 5911, 63, 15423, 8009, 15423, 480, 1731, 1578, 12, 20, 92, 20, 3631, 315, 3278, 1552, 486, 1005, 8863, 203, 5411, 2583, 12, 280, 564, 5911, 63, 3341, 461, 8009, 8387, 5911, 63, 15423, 8009, 15423, 422, 1731, 1578, 12, 20, 92, 20, 3631, 315, 3278, 1818, 1704, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x874B936cc69A68D4cb6f5f24aB90ba60eb376AD6/sources/BitmassExchangeToken.sol
Set the symbol for display purposes (CHANGE THIS)
symbol = "BMEV";
3,979,386
[ 1, 694, 326, 3273, 364, 2562, 13694, 261, 14473, 20676, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 38, 958, 58, 14432, 4766, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x8cdC9deDE6cfe0f8c24eca20c2dc01dB2F4f3032/sources/contracts/registry/ENSRegistryUpgradeable.sol
* The ENS registry contract./
contract ENSRegistryUpgradeable is ENS, Initializable, UUPSProxy { pragma solidity >=0.8.4; import {ENS} from "./interfaces/IENS.sol"; import {UUPSProxy} from "../proxy/UUPSProxy.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32 => Record) records; mapping(address => mapping(address => bool)) operators; modifier authorised(bytes32 _node) { address recordOwner = records[_node].owner; require( recordOwner == msg.sender || operators[recordOwner][msg.sender], "ENSRegistry: not authorised" ); _; } constructor() initializer {} function initialize() public initializer { records[0x0].owner = msg.sender; __UUPSProxy_init(); } function setRecord( bytes32 _node, address _recordOwner, address _resolver, uint64 _ttl ) external virtual override { setOwner(_node, _recordOwner); _setResolverAndTTL(_node, _resolver, _ttl); } function setSubnodeRecord( bytes32 _node, bytes32 _label, address _recordOwner, address _resolver, uint64 _ttl ) external virtual override { bytes32 subnode = setSubnodeOwner(_node, _label, _recordOwner); _setResolverAndTTL(subnode, _resolver, _ttl); } function setOwner(bytes32 _node, address _recordOwner) public virtual override authorised(_node) { _setOwner(_node, _recordOwner); emit Transfer(_node, _recordOwner); } function setSubnodeOwner( bytes32 _node, bytes32 _label, address _recordOwner ) public virtual override authorised(_node) returns (bytes32) { bytes32 subnode = keccak256(abi.encodePacked(_node, _label)); _setOwner(subnode, _recordOwner); emit NewOwner(_node, _label, _recordOwner); return subnode; } function setResolver(bytes32 _node, address _resolver) public virtual override authorised(_node) { emit NewResolver(_node, _resolver); records[_node].resolver = _resolver; } function setTTL(bytes32 _node, uint64 _ttl) public virtual override authorised(_node) { emit NewTTL(_node, _ttl); records[_node].ttl = _ttl; } function setApprovalForAll(address _operator, bool _approved) external virtual override { operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function owner(bytes32 _node) public view virtual override returns (address) { address addr = records[_node].owner; if (addr == address(this)) { return address(0x0); } return addr; } function owner(bytes32 _node) public view virtual override returns (address) { address addr = records[_node].owner; if (addr == address(this)) { return address(0x0); } return addr; } function resolver(bytes32 _node) public view virtual override returns (address) { return records[_node].resolver; } function ttl(bytes32 _node) public view virtual override returns (uint64) { return records[_node].ttl; } function recordExists(bytes32 node) public view virtual override returns (bool) { return records[node].owner != address(0x0); } function isApprovedForAll(address _recordOwner, address _operator) external view virtual override returns (bool) { return operators[_recordOwner][_operator]; } function _setOwner(bytes32 _node, address _recordOwner) internal virtual { address addr = _recordOwner; if (addr == address(0x0)) { addr = address(this); } records[_node].owner = _recordOwner; } function _setOwner(bytes32 _node, address _recordOwner) internal virtual { address addr = _recordOwner; if (addr == address(0x0)) { addr = address(this); } records[_node].owner = _recordOwner; } function _setResolverAndTTL( bytes32 _node, address _resolver, uint64 _ttl ) internal { if (_resolver != records[_node].resolver) { records[_node].resolver = _resolver; emit NewResolver(_node, _resolver); } if (_ttl != records[_node].ttl) { records[_node].ttl = _ttl; emit NewTTL(_node, _ttl); } } function _setResolverAndTTL( bytes32 _node, address _resolver, uint64 _ttl ) internal { if (_resolver != records[_node].resolver) { records[_node].resolver = _resolver; emit NewResolver(_node, _resolver); } if (_ttl != records[_node].ttl) { records[_node].ttl = _ttl; emit NewTTL(_node, _ttl); } } function _setResolverAndTTL( bytes32 _node, address _resolver, uint64 _ttl ) internal { if (_resolver != records[_node].resolver) { records[_node].resolver = _resolver; emit NewResolver(_node, _resolver); } if (_ttl != records[_node].ttl) { records[_node].ttl = _ttl; emit NewTTL(_node, _ttl); } } }
13,287,809
[ 1, 1986, 512, 3156, 4023, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 512, 3156, 4243, 10784, 429, 353, 512, 3156, 16, 10188, 6934, 16, 587, 3079, 55, 3886, 288, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 24, 31, 203, 5666, 288, 21951, 97, 628, 25165, 15898, 19, 45, 21951, 18, 18281, 14432, 203, 5666, 288, 57, 3079, 55, 3886, 97, 628, 315, 6216, 5656, 19, 57, 3079, 55, 3886, 18, 18281, 14432, 203, 5666, 288, 4435, 6934, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 5656, 19, 5471, 19, 4435, 6934, 18, 18281, 14432, 203, 5666, 288, 57, 3079, 55, 10784, 429, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 5656, 19, 5471, 19, 57, 3079, 55, 10784, 429, 18, 18281, 14432, 203, 5666, 288, 5460, 429, 10784, 429, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 3860, 19, 5460, 429, 10784, 429, 18, 18281, 14432, 203, 565, 1958, 5059, 288, 203, 3639, 1758, 3410, 31, 203, 3639, 1758, 5039, 31, 203, 3639, 2254, 1105, 6337, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 3890, 1578, 516, 5059, 13, 3853, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 12213, 31, 203, 203, 565, 9606, 2869, 5918, 12, 3890, 1578, 389, 2159, 13, 288, 203, 3639, 1758, 1409, 5541, 273, 3853, 63, 67, 2159, 8009, 8443, 31, 203, 3639, 2583, 12, 203, 5411, 1409, 5541, 422, 1234, 18, 15330, 747, 12213, 63, 3366, 2 ]
// File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: 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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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: contracts/Storage.sol pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } } // File: contracts/Governable.sol pragma solidity 0.5.16; contract Governable { Storage public store; constructor(address _store) public { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } modifier onlyGovernance() { require(store.isGovernance(msg.sender), "Not governance"); _; } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } function governance() public view returns (address) { return store.governance(); } } // File: contracts/Controllable.sol pragma solidity 0.5.16; contract Controllable is Governable { constructor(address _storage) Governable(_storage) public { } modifier onlyController() { require(store.isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance(){ require((store.isController(msg.sender) || store.isGovernance(msg.sender)), "The caller must be controller or governance"); _; } function controller() public view returns (address) { return store.controller(); } } // File: contracts/uniswap/interfaces/IUniswapV2Router01.sol pragma solidity >=0.5.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts/uniswap/interfaces/IUniswapV2Router02.sol pragma solidity >=0.5.0; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: contracts/hardworkInterface/IStrategy.sol pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } // File: contracts/hardworkInterface/IVault.sol pragma solidity 0.5.16; interface IVault { // the IERC20 part is the share function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; function rebalance() external; } // File: contracts/strategies/SNXRewards/SNXRewardInterface.sol pragma solidity 0.5.16; interface SNXRewardInterface { function withdraw(uint) external; function getReward() external; function stake(uint) external; function balanceOf(address) external view returns (uint); function earned(address account) external view returns (uint256); function exit() external; } // File: contracts/hardworkInterface/IController.sol pragma solidity 0.5.16; interface IController { // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external returns(bool); function addVaultAndStrategy(address _vault, address _strategy) external; function doHardWork(address _vault) external; function hasVault(address _vault) external returns(bool); function salvage(address _token, uint256 amount) external; function salvageStrategy(address _strategy, address _token, uint256 amount) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); } // File: contracts/strategies/RewardTokenProfitNotifier.sol pragma solidity 0.5.16; contract RewardTokenProfitNotifier is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public profitSharingNumerator; uint256 public profitSharingDenominator; address public rewardToken; constructor( address _storage, address _rewardToken ) public Controllable(_storage){ rewardToken = _rewardToken; // persist in the state for immutability of the fee profitSharingNumerator = 5; //IController(controller()).profitSharingNumerator(); profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator(); require(profitSharingNumerator < profitSharingDenominator, "invalid profit share"); } event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); function notifyProfitInRewardToken(uint256 _rewardBalance) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(controller(), 0); IERC20(rewardToken).safeApprove(controller(), feeAmount); IController(controller()).notifyFee( rewardToken, feeAmount ); } else { emit ProfitLogInReward(0, 0, block.timestamp); } } } // File: contracts/uniswap/interfaces/IUniswapV2Pair.sol /** *Submitted for verification at Etherscan.io on 2020-05-05 */ // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/strategies/SNXRewards/SNXRewardUniLPStrategy.sol pragma solidity 0.5.16; /* * This is a general strategy for yields that are based on the synthetix reward contract * for example, yam, spaghetti, ham, shrimp. * * One strategy is deployed for one underlying asset, but the design of the contract * should allow it to switch between different reward contracts. * * It is important to note that not all SNX reward contracts that are accessible via the same interface are * suitable for this Strategy. One concrete example is CREAM.finance, as it implements a "Lock" feature and * would not allow the user to withdraw within some timeframe after the user have deposited. * This would be problematic to user as our "invest" function in the vault could be invoked by anyone anytime * and thus locking/reverting on subsequent withdrawals. Another variation is the YFI Governance: it can * activate a vote lock to stop withdrawal. * * Ref: * 1. CREAM https://etherscan.io/address/0xc29e89845fa794aa0a0b8823de23b760c3d766f5#code * 2. YAM https://etherscan.io/address/0x8538E5910c6F80419CD3170c26073Ff238048c9E#code * 3. SHRIMP https://etherscan.io/address/0x9f83883FD3cadB7d2A83a1De51F9Bf483438122e#code * 4. BASED https://etherscan.io/address/0x5BB622ba7b2F09BF23F1a9b509cd210A818c53d7#code * 5. YFII https://etherscan.io/address/0xb81D3cB2708530ea990a287142b82D058725C092#code * 6. YFIGovernance https://etherscan.io/address/0xBa37B002AbaFDd8E89a1995dA52740bbC013D992#code * * * * Respecting the current system design of choosing the best strategy under the vault, and also rewarding/funding * the public key that invokes the switch of strategies, this smart contract should be deployed twice and linked * to the same vault. When the governance want to rotate the crop, they would set the reward source on the strategy * that is not active, then set that apy higher and this one lower. * * Consequently, in the smart contract we restrict that we can only set a new reward source when it is not active. * */ contract SNXRewardUniLPStrategy is IStrategy, Controllable, RewardTokenProfitNotifier { using SafeMath for uint256; using SafeERC20 for IERC20; ERC20Detailed public underlying; // underlying here would be Uniswap's LP Token / Pair token address public uniLPComponentToken0; address public uniLPComponentToken1; address public vault; bool pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw. SNXRewardInterface public rewardPool; address public rewardToken; // unfortunately, the interface is not unified for rewardToken for all the variants // a flag for disabling selling for simplified emergency exit bool public sell = true; uint256 public sellFloor = 10e18; // UniswapV2Router02 // https://uniswap.org/docs/v2/smart-contracts/router02/ // https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D address public constant uniswapRouterV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); mapping (address => address[]) public uniswapRoutes; // These tokens cannot be claimed by the controller mapping (address => bool) public unsalvagableTokens; event ProfitsNotCollected(); modifier restricted() { require(msg.sender == vault || msg.sender == controller() || msg.sender == governance(), "The sender has to be the controller, governance, or vault"); _; } // This is only used in `investAllUnderlying()` // The user can still freely withdraw from the strategy modifier onlyNotPausedInvesting() { require(!pausedInvesting, "Action blocked as the strategy is in emergency state"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardPool, address _rewardToken ) RewardTokenProfitNotifier(_storage, _rewardToken) public { underlying = ERC20Detailed(_underlying); vault = _vault; uniLPComponentToken0 = IUniswapV2Pair(address(underlying)).token0(); uniLPComponentToken1 = IUniswapV2Pair(address(underlying)).token1(); rewardPool = SNXRewardInterface(_rewardPool); rewardToken = _rewardToken; unsalvagableTokens[_underlying] = true; unsalvagableTokens[_rewardToken] = true; } function depositArbCheck() public view returns(bool) { return true; } /* * In case there are some issues discovered about the pool or underlying asset * Governance can exit the pool properly * The function is only used for emergency to exit the pool */ function emergencyExit() public onlyGovernance { rewardPool.exit(); pausedInvesting = true; } /* * Resumes the ability to invest into the underlying reward pools */ function continueInvesting() public onlyGovernance { pausedInvesting = false; } function setLiquidationPaths(address [] memory _uniswapRouteToToken0, address [] memory _uniswapRouteToToken1) public onlyGovernance { uniswapRoutes[uniLPComponentToken0] = _uniswapRouteToToken0; uniswapRoutes[uniLPComponentToken1] = _uniswapRouteToToken1; } // We assume that all the tradings can be done on Uniswap function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { // Profits can be disabled for possible simplified and rapid exit emit ProfitsNotCollected(); return; } notifyProfitInRewardToken(rewardBalance); uint256 remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (remainingRewardBalance > 0 // we have tokens to swap && uniswapRoutes[address(uniLPComponentToken0)].length > 1 // and we have a route to do the swap && uniswapRoutes[address(uniLPComponentToken1)].length > 1 // and we have a route to do the swap ) { // allow Uniswap to sell our reward uint256 amountOutMin = 1; IERC20(rewardToken).safeApprove(uniswapRouterV2, 0); IERC20(rewardToken).safeApprove(uniswapRouterV2, remainingRewardBalance); // sell Uni to token1 // we can accept 1 as minimum because this is called only by a trusted role IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); uint256 token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this)); // sell Uni to token2 // we can accept 1 as minimum because this is called only by a trusted role remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, uniswapRoutes[uniLPComponentToken1], address(this), block.timestamp ); uint256 token1Amount = IERC20(uniLPComponentToken1).balanceOf(address(this)); // provide token1 and token2 to UniLPToken IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, token1Amount); uint256 liquidity; (,,liquidity) = IUniswapV2Router02(uniswapRouterV2).addLiquidity( uniLPComponentToken0, uniLPComponentToken1, token0Amount, token1Amount, 1, // we are willing to take whatever the pair gives us 1, address(this), block.timestamp ); } } /* * Stakes everything the strategy holds into the reward pool */ function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(underlying.balanceOf(address(this)) > 0) { underlying.approve(address(rewardPool), underlying.balanceOf(address(this))); rewardPool.stake(underlying.balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawAllToVault() public restricted { if (address(rewardPool) != address(0)) { rewardPool.exit(); } _liquidateReward(); IERC20(underlying).safeTransfer(vault, underlying.balanceOf(address(this))); } /* * Withdraws all the asset to the vault */ function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit if(amount > underlying.balanceOf(address(this))){ // While we have the check above, we still using SafeMath below // for the peace of mind (in case something gets changed in between) uint256 needToWithdraw = amount.sub(underlying.balanceOf(address(this))); rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw)); } IERC20(underlying).safeTransfer(vault, amount); } /* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */ function investedUnderlyingBalance() external view returns (uint256) { if (address(rewardPool) == address(0)) { return underlying.balanceOf(address(this)); } // Adding the amount locked in the reward pool and the amount that is somehow in this contract // both are in the units of "underlying" // The second part is needed because there is the emergency exit mechanism // which would break the assumption that all the funds are always inside of the reward pool return rewardPool.balanceOf(address(this)).add(underlying.balanceOf(address(this))); } /* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself * Those are protected by the "unsalvagableTokens". To check, see where those are being flagged. */ function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } /* * Get the reward, sell it in exchange for underlying, invest what you got. * It's not much, but it's honest work. * * Note that although `onlyNotPausedInvesting` is not added here, * calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` * when the investing is being paused by governance. */ function doHardWork() external onlyNotPausedInvesting restricted { rewardPool.getReward(); _liquidateReward(); investAllUnderlying(); } /** * Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the * simplest possible way. */ function setSell(bool s) public onlyGovernance { sell = s; } /** * Sets the minimum amount of CRV needed to trigger a sale. */ function setSellFloor(uint256 floor) public onlyGovernance { sellFloor = floor; } }
a flag for disabling selling for simplified emergency exit UniswapV2Router02 https:uniswap.org/docs/v2/smart-contracts/router02/ https:etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D These tokens cannot be claimed by the controller
contract SNXRewardUniLPStrategy is IStrategy, Controllable, RewardTokenProfitNotifier { using SafeMath for uint256; using SafeERC20 for IERC20; address public uniLPComponentToken0; address public uniLPComponentToken1; address public vault; SNXRewardInterface public rewardPool; bool public sell = true; uint256 public sellFloor = 10e18; address public constant uniswapRouterV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); mapping (address => address[]) public uniswapRoutes; mapping (address => bool) public unsalvagableTokens; event ProfitsNotCollected(); modifier restricted() { require(msg.sender == vault || msg.sender == controller() || msg.sender == governance(), "The sender has to be the controller, governance, or vault"); _; } modifier onlyNotPausedInvesting() { require(!pausedInvesting, "Action blocked as the strategy is in emergency state"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardPool, address _rewardToken ) RewardTokenProfitNotifier(_storage, _rewardToken) public { underlying = ERC20Detailed(_underlying); vault = _vault; uniLPComponentToken0 = IUniswapV2Pair(address(underlying)).token0(); uniLPComponentToken1 = IUniswapV2Pair(address(underlying)).token1(); rewardPool = SNXRewardInterface(_rewardPool); rewardToken = _rewardToken; unsalvagableTokens[_underlying] = true; unsalvagableTokens[_rewardToken] = true; } function depositArbCheck() public view returns(bool) { return true; } function emergencyExit() public onlyGovernance { rewardPool.exit(); pausedInvesting = true; } function continueInvesting() public onlyGovernance { pausedInvesting = false; } function setLiquidationPaths(address [] memory _uniswapRouteToToken0, address [] memory _uniswapRouteToToken1) public onlyGovernance { uniswapRoutes[uniLPComponentToken0] = _uniswapRouteToToken0; uniswapRoutes[uniLPComponentToken1] = _uniswapRouteToToken1; } function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { emit ProfitsNotCollected(); return; } notifyProfitInRewardToken(rewardBalance); uint256 remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); ) { uint256 amountOutMin = 1; IERC20(rewardToken).safeApprove(uniswapRouterV2, 0); IERC20(rewardToken).safeApprove(uniswapRouterV2, remainingRewardBalance); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); uint256 token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this)); remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, uniswapRoutes[uniLPComponentToken1], address(this), block.timestamp ); uint256 token1Amount = IERC20(uniLPComponentToken1).balanceOf(address(this)); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, token1Amount); uint256 liquidity; (,,liquidity) = IUniswapV2Router02(uniswapRouterV2).addLiquidity( uniLPComponentToken0, uniLPComponentToken1, token0Amount, token1Amount, 1, address(this), block.timestamp ); } } function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { emit ProfitsNotCollected(); return; } notifyProfitInRewardToken(rewardBalance); uint256 remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); ) { uint256 amountOutMin = 1; IERC20(rewardToken).safeApprove(uniswapRouterV2, 0); IERC20(rewardToken).safeApprove(uniswapRouterV2, remainingRewardBalance); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); uint256 token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this)); remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, uniswapRoutes[uniLPComponentToken1], address(this), block.timestamp ); uint256 token1Amount = IERC20(uniLPComponentToken1).balanceOf(address(this)); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, token1Amount); uint256 liquidity; (,,liquidity) = IUniswapV2Router02(uniswapRouterV2).addLiquidity( uniLPComponentToken0, uniLPComponentToken1, token0Amount, token1Amount, 1, address(this), block.timestamp ); } } function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { emit ProfitsNotCollected(); return; } notifyProfitInRewardToken(rewardBalance); uint256 remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); ) { uint256 amountOutMin = 1; IERC20(rewardToken).safeApprove(uniswapRouterV2, 0); IERC20(rewardToken).safeApprove(uniswapRouterV2, remainingRewardBalance); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); uint256 token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this)); remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, uniswapRoutes[uniLPComponentToken1], address(this), block.timestamp ); uint256 token1Amount = IERC20(uniLPComponentToken1).balanceOf(address(this)); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, token1Amount); uint256 liquidity; (,,liquidity) = IUniswapV2Router02(uniswapRouterV2).addLiquidity( uniLPComponentToken0, uniLPComponentToken1, token0Amount, token1Amount, 1, address(this), block.timestamp ); } } function investAllUnderlying() internal onlyNotPausedInvesting { if(underlying.balanceOf(address(this)) > 0) { underlying.approve(address(rewardPool), underlying.balanceOf(address(this))); rewardPool.stake(underlying.balanceOf(address(this))); } } function investAllUnderlying() internal onlyNotPausedInvesting { if(underlying.balanceOf(address(this)) > 0) { underlying.approve(address(rewardPool), underlying.balanceOf(address(this))); rewardPool.stake(underlying.balanceOf(address(this))); } } function withdrawAllToVault() public restricted { if (address(rewardPool) != address(0)) { rewardPool.exit(); } _liquidateReward(); IERC20(underlying).safeTransfer(vault, underlying.balanceOf(address(this))); } function withdrawAllToVault() public restricted { if (address(rewardPool) != address(0)) { rewardPool.exit(); } _liquidateReward(); IERC20(underlying).safeTransfer(vault, underlying.balanceOf(address(this))); } function withdrawToVault(uint256 amount) public restricted { if(amount > underlying.balanceOf(address(this))){ uint256 needToWithdraw = amount.sub(underlying.balanceOf(address(this))); rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw)); } IERC20(underlying).safeTransfer(vault, amount); } function withdrawToVault(uint256 amount) public restricted { if(amount > underlying.balanceOf(address(this))){ uint256 needToWithdraw = amount.sub(underlying.balanceOf(address(this))); rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw)); } IERC20(underlying).safeTransfer(vault, amount); } function investedUnderlyingBalance() external view returns (uint256) { if (address(rewardPool) == address(0)) { return underlying.balanceOf(address(this)); } } function investedUnderlyingBalance() external view returns (uint256) { if (address(rewardPool) == address(0)) { return underlying.balanceOf(address(this)); } } return rewardPool.balanceOf(address(this)).add(underlying.balanceOf(address(this))); function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } function doHardWork() external onlyNotPausedInvesting restricted { rewardPool.getReward(); _liquidateReward(); investAllUnderlying(); } function setSell(bool s) public onlyGovernance { sell = s; } function setSellFloor(uint256 floor) public onlyGovernance { sellFloor = floor; } }
415,644
[ 1, 69, 2982, 364, 1015, 17912, 357, 2456, 364, 20482, 801, 24530, 2427, 1351, 291, 91, 438, 58, 22, 8259, 3103, 2333, 30, 318, 291, 91, 438, 18, 3341, 19, 8532, 19, 90, 22, 19, 26416, 17, 16351, 87, 19, 10717, 3103, 19, 2333, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 8646, 2430, 2780, 506, 7516, 329, 635, 326, 2596, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14204, 60, 17631, 1060, 984, 77, 14461, 4525, 353, 467, 4525, 16, 1816, 30453, 16, 534, 359, 1060, 1345, 626, 7216, 14889, 288, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 225, 1758, 1071, 7738, 14461, 1841, 1345, 20, 31, 203, 225, 1758, 1071, 7738, 14461, 1841, 1345, 21, 31, 203, 203, 225, 1758, 1071, 9229, 31, 203, 203, 225, 14204, 60, 17631, 1060, 1358, 1071, 19890, 2864, 31, 203, 203, 225, 1426, 1071, 357, 80, 273, 638, 31, 203, 225, 2254, 5034, 1071, 357, 80, 42, 5807, 273, 1728, 73, 2643, 31, 203, 203, 225, 1758, 1071, 5381, 640, 291, 91, 438, 8259, 58, 22, 273, 1758, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 203, 225, 2874, 261, 2867, 516, 1758, 63, 5717, 1071, 640, 291, 91, 438, 8110, 31, 203, 203, 225, 2874, 261, 2867, 516, 1426, 13, 1071, 16804, 287, 90, 346, 429, 5157, 31, 203, 203, 225, 871, 1186, 18352, 1248, 10808, 329, 5621, 203, 203, 203, 203, 225, 9606, 15693, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 9229, 747, 1234, 18, 15330, 422, 2596, 1435, 203, 1377, 747, 1234, 18, 15330, 422, 314, 1643, 82, 1359, 9334, 203, 1377, 315, 1986, 5793, 711, 358, 506, 326, 2596, 16, 314, 1643, 2 ]
// File: @openzeppelin/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/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) { 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/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) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/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 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: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/SashimiPlates/interfaces/IUniStakingRewards.sol pragma solidity 0.6.12; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } // File: contracts/SashimiPlates/interfaces/ISashimiPlateController.sol pragma solidity 0.6.12; interface ISashimiPlateController { function plates(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } // File: contracts/SashimiPlates/strategies/StrategyUniStakingReward.sol pragma solidity 0.6.12; contract StrategyUniStakingReward { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Staking rewards address for LP providers address public immutable rewards; // want lp tokens address public immutable want; // tokens we're farming address public immutable uni; // stablecoins address public immutable token; // weth address public immutable weth; // dex address public immutable univ2Router2; // How much UNI tokens to keep? uint256 public keepUNI = 0; uint256 public constant keepUNIMax = 10000; // UNI swap threshold uint256 public uniThreshold = 0; // Perfomance fee 4.5% uint256 public performanceFee = 450; uint256 public constant performanceMax = 10000; // Withdrawal fee 0.5% // - 0.375% to treasury // - 0.125% to dev fund uint256 public treasuryFee = 375; uint256 public constant treasuryMax = 100000; uint256 public devFundFee = 125; uint256 public constant devFundMax = 100000; address public governance; address public controller; address public strategist; address public timelock; constructor( address _governance, address _strategist, address _controller, address _timelock, address _rewards, address _token, address _weth, address _uni, address _want, address _univ2Router2 ) public { governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; rewards = _rewards; token = _token; weth = _weth; uni = _uni; want = _want; univ2Router2 = _univ2Router2; } // **** Views **** function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external pure returns (string memory) { return "StrategyUniStakingReward"; } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function setKeepUNI(uint256 _keepUNI) external { require(msg.sender == governance, "!governance"); keepUNI = _keepUNI; } function setUniThreshold(uint256 _uniThreshold) external { require(msg.sender == governance, "!governance"); uniThreshold = _uniThreshold; } function setDevFundFee(uint256 _devFundFee) external { require(msg.sender == governance, "!governance"); devFundFee = _devFundFee; } function setTreasuryFee(uint256 _treasuryFee) external { require(msg.sender == governance, "!governance"); treasuryFee = _treasuryFee; } function setPerformanceFee(uint256 _performanceFee) external { require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State Mutations **** function deposit() public { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).approve(rewards, _want); IStakingRewards(rewards).stake(_want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a plate withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax); IERC20(want).safeTransfer(ISashimiPlateController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax); IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _feeTreasury ); address _plate = ISashimiPlateController(controller).plates(address(want)); require(_plate != address(0), "!plate"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_plate, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _plate = ISashimiPlateController(controller).plates(address(want)); require(_plate != address(0), "!plate"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_plate, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } function brine() public { harvest(); } function harvest() public { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects UNI tokens IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if(_uni <= uniThreshold) return; if (_uni > 0) { // 10% is locked up for future gov uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( ISashimiPlateController(controller).treasury(), _keepUNI ); _swap(uni, weth, _uni.sub(_keepUNI)); } // Swap half WETH for token uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swap(weth, token, _weth.div(2)); } // Adds in liquidity for ETH/token _weth = IERC20(weth).balanceOf(address(this)); uint256 _token = IERC20(token).balanceOf(address(this)); if (_weth > 0 && _token > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token).safeApprove(univ2Router2, 0); IERC20(token).safeApprove(univ2Router2, _token); IUniswapV2Router02(univ2Router2).addLiquidity( weth, token, _weth, _token, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( ISashimiPlateController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token).safeTransfer( ISashimiPlateController(controller).treasury(), IERC20(token).balanceOf(address(this)) ); } // We want to get back UNI ETH/token LP tokens uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Performance fee IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _want.mul(performanceFee).div(performanceMax) ); deposit(); } } // Emergency proxy pattern function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swap( address _from, address _to, uint256 _amount ) internal { // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } IUniswapV2Router02(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } }
Anyone can harvest it at any given time. I understand the possibility of being frontrun But ETH is a dark forest, and I wanna see how this plays out i.e. will be be heavily frontrunned? if so, a new strategy will be deployed. Collects UNI tokens 10% is locked up for future gov Donates DUST Performance fee
function harvest() public { IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if(_uni <= uniThreshold) return; if (_uni > 0) { uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( ISashimiPlateController(controller).treasury(), _keepUNI ); _swap(uni, weth, _uni.sub(_keepUNI)); } if (_weth > 0) { _swap(weth, token, _weth.div(2)); } uint256 _token = IERC20(token).balanceOf(address(this)); if (_weth > 0 && _token > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token).safeApprove(univ2Router2, 0); IERC20(token).safeApprove(univ2Router2, _token); IUniswapV2Router02(univ2Router2).addLiquidity( weth, token, _weth, _token, 0, 0, address(this), now + 60 ); IERC20(weth).transfer( ISashimiPlateController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token).safeTransfer( ISashimiPlateController(controller).treasury(), IERC20(token).balanceOf(address(this)) ); } if (_want > 0) { IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _want.mul(performanceFee).div(performanceMax) ); deposit(); } }
1,967,274
[ 1, 2961, 476, 848, 17895, 26923, 518, 622, 1281, 864, 813, 18, 467, 22413, 326, 25547, 434, 3832, 284, 1949, 313, 318, 12484, 512, 2455, 353, 279, 23433, 30763, 16, 471, 467, 341, 1072, 69, 2621, 3661, 333, 6599, 87, 596, 277, 18, 73, 18, 903, 506, 506, 3904, 842, 3220, 284, 1949, 313, 318, 11748, 35, 1377, 309, 1427, 16, 279, 394, 6252, 903, 506, 19357, 18, 9302, 87, 19462, 2430, 1728, 9, 353, 8586, 731, 364, 3563, 31841, 7615, 815, 463, 5996, 11217, 1359, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 1435, 1071, 288, 203, 203, 3639, 467, 510, 6159, 17631, 14727, 12, 266, 6397, 2934, 588, 17631, 1060, 5621, 203, 3639, 2254, 5034, 389, 318, 77, 273, 467, 654, 39, 3462, 12, 318, 77, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 24899, 318, 77, 1648, 7738, 7614, 13, 327, 31, 203, 3639, 309, 261, 67, 318, 77, 405, 374, 13, 288, 203, 5411, 2254, 5034, 389, 10102, 10377, 273, 389, 318, 77, 18, 16411, 12, 10102, 10377, 2934, 2892, 12, 10102, 10377, 2747, 1769, 203, 5411, 467, 654, 39, 3462, 12, 318, 77, 2934, 4626, 5912, 12, 203, 7734, 4437, 961, 381, 77, 1749, 340, 2933, 12, 5723, 2934, 27427, 345, 22498, 9334, 203, 7734, 389, 10102, 10377, 203, 5411, 11272, 203, 5411, 389, 22270, 12, 318, 77, 16, 341, 546, 16, 389, 318, 77, 18, 1717, 24899, 10102, 10377, 10019, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 91, 546, 405, 374, 13, 288, 203, 5411, 389, 22270, 12, 91, 546, 16, 1147, 16, 389, 91, 546, 18, 2892, 12, 22, 10019, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 389, 2316, 273, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 91, 546, 405, 374, 597, 389, 2316, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 91, 546, 2934, 4626, 12053, 537, 12, 318, 427, 22, 8259, 22, 16, 374, 1769, 203, 5411, 467, 654, 39, 3462, 12, 91, 546, 2 ]
pragma solidity ^0.4.18; //------------------------------- // ( ) ) ( ) // )\ ) ( /(( /( )\ ) ( ( /( //(()/( )\())\())(()/( )\ )\()) // /(_))((_)((_)\ /(_)|((_)((_)\ //(_)) |_ ((_)((_)(_)) )\___ _((_) /// __|| |/ // _ \| _ ((/ __| || | //\__ \ ' <| (_) | /| (__| __ | //|___/ _|\_\\___/|_|_\ \___|_||_| //-------------------------------- //------------------------------------------ // Official Website: https://skorch.io // Github: https://github.com/skorchtoken // Twitter: https://twitter.com/SkorchToken // Reddit: https://reddit.com/r/SkorchToken // Medium: https://medium.com/@skorchtoken // Discord: https://discord.gg/yxZAnfe // Telegram: https://t.me/skorchtoken // ALWAYS refer to our official social media channels and website for project announcements. //------------------------------------------ // Skorch is the first PoW+PoS mineable ERC20 token using Keccak256 (Sha3) algorithm // 210 Million Total Supply // 21 Million available for Proof of Work mining based on Bitcoin's SHA256 Algorithm // 21k (21,000) SKO Required to be held in your wallet to gain Proof of Stake Rewards // 189 Million of 210 Million total supply will be minted by the smart contract for PoS rewards // 30% PoS rewards for the first year but decreases each year after until 0 // PoS requirement decreases after first year and each year after until 0 // Difficulty target auto-adjusts with PoW hashrate // Mining rewards decrease as more tokens are minted // To fix and improve the original Skorch token contract a snapshot was taken at block 5882054. library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } //209899900000000 library ExtendedMath { //return the smaller of the two inputs (a or b) function limitLessThan(uint a, uint b) internal pure returns (uint c) { if(a > b) return b; return a; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract Skorch is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals = 8; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; uint public _BLOCKS_PER_READJUSTMENT = 1024; uint public _MINIMUM_TARGET = 2**16; uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; uint internal GLOBAL_START_TIMER; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => uint256) timer; // timer to check PoS // how to calculate doubleUnit: // specify how much percent increase you want per year // e.g. 130% -> 2.3 multiplier every year // now divide (1 years) by LOG(2.3) where LOG is the natural logarithm (not LOG10) // in this case LOG(2.3) is 0.83290912293 // hence multiplying by 1/0.83290912293 is the same // 31536000 = 1 years (to prevent deprecated warning in solc) // uint256 timerUnit = 2.2075199 * (10**8); uint256 timerUnit = 88416639; // unit for staking req uint256 stakingRequirement = (21000 * (10**uint(decimals))); uint stakeUnit = 930222908; // unit for staking //uint256 stakingCap = (210000000 * (10**uint(decimals))); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); event PoS(address indexed from, uint reward_amount); constructor() public onlyOwner() { symbol = "SKO"; name = "Skorch"; decimals = 8; // uncomment this to test //balances[msg.sender] = (21000) * (10 ** uint(decimals)); // change 21000 to some lower number than 21000 //to see you will not get PoS tokens if you have less than 21000 tokens //timer[msg.sender] = now - (1 years); _totalSupply = 210000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 69750000000000; rewardEra = 0; maxSupplyForEra = 1050000000000000; //miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; //_startNewMiningEpoch(); all relevant vars are set below GLOBAL_START_TIMER = now; challengeNumber = 0x48f499eca7dc41858c2a53fded09096d138b8b88a9da8f488dccd5118bb1bbe2; epochCount = 20181; rewardEra = 0; maxSupplyForEra = (_totalSupply/10) - _totalSupply.div( 20**(rewardEra + 1)); // multiplied by 10 since totalsupply is 210 million here miningTarget = 462884030900683306229868328231836786922375156766639975465481078398; // SNAPSHOT DATA // NEW FILE balances[0xab4485ca338b91087a09ae8bc141648bb1c6e967]=111501588282; emit Transfer(address(0x0), 0xab4485ca338b91087a09ae8bc141648bb1c6e967, 111501588282); balances[0xf2119e50578b3dfa248652c4fbec76b9e415acb2]=10136508025; emit Transfer(address(0x0), 0xf2119e50578b3dfa248652c4fbec76b9e415acb2, 10136508025); balances[0xb12b538cb67fceb50bbc1a31d2011eb92e6f7188]=1583682; emit Transfer(address(0x0), 0xb12b538cb67fceb50bbc1a31d2011eb92e6f7188, 1583682); balances[0x21b7e18dacde5c004a0a56e74f071ac3fb2e98ff]=10790714329; emit Transfer(address(0x0), 0x21b7e18dacde5c004a0a56e74f071ac3fb2e98ff, 10790714329); balances[0xe539a7645d2f33103c89b5b03abb422a163b7c73]=60819048154; emit Transfer(address(0x0), 0xe539a7645d2f33103c89b5b03abb422a163b7c73, 60819048154); balances[0x4ffe17a2a72bc7422cb176bc71c04ee6d87ce329]=451048209723; emit Transfer(address(0x0), 0x4ffe17a2a72bc7422cb176bc71c04ee6d87ce329, 451048209723); balances[0xc0a2002e74b3b22e77098cb87232f446d813ce31]=33885; emit Transfer(address(0x0), 0xc0a2002e74b3b22e77098cb87232f446d813ce31, 33885); balances[0xfc313f77c2cbc6cd0dd82b9a0ed1620ba906e46d]=192593652488; emit Transfer(address(0x0), 0xfc313f77c2cbc6cd0dd82b9a0ed1620ba906e46d, 192593652488); balances[0x219fdb55ea364fcaf29aaa87fb1c45ba7db8128e]=20273016051; emit Transfer(address(0x0), 0x219fdb55ea364fcaf29aaa87fb1c45ba7db8128e, 20273016051); balances[0xfbc2b315ac1fba765597a92ff100222425ce66fd]=608190481542; emit Transfer(address(0x0), 0xfbc2b315ac1fba765597a92ff100222425ce66fd, 608190481542); balances[0x852563d88480decbc9bfb4428bb689af48dd92a9]=1008618359915; emit Transfer(address(0x0), 0x852563d88480decbc9bfb4428bb689af48dd92a9, 1008618359915); balances[0x4d01d11697f00097064d7e05114ecd3843e82867]=789840293838; emit Transfer(address(0x0), 0x4d01d11697f00097064d7e05114ecd3843e82867, 789840293838); balances[0xe75ea07e4b90e46e13c37644138aa99ec69020ae]=526108154879; emit Transfer(address(0x0), 0xe75ea07e4b90e46e13c37644138aa99ec69020ae, 526108154879); balances[0x51138ab5497b2c3d85be94d23905f5ead9e533a7]=5068254012; emit Transfer(address(0x0), 0x51138ab5497b2c3d85be94d23905f5ead9e533a7, 5068254012); balances[0xae7c95f2192c739edfb16412a6112a54f8965305]=55750794141; emit Transfer(address(0x0), 0xae7c95f2192c739edfb16412a6112a54f8965305, 55750794141); balances[0xe0261acfdd10508c75b6a60b1534c8386c4daa52]=5047016671743; emit Transfer(address(0x0), 0xe0261acfdd10508c75b6a60b1534c8386c4daa52, 5047016671743); balances[0x0a26d9674c2a1581ada4316e3f5960bb70fb0fb2]=516961909310; emit Transfer(address(0x0), 0x0a26d9674c2a1581ada4316e3f5960bb70fb0fb2, 516961909310); balances[0xa62178f120cccba370d2d2d12ec6fb1ff276d706]=2052642875205; emit Transfer(address(0x0), 0xa62178f120cccba370d2d2d12ec6fb1ff276d706, 2052642875205); balances[0xe57a18783640c9fa3c5e8e4d4b4443e2024a7ff9]=2494738345632; emit Transfer(address(0x0), 0xe57a18783640c9fa3c5e8e4d4b4443e2024a7ff9, 2494738345632); balances[0x9b8957d1ac592bd388dcde346933ac1269b7c314]=106433334269; emit Transfer(address(0x0), 0x9b8957d1ac592bd388dcde346933ac1269b7c314, 106433334269); balances[0xf27bb893a4d9574378c4b1d089bdb6b9fce5099e]=380845; emit Transfer(address(0x0), 0xf27bb893a4d9574378c4b1d089bdb6b9fce5099e, 380845); balances[0x54a8f792298af9489de7a1245169a943fb69f5a6]=707886981662; emit Transfer(address(0x0), 0x54a8f792298af9489de7a1245169a943fb69f5a6, 707886981662); balances[0x004ba728a652bded4d4b79fb04b5a92ad8ce15e7]=21250198; emit Transfer(address(0x0), 0x004ba728a652bded4d4b79fb04b5a92ad8ce15e7, 21250198); balances[0xd05803aee240195460f8589a6d6487fcea0097c1]=85731; emit Transfer(address(0x0), 0xd05803aee240195460f8589a6d6487fcea0097c1, 85731); balances[0xad9f11d1dd6d202243473a0cdae606308ab243b4]=101365080257; emit Transfer(address(0x0), 0xad9f11d1dd6d202243473a0cdae606308ab243b4, 101365080257); balances[0xfec55e783595682141c4b5e6ad9ea605f1683844]=60657099080; emit Transfer(address(0x0), 0xfec55e783595682141c4b5e6ad9ea605f1683844, 60657099080); balances[0x99a7e5777b711ff23e2b6961232a4009f7cec1b0]=456860909542; emit Transfer(address(0x0), 0x99a7e5777b711ff23e2b6961232a4009f7cec1b0, 456860909542); balances[0xbf45f4280cfbe7c2d2515a7d984b8c71c15e82b7]=1366848029003; emit Transfer(address(0x0), 0xbf45f4280cfbe7c2d2515a7d984b8c71c15e82b7, 1366848029003); balances[0xb38094d492af4fffff760707f36869713bfb2250]=2032369859152; emit Transfer(address(0x0), 0xb38094d492af4fffff760707f36869713bfb2250, 2032369859152); balances[0x900953b10460908ec636b46307dca13a759275cb]=1856435; emit Transfer(address(0x0), 0x900953b10460908ec636b46307dca13a759275cb, 1856435); balances[0x167e733de0861f0d61b179d3d1891e6b90587732]=2047574621189; emit Transfer(address(0x0), 0x167e733de0861f0d61b179d3d1891e6b90587732, 2047574621189); balances[0xdb3cbb8aa4dec854e6e60982dd9d4e85a8b422bc]=2; emit Transfer(address(0x0), 0xdb3cbb8aa4dec854e6e60982dd9d4e85a8b422bc, 2); balances[0x072e8711704654019c3d9bc242b3f9a4ee1963ce]=10136236279; emit Transfer(address(0x0), 0x072e8711704654019c3d9bc242b3f9a4ee1963ce, 10136236279); balances[0x04f72aa695b65a54d79db635005077293d111635]=167020515303; emit Transfer(address(0x0), 0x04f72aa695b65a54d79db635005077293d111635, 167020515303); balances[0x30385a99e66469a8c0bf172896758dd4595704a9]=614699515479; emit Transfer(address(0x0), 0x30385a99e66469a8c0bf172896758dd4595704a9, 614699515479); balances[0xfe5a94e5bab010f52ae8fd8589b7d0a7b0b433ae]=2067847571118; emit Transfer(address(0x0), 0xfe5a94e5bab010f52ae8fd8589b7d0a7b0b433ae, 2067847571118); balances[0x88058d4d90cc9d9471509e5be819b2be361b51c6]=957900008429; emit Transfer(address(0x0), 0x88058d4d90cc9d9471509e5be819b2be361b51c6, 957900008429); balances[0xfcc6bf3369077e22a90e05ad567744bf5109e4d4]=1635580659302; emit Transfer(address(0x0), 0xfcc6bf3369077e22a90e05ad567744bf5109e4d4, 1635580659302); balances[0x21a6043877a0ac376b7ca91195521de88d440eba]=162184128411; emit Transfer(address(0x0), 0x21a6043877a0ac376b7ca91195521de88d440eba, 162184128411); balances[0xd7dd80404d3d923c8a40c47c1f61aacbccb4191e]=3569292763171; emit Transfer(address(0x0), 0xd7dd80404d3d923c8a40c47c1f61aacbccb4191e, 3569292763171); balances[0xa1a3e2fcc1e7c805994ca7309f9a829908a18b4c]=633301706054; emit Transfer(address(0x0), 0xa1a3e2fcc1e7c805994ca7309f9a829908a18b4c, 633301706054); balances[0xc5556ce5c51d2f6a8d7a54bec2a9961dfada84db]=2471775966918; emit Transfer(address(0x0), 0xc5556ce5c51d2f6a8d7a54bec2a9961dfada84db, 2471775966918); balances[0xb4894098be4dbfdc0024dfb9d2e9f6654e0e3786]=10053178133; emit Transfer(address(0x0), 0xb4894098be4dbfdc0024dfb9d2e9f6654e0e3786, 10053178133); balances[0xe8a01b61f80130aefda985ee2e9c6899a57a17c8]=177388890449; emit Transfer(address(0x0), 0xe8a01b61f80130aefda985ee2e9c6899a57a17c8, 177388890449); balances[0x559a922941f84ebe6b9f0ed58e3b96530614237e]=65887302167; emit Transfer(address(0x0), 0x559a922941f84ebe6b9f0ed58e3b96530614237e, 65887302167); balances[0xf95f528d7c25904f15d4154e45eab8e5d4b6c160]=425572373267; emit Transfer(address(0x0), 0xf95f528d7c25904f15d4154e45eab8e5d4b6c160, 425572373267); balances[0x0045b9707913eae3889283ed4d72077a904b9848]=1507541146428; emit Transfer(address(0x0), 0x0045b9707913eae3889283ed4d72077a904b9848, 1507541146428); balances[0x586389feed58c2c6a0ce6258cb1c58833abdb093]=2603426; emit Transfer(address(0x0), 0x586389feed58c2c6a0ce6258cb1c58833abdb093, 2603426); balances[0xd2b752bec2fe5c7e5cc600eb5ce465a210cb857a]=380119050963; emit Transfer(address(0x0), 0xd2b752bec2fe5c7e5cc600eb5ce465a210cb857a, 380119050963); balances[0x518bbb5e4a1e8f8f21a09436c35b9cb5c20c7b43]=5037433249; emit Transfer(address(0x0), 0x518bbb5e4a1e8f8f21a09436c35b9cb5c20c7b43, 5037433249); balances[0x25e5c43d5f53ee1a7dd5ad7560348e29baea3048]=5068254012; emit Transfer(address(0x0), 0x25e5c43d5f53ee1a7dd5ad7560348e29baea3048, 5068254012); balances[0x22dd964193df4de2e6954a2a9d9cbbd6f44f0b28]=2754253183453; emit Transfer(address(0x0), 0x22dd964193df4de2e6954a2a9d9cbbd6f44f0b28, 2754253183453); balances[0xaa7a7c2decb180f68f11e975e6d92b5dc06083a6]=116569842295; emit Transfer(address(0x0), 0xaa7a7c2decb180f68f11e975e6d92b5dc06083a6, 116569842295); balances[0x4e27a678c8dc883035c542c83124e7e3f39842b0]=35477778089; emit Transfer(address(0x0), 0x4e27a678c8dc883035c542c83124e7e3f39842b0, 35477778089); balances[0x3bd56f97876d3af248b1fe92e361c05038c74c27]=15181683975; emit Transfer(address(0x0), 0x3bd56f97876d3af248b1fe92e361c05038c74c27, 15181683975); balances[0x674194d05bfc9a176a5b84711c8687609ff3d17b]=4287056630970; emit Transfer(address(0x0), 0x674194d05bfc9a176a5b84711c8687609ff3d17b, 4287056630970); balances[0x0102f6ca7278e7d96a6d649da30bfe07e87155a3]=1233053375653; emit Transfer(address(0x0), 0x0102f6ca7278e7d96a6d649da30bfe07e87155a3, 1233053375653); balances[0x3750ecf5e0536d04dd3858173ab571a0dcbdf7e0]=50270330036; emit Transfer(address(0x0), 0x3750ecf5e0536d04dd3858173ab571a0dcbdf7e0, 50270330036); balances[0x07a68bd44a526e09b8dbfc7085b265450362b61a]=101365080257; emit Transfer(address(0x0), 0x07a68bd44a526e09b8dbfc7085b265450362b61a, 101365080257); balances[0xebd76aa221968b8ba9cdd6e6b4dbb889140088a3]=309163494783; emit Transfer(address(0x0), 0xebd76aa221968b8ba9cdd6e6b4dbb889140088a3, 309163494783); balances[0xc7ee330d69cdddc1b9955618ff0df27bb8de3143]=10098567209; emit Transfer(address(0x0), 0xc7ee330d69cdddc1b9955618ff0df27bb8de3143, 10098567209); balances[0xe0c059faabce16dd5ddb4817f427f5cf3b40f4c4]=656449480989; emit Transfer(address(0x0), 0xe0c059faabce16dd5ddb4817f427f5cf3b40f4c4, 656449480989); balances[0xdc680cc11a535e45329f49566850668fef34054f]=1629652247199; emit Transfer(address(0x0), 0xdc680cc11a535e45329f49566850668fef34054f, 1629652247199); balances[0x22ef324a534ba9aa0d060c92294fdd0fc4aca065]=105388398778; emit Transfer(address(0x0), 0x22ef324a534ba9aa0d060c92294fdd0fc4aca065, 105388398778); balances[0xe14cffadb6bbad8de69bd5ba214441a9582ec548]=70955556179; emit Transfer(address(0x0), 0xe14cffadb6bbad8de69bd5ba214441a9582ec548, 70955556179); balances[0xdfb895c870c4956261f4839dd12786ef612d7314]=307632851383; emit Transfer(address(0x0), 0xdfb895c870c4956261f4839dd12786ef612d7314, 307632851383); balances[0x620103bb2b263ab0a50a47f73140d218401541c0]=10780637244561; emit Transfer(address(0x0), 0x620103bb2b263ab0a50a47f73140d218401541c0, 10780637244561); balances[0x9fc5b0edc0309745c6974f1a6718029ea41a4d6e]=65859631176; emit Transfer(address(0x0), 0x9fc5b0edc0309745c6974f1a6718029ea41a4d6e, 65859631176); balances[0xd6ceae2756f2af0a2f825b6e3ca8a9cfb4d082e2]=1122517124649; emit Transfer(address(0x0), 0xd6ceae2756f2af0a2f825b6e3ca8a9cfb4d082e2, 1122517124649); balances[0x25437b6a20021ea94d549ddd50403994e532e9d7]=1711954946632; emit Transfer(address(0x0), 0x25437b6a20021ea94d549ddd50403994e532e9d7, 1711954946632); balances[0xeb4f4c886b402c65ff6f619716efe9319ce40fcf]=526035186557; emit Transfer(address(0x0), 0xeb4f4c886b402c65ff6f619716efe9319ce40fcf, 526035186557); balances[0xf3552d4018fad9fcc390f5684a243f7318d8b570]=253412700642; emit Transfer(address(0x0), 0xf3552d4018fad9fcc390f5684a243f7318d8b570, 253412700642); balances[0x85abe8e3bed0d4891ba201af1e212fe50bb65a26]=1060373239943; emit Transfer(address(0x0), 0x85abe8e3bed0d4891ba201af1e212fe50bb65a26, 1060373239943); balances[0xc446073e0c00a1138812b3a99a19df3cb8ace70d]=2032369859153; emit Transfer(address(0x0), 0xc446073e0c00a1138812b3a99a19df3cb8ace70d, 2032369859153); balances[0x195d65187a4aeb24b563dd2d52709a6b67064ad3]=235803680643; emit Transfer(address(0x0), 0x195d65187a4aeb24b563dd2d52709a6b67064ad3, 235803680643); balances[0x588611841bd8b134f3d6ca3ff2796b483dfca4c6]=27875; emit Transfer(address(0x0), 0x588611841bd8b134f3d6ca3ff2796b483dfca4c6, 27875); balances[0x43237ce180fc47cb4e3d32eb23e420f5ecf7a95e]=5087020825285; emit Transfer(address(0x0), 0x43237ce180fc47cb4e3d32eb23e420f5ecf7a95e, 5087020825285); balances[0x394299ef1650ac563a9adbec4061b25e50570f49]=65523270720; emit Transfer(address(0x0), 0x394299ef1650ac563a9adbec4061b25e50570f49, 65523270720); balances[0x0000bb50ee5f5df06be902d1f9cb774949c337ed]=728415; emit Transfer(address(0x0), 0x0000bb50ee5f5df06be902d1f9cb774949c337ed, 728415); balances[0x4927fb34fff626adb7b07305c447ac89ded8bea2]=15181318646; emit Transfer(address(0x0), 0x4927fb34fff626adb7b07305c447ac89ded8bea2, 15181318646); balances[0x93da7b2830e3932d906749e67a7ce1fbf3a5366d]=2768553093810; emit Transfer(address(0x0), 0x93da7b2830e3932d906749e67a7ce1fbf3a5366d, 2768553093810); balances[0x7f4924f55e215e1fe44e3b5bb7fdfced2154b30f]=506445600761; emit Transfer(address(0x0), 0x7f4924f55e215e1fe44e3b5bb7fdfced2154b30f, 506445600761); balances[0x9834977aa420b078b8fd47c73a9520f968d66a3a]=1035039327674; emit Transfer(address(0x0), 0x9834977aa420b078b8fd47c73a9520f968d66a3a, 1035039327674); balances[0x26b8c7606e828a509bbb208a0322cf960c17b225]=1314664139193; emit Transfer(address(0x0), 0x26b8c7606e828a509bbb208a0322cf960c17b225, 1314664139193); balances[0x8f3dd21c9334980030ba95c37565ba25df9574cd]=20273016051; emit Transfer(address(0x0), 0x8f3dd21c9334980030ba95c37565ba25df9574cd, 20273016051); balances[0x85d66f3a8da35f47e03d6bb51f51c2d70a61e12e]=10419370357974; emit Transfer(address(0x0), 0x85d66f3a8da35f47e03d6bb51f51c2d70a61e12e, 10419370357974); balances[0xbafc492638a2ec4f89aff258c8f18f806a844d72]=396663813367; emit Transfer(address(0x0), 0xbafc492638a2ec4f89aff258c8f18f806a844d72, 396663813367); balances[0x2f0d5a1d6bb5d7eaa0eaad39518621911a4a1d9f]=45613275677; emit Transfer(address(0x0), 0x2f0d5a1d6bb5d7eaa0eaad39518621911a4a1d9f, 45613275677); balances[0xae5910c6f3cd709bf497bae2b8eae8cf983aca1b]=561729123519; emit Transfer(address(0x0), 0xae5910c6f3cd709bf497bae2b8eae8cf983aca1b, 561729123519); balances[0xb963db36d28468ce64bce65e560e5f27e75f2f50]=50497795029; emit Transfer(address(0x0), 0xb963db36d28468ce64bce65e560e5f27e75f2f50, 50497795029); balances[0x7134161b9e6fa84d62f156037870ee77fa50f607]=806825; emit Transfer(address(0x0), 0x7134161b9e6fa84d62f156037870ee77fa50f607, 806825); balances[0x111fd8a12981d1174cfa8eef3b0141b3d5d4e5b3]=5023380788; emit Transfer(address(0x0), 0x111fd8a12981d1174cfa8eef3b0141b3d5d4e5b3, 5023380788); balances[0xafaf9a165408737e11191393fe695c1ebc7a5429]=3750469994332; emit Transfer(address(0x0), 0xafaf9a165408737e11191393fe695c1ebc7a5429, 3750469994332); balances[0x5329fcc196c445009aac138b22d25543ed195888]=126671028590; emit Transfer(address(0x0), 0x5329fcc196c445009aac138b22d25543ed195888, 126671028590); balances[0xa5b3725e37431dc6a103961749cb9c98954202cd]=446006353130; emit Transfer(address(0x0), 0xa5b3725e37431dc6a103961749cb9c98954202cd, 446006353130); balances[0xb8ab7387076f022c28481fafb28911ce4377e0ea]=3045242779146; emit Transfer(address(0x0), 0xb8ab7387076f022c28481fafb28911ce4377e0ea, 3045242779146); balances[0xd2470aacd96242207f06111819111d17ca055dfb]=957900008429; emit Transfer(address(0x0), 0xd2470aacd96242207f06111819111d17ca055dfb, 957900008429); balances[0x1fca39ed4f19edd12eb274dc467c099eb5106a13]=278753970706; emit Transfer(address(0x0), 0x1fca39ed4f19edd12eb274dc467c099eb5106a13, 278753970706); balances[0x8d12a197cb00d4747a1fe03395095ce2a5cc6819]=4743885756029; emit Transfer(address(0x0), 0x8d12a197cb00d4747a1fe03395095ce2a5cc6819, 4743885756029); balances[0x2a23527a6dbafae390514686d50f47747d01e44d]=652376852116; emit Transfer(address(0x0), 0x2a23527a6dbafae390514686d50f47747d01e44d, 652376852116); balances[0x371e31169df00563eafab334c738e66dd0476a8f]=226377928506; emit Transfer(address(0x0), 0x371e31169df00563eafab334c738e66dd0476a8f, 226377928506); balances[0x40ea0a2abc9479e51e411870cafd759cb110c258]=30282012248; emit Transfer(address(0x0), 0x40ea0a2abc9479e51e411870cafd759cb110c258, 30282012248); balances[0xe585ba86b84283f0f1118041837b06d03b96885e]=170791; emit Transfer(address(0x0), 0xe585ba86b84283f0f1118041837b06d03b96885e, 170791); balances[0xbede88c495132efb90b5039bc2942042e07814df]=40513641855; emit Transfer(address(0x0), 0xbede88c495132efb90b5039bc2942042e07814df, 40513641855); // test lines //balances[msg.sender] = 21000 * (10 ** uint(decimals)); //timer[msg.sender ] = ( now - ( 1 years)); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); if (digest != challenge_digest) revert(); if(uint256(digest) > miningTarget) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice _claimTokens(msg.sender); timer[msg.sender]=now; uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); assert(tokensMinted <= maxSupplyForEra); lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, reward_amount, epochCount, challengeNumber ); emit Transfer(address(0x0), msg.sender, reward_amount); return true; } function _startNewMiningEpoch() internal { if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39) { rewardEra = rewardEra + 1; } maxSupplyForEra = _totalSupply/10 - _totalSupply.div( 20**(rewardEra + 1)); epochCount = epochCount.add(1); if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; uint epochsMined = _BLOCKS_PER_READJUSTMENT; uint targetEthBlocksPerDiffPeriod = epochsMined * 60; //should be 60 times slower than ethereum if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % }else{ uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } function getMiningReward() public constant returns (uint) { return (50 * 10**uint(decimals) ).div( 2**rewardEra ) ; } function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); return digest; } function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner] + _getPoS(tokenOwner); // add unclaimed pos tokens } function transfer(address to, uint tokens) public returns (bool success) { _claimTokens(msg.sender); _claimTokens(to); timer[msg.sender] = now; timer[to] = now; balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { _claimTokens(from); _claimTokens(to); timer[from] = now; timer[to] = now; balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } function claimTokens() public { _claimTokens(msg.sender); timer[msg.sender] = now; } function _claimTokens(address target) internal{ if (timer[target] == 0){ // russian hackers BTFO if (balances[target] > 0){ // timer is handled in _getPoS } else{ return; } } if (timer[target] == now){ // 0 seconds passed, 0 tokens gotten via PoS // return so no gas waste return; } uint256 totalTkn = _getPoS(target); if (totalTkn > 0){ balances[target] = balances[target].add(totalTkn); //_totalSupply.add(totalTkn); total supply is fixed emit PoS(target, totalTkn); } //timer[target] = now; every time you claim tokens this timer is set. this is to prevent people claiming 0 tokens and then setting their timer emit Transfer(address(0x0), target, totalTkn); } function getStakingRequirementTime(address target, uint256 TIME) view returns (uint256){ return (stakingRequirement * fixedExp(((int(GLOBAL_START_TIMER) - int(TIME)) * one) / int(timerUnit)))/uint(one) ; } function getRequirementTime(address target) view returns (uint256) { uint256 balance = balances[target]; int ONE = 0x10000000000000000; if (balance == 0){ return (uint256(0) - 1); // inf } uint TIME = timer[target]; if (TIME == 0){ TIME = GLOBAL_START_TIMER; } int ln = fixedLog((balance * uint(one)) / stakingRequirement); int mul = (int(timerUnit) * ln) / (int(one)); uint pos = uint( -mul); return (pos + GLOBAL_START_TIMER); } function GetStakingNow() view returns (uint256){ return (stakingRequirement * fixedExp(((int(GLOBAL_START_TIMER) - int(now)) * one) / int(timerUnit)))/uint(one) ; } function _getPoS(address target) internal view returns (uint256){ if (balances[target] == 0){ return 0; } int ONE_SECOND = 0x10000000000000000; uint TIME = timer[target]; if (TIME == 0){ TIME = GLOBAL_START_TIMER; } if (balances[target] < getStakingRequirementTime(target, TIME)){ // staking requirement was too low at update // maybe it has since surpassed the requirement? uint flipTime = getRequirementTime(target); if ( now > flipTime ){ TIME = flipTime; } else{ return 0; } } int PORTION_SCALED = ( (int(GLOBAL_START_TIMER) - int(TIME)) * ONE_SECOND) / int(stakeUnit); uint256 exp = fixedExp(PORTION_SCALED); PORTION_SCALED = ( (int(GLOBAL_START_TIMER) - int(now)) * ONE_SECOND) / int(stakeUnit); uint256 exp2 = fixedExp(PORTION_SCALED); uint256 MULT = (9 * (exp.sub(exp2)) * (balances[target])) / (uint(one)); return (MULT); } int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5= 0x2cb53f09f05cc627c8; int256 constant one = 0x10000000000000000; int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; function fixedExp(int256 a) public pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } }
staking requirement was too low at update maybe it has since surpassed the requirement?
function _getPoS(address target) internal view returns (uint256){ if (balances[target] == 0){ return 0; } int ONE_SECOND = 0x10000000000000000; uint TIME = timer[target]; if (TIME == 0){ TIME = GLOBAL_START_TIMER; } if (balances[target] < getStakingRequirementTime(target, TIME)){ uint flipTime = getRequirementTime(target); if ( now > flipTime ){ TIME = flipTime; } else{ return 0; } } int PORTION_SCALED = ( (int(GLOBAL_START_TIMER) - int(TIME)) * ONE_SECOND) / int(stakeUnit); uint256 exp = fixedExp(PORTION_SCALED); PORTION_SCALED = ( (int(GLOBAL_START_TIMER) - int(now)) * ONE_SECOND) / int(stakeUnit); uint256 exp2 = fixedExp(PORTION_SCALED); uint256 MULT = (9 * (exp.sub(exp2)) * (balances[target])) / (uint(one)); return (MULT); } int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5= 0x2cb53f09f05cc627c8; int256 constant one = 0x10000000000000000; int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f;
402,504
[ 1, 334, 6159, 12405, 1703, 4885, 4587, 622, 1089, 6944, 518, 711, 3241, 5056, 23603, 326, 12405, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 29198, 55, 12, 2867, 1018, 13, 2713, 1476, 1135, 261, 11890, 5034, 15329, 203, 3639, 309, 261, 70, 26488, 63, 3299, 65, 422, 374, 15329, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 509, 15623, 67, 16328, 273, 374, 92, 21, 12648, 12648, 31, 203, 3639, 2254, 8721, 273, 5441, 63, 3299, 15533, 203, 3639, 309, 261, 4684, 422, 374, 15329, 203, 5411, 8721, 273, 7779, 67, 7570, 67, 56, 31582, 31, 203, 3639, 289, 203, 3639, 309, 261, 70, 26488, 63, 3299, 65, 411, 21491, 6159, 18599, 950, 12, 3299, 16, 8721, 3719, 95, 203, 5411, 2254, 9668, 950, 273, 5561, 1039, 475, 950, 12, 3299, 1769, 203, 5411, 309, 261, 2037, 405, 9668, 950, 262, 95, 203, 7734, 8721, 273, 9668, 950, 31, 203, 5411, 289, 203, 5411, 469, 95, 203, 7734, 327, 374, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 509, 20987, 1146, 67, 8754, 6687, 273, 261, 261, 474, 12, 20402, 67, 7570, 67, 56, 31582, 13, 300, 509, 12, 4684, 3719, 380, 15623, 67, 16328, 13, 342, 509, 12, 334, 911, 2802, 1769, 7010, 3639, 2254, 5034, 1329, 273, 5499, 2966, 12, 6354, 1146, 67, 8754, 6687, 1769, 203, 540, 203, 3639, 20987, 1146, 67, 8754, 6687, 273, 261, 261, 474, 12, 20402, 67, 7570, 67, 56, 31582, 13, 300, 509, 12, 3338, 3719, 380, 15623, 67, 16328, 13, 342, 509, 12, 334, 911, 2802, 1769, 7010, 3639, 2254, 5034, 1329, 22, 273, 5499, 2966, 12, 6354, 1146, 67, 8754, 6687, 2 ]
./partial_match/4/0xEf7b3DA219D2A15CE327950cEA1666602A19dBaE/sources/InstantSwap.sol
* Swap Out function Deposit Asset backed tokens and claim back external tokens Prices are calculated from API services/@dev 'msg.sender' should have balance of 'address(this)' 'asset'@dev 'address(this)' should have balance of 'token' 'value'
function swapOut(address assetAdd, uint256 asset) external validateAsset(assetAdd) { _swapOut(assetAdd, asset); }
8,664,543
[ 1, 12521, 2976, 445, 4019, 538, 305, 10494, 20732, 2430, 471, 7516, 1473, 3903, 2430, 2301, 1242, 854, 8894, 628, 1491, 4028, 19, 296, 3576, 18, 15330, 11, 1410, 1240, 11013, 434, 296, 2867, 12, 2211, 2506, 296, 9406, 11, 296, 2867, 12, 2211, 2506, 1410, 1240, 11013, 434, 296, 2316, 11, 296, 1132, 11, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1182, 12, 2867, 3310, 986, 16, 2254, 5034, 3310, 13, 7010, 3639, 3903, 7010, 3639, 1954, 6672, 12, 9406, 986, 13, 288, 203, 540, 203, 3639, 389, 22270, 1182, 12, 9406, 986, 16, 3310, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../modules/license/ILicenseController.sol"; import "../modules/ComponentController.sol"; import "../shared/WithRegistry.sol"; import "../shared/IModuleController.sol"; import "../shared/IModuleStorage.sol"; import "@gif-interface/contracts/modules/IAccess.sol"; import "@gif-interface/contracts/modules/IQuery.sol"; import "@gif-interface/contracts/services/IInstanceOperatorService.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract InstanceOperatorService is IInstanceOperatorService, WithRegistry, Ownable { bytes32 public constant NAME = "InstanceOperatorService"; // solhint-disable-next-line no-empty-blocks constructor(address _registry) WithRegistry(_registry) {} function assignController(address _storage, address _controller) external override onlyOwner { IModuleStorage(_storage).assignController(_controller); } function assignStorage(address _controller, address _storage) external override onlyOwner { IModuleController(_controller).assignStorage(_storage); } /* License */ function approveProduct(uint256 _productId) external override onlyOwner { license().approveProduct(_productId); } function disapproveProduct(uint256 _productId) external override onlyOwner { license().disapproveProduct(_productId); } function pauseProduct(uint256 _productId) external override onlyOwner { license().pauseProduct(_productId); } /* Access */ function productOwnerRole() public view returns(bytes32) { return access().productOwnerRole(); } function oracleProviderRole() public view returns(bytes32) { return access().oracleProviderRole(); } function riskpoolKeeperRole() public view returns(bytes32) { return access().riskpoolKeeperRole(); } // TODO add to interface IInstanceOperatorService function hasRole(bytes32 _role, address _address) public view returns(bool) { return access().hasRole(_role, _address); } // TODO update interface and rename to addRole function createRole(bytes32 _role) external override onlyOwner { access().addRole(_role); } // TODO update interface and rename to grantRole and switch argument order function addRoleToAccount(address _address, bytes32 _role) external override onlyOwner { access().grantRole(_role, _address); } // TODO add implementation in accesscontroller function cleanRolesForAccount(address _address) external override onlyOwner { } /* Registry */ function registerInRelease( bytes32 _release, bytes32 _contractName, address _contractAddress ) external override onlyOwner { registry.registerInRelease(_release, _contractName, _contractAddress); } function register(bytes32 _contractName, address _contractAddress) external override onlyOwner { registry.register(_contractName, _contractAddress); } function deregisterInRelease(bytes32 _release, bytes32 _contractName) external override onlyOwner { registry.deregisterInRelease(_release, _contractName); } function deregister(bytes32 _contractName) external override onlyOwner { registry.deregister(_contractName); } function prepareRelease(bytes32 _newRelease) external override onlyOwner { registry.prepareRelease(_newRelease); } /* Query */ function approveOracle(uint256 _oracleId) external override onlyOwner { address [] memory tokens = new address[](0); uint256 [] memory amounts = new uint256[](0); component().approve(_oracleId, tokens, amounts); } // TODO align with component neutral workflows function disapproveOracle(uint256 _oracleId) external override onlyOwner { // query().disapproveOracle(_oracleId); component().decline(_oracleId); } /* Inventory */ function products() external override view returns(uint256) { return license().getProductCount(); } function oracles() external override view returns(uint256) { // TODO continue here // return query().getOracleCount(); return component().oracles(); } /* Lookup */ function access() internal view returns (IAccess) { return IAccess(registry.getContract("Access")); } function component() internal view returns (ComponentController) { return ComponentController(registry.getContract("Component")); } function license() internal view returns (ILicenseController) { return ILicenseController(registry.getContract("License")); } function query() internal view returns (IQuery) { return IQuery(registry.getContract("Query")); } }
TODO update interface and rename to addRole
function createRole(bytes32 _role) external override onlyOwner { access().addRole(_role); }
12,784,056
[ 1, 6241, 1089, 1560, 471, 6472, 358, 527, 2996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 2996, 12, 3890, 1578, 389, 4615, 13, 7010, 3639, 3903, 3849, 203, 3639, 1338, 5541, 7010, 565, 288, 203, 3639, 2006, 7675, 1289, 2996, 24899, 4615, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xe0Ab69528526a07c03335B64487cFD5fD7273501/sources/index.sol
@dev Swaps one token for another. The router must support swap callbacks and ensure there isn't too much slippage. @dev Check Trident router has sent `amountIn` for skim into pool.
function flashSwap(bytes calldata data) public override lock returns (uint256 amountOut) { ( address tokenIn, address tokenOut, address recipient, bool unwrapBento, uint256 amountIn, bytes memory context ) = abi.decode(data, (address, address, address, bool, uint256, bytes)); Record storage inRecord = records[tokenIn]; Record storage outRecord = records[tokenOut]; require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO"); amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight); ITridentCallee(msg.sender).tridentSwapCallback(context); require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED"); inRecord.reserve += uint120(amountIn); outRecord.reserve -= uint120(amountOut); }
9,572,394
[ 1, 6050, 6679, 1245, 1147, 364, 4042, 18, 1021, 4633, 1297, 2865, 7720, 6689, 471, 3387, 1915, 5177, 1404, 4885, 9816, 272, 3169, 2433, 18, 225, 2073, 840, 6392, 4633, 711, 3271, 1375, 8949, 382, 68, 364, 4343, 381, 1368, 2845, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9563, 12521, 12, 3890, 745, 892, 501, 13, 1071, 3849, 2176, 1135, 261, 11890, 5034, 3844, 1182, 13, 288, 203, 3639, 261, 203, 5411, 1758, 1147, 382, 16, 203, 5411, 1758, 1147, 1182, 16, 203, 5411, 1758, 8027, 16, 203, 5411, 1426, 11014, 38, 29565, 16, 203, 5411, 2254, 5034, 3844, 382, 16, 203, 5411, 1731, 3778, 819, 203, 3639, 262, 273, 24126, 18, 3922, 12, 892, 16, 261, 2867, 16, 1758, 16, 1758, 16, 1426, 16, 2254, 5034, 16, 1731, 10019, 203, 203, 3639, 5059, 2502, 316, 2115, 273, 3853, 63, 2316, 382, 15533, 203, 3639, 5059, 2502, 596, 2115, 273, 3853, 63, 2316, 1182, 15533, 203, 203, 3639, 2583, 12, 8949, 382, 1648, 389, 16411, 12, 267, 2115, 18, 455, 6527, 16, 4552, 67, 706, 67, 54, 789, 4294, 3631, 315, 6694, 67, 706, 67, 54, 789, 4294, 8863, 203, 203, 3639, 3844, 1182, 273, 389, 588, 6275, 1182, 12, 8949, 382, 16, 316, 2115, 18, 455, 6527, 16, 316, 2115, 18, 4865, 16, 596, 2115, 18, 455, 6527, 16, 596, 2115, 18, 4865, 1769, 203, 203, 3639, 467, 1070, 6392, 3005, 11182, 12, 3576, 18, 15330, 2934, 313, 6392, 12521, 2428, 12, 2472, 1769, 203, 5411, 2583, 24899, 12296, 12, 2316, 382, 13, 1545, 3844, 382, 397, 316, 2115, 18, 455, 6527, 16, 315, 4400, 67, 27086, 20764, 8863, 203, 5411, 316, 2115, 18, 455, 6527, 1011, 2254, 22343, 12, 8949, 382, 1769, 203, 5411, 596, 2115, 18, 455, 6527, 3947, 2254, 22343, 12, 8949, 1182, 1769, 203, 3639, 2 ]
./partial_match/8453/0xc0d3C0D3C0D3c0D3C0D3C0d3C0D3c0D3c0d30015/sources/contracts/universal/CrossDomainMessenger.sol
* @custom:legacy @title CrossDomainMessengerLegacySpacer @notice Contract only exists to add a spacer to the CrossDomainMessenger where the libAddressManager variable used to exist. Must be the first contract in the inheritance tree of the CrossDomainMessenger/
contract CrossDomainMessengerLegacySpacer { address private spacer_0_0_20; import { SafeCall } from "../libraries/SafeCall.sol"; import { Hashing } from "../libraries/Hashing.sol"; import { Encoding } from "../libraries/Encoding.sol"; import { Constants } from "../libraries/Constants.sol"; }
16,772,527
[ 1, 36, 3662, 30, 17386, 225, 19742, 3748, 29329, 12235, 3389, 10598, 225, 13456, 1338, 1704, 358, 527, 279, 31896, 358, 326, 19742, 3748, 29329, 1625, 326, 540, 2561, 1887, 1318, 2190, 1399, 358, 1005, 18, 6753, 506, 326, 1122, 6835, 316, 326, 16334, 540, 2151, 434, 326, 19742, 3748, 29329, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19742, 3748, 29329, 12235, 3389, 10598, 288, 203, 565, 1758, 3238, 31896, 67, 20, 67, 20, 67, 3462, 31, 203, 5666, 288, 14060, 1477, 289, 628, 315, 6216, 31417, 19, 9890, 1477, 18, 18281, 14432, 203, 5666, 288, 2474, 310, 289, 628, 315, 6216, 31417, 19, 2310, 310, 18, 18281, 14432, 203, 5666, 288, 13400, 289, 628, 315, 6216, 31417, 19, 4705, 18, 18281, 14432, 203, 5666, 288, 5245, 289, 628, 315, 6216, 31417, 19, 2918, 18, 18281, 14432, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x5094a8f54B12AEc540bF7cCd0Dd7B62f4FecF7f2/sources/Users/Elena/Source/argent-contracts/contracts/modules/TransferManager.sol
* @inheritdoc IFeature/
function getStaticCallSignatures() external virtual override view returns (bytes4[] memory _sigs) { _sigs = new bytes4[](1); _sigs[0] = ERC1271_ISVALIDSIGNATURE_BYTES32; }
9,255,145
[ 1, 36, 10093, 467, 4595, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23414, 1477, 23918, 1435, 3903, 5024, 3849, 1476, 1135, 261, 3890, 24, 8526, 3778, 389, 7340, 87, 13, 288, 203, 3639, 389, 7340, 87, 273, 394, 1731, 24, 8526, 12, 21, 1769, 203, 3639, 389, 7340, 87, 63, 20, 65, 273, 4232, 39, 2138, 11212, 67, 5127, 5063, 26587, 67, 13718, 1578, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.13; import './interfaces/SyscoinClaimManagerI.sol'; import './interfaces/SyscoinSuperblocksI.sol'; import './SyscoinErrorCodes.sol'; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./SyscoinParser/SyscoinMessageLibrary.sol"; // @dev - Manages a battle session between superblock submitter and challenger contract SyscoinBattleManager is Initializable, SyscoinErrorCodes, SyscoinMessageLibrary { // For verifying Syscoin difficulty uint constant TARGET_TIMESPAN = 21600; uint constant TARGET_TIMESPAN_MIN = 17280; // TARGET_TIMESPAN * (8/10); uint constant TARGET_TIMESPAN_MAX = 27000; // TARGET_TIMESPAN * (10/8); uint constant TARGET_TIMESPAN_ADJUSTMENT = 360; // 6 hour uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; struct BattleSession { address submitter; address challenger; uint lastActionTimestamp; // Last action timestamp bytes32 prevSubmitBlockhash; bytes32[] merkleRoots; // interim merkle roots to recreate final root hash on last set of headers } // AuxPoW block fields struct AuxPoW { uint blockHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Syscoin block hash belongs to a tree with the above root uint syscoinHashIndex; // index of Syscoin block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Bitcoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Bitcoin tx tree uint parentNonce; uint pos; } // Syscoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 bits; bytes32 prevBlock; uint32 timestamp; bytes32 blockHash; } mapping (bytes32 => BattleSession) sessions; uint public superblockDuration; // Superblock duration (in blocks) uint public superblockTimeout; // Timeout action (in seconds) // network that the stored blocks belong to Network private net; // Syscoin claim manager SyscoinClaimManagerI trustedSyscoinClaimManager; // Superblocks contract SyscoinSuperblocksI trustedSuperblocks; event NewBattle(bytes32 superblockHash,address submitter, address challenger); event ChallengerConvicted(bytes32 superblockHash, uint err, address challenger); event SubmitterConvicted(bytes32 superblockHash, uint err, address submitter); event RespondBlockHeaders(bytes32 superblockHash, uint merkleHashCount, address submitter); modifier onlyFrom(address sender) { require(msg.sender == sender); _; } modifier onlyChallenger(bytes32 superblockHash) { require(msg.sender == sessions[superblockHash].challenger); _; } // @dev – Configures the contract managing superblocks battles // @param _network Network type to use for block difficulty validation // @param _superblocks Contract that manages superblocks // @param _superblockDuration Superblock duration (in blocks) // @param _superblockTimeout Time to wait for challenges (in seconds) function init( Network _network, SyscoinSuperblocksI _superblocks, uint _superblockDuration, uint _superblockTimeout ) external initializer { net = _network; trustedSuperblocks = _superblocks; superblockDuration = _superblockDuration; superblockTimeout = _superblockTimeout; } function setSyscoinClaimManager(SyscoinClaimManagerI _syscoinClaimManager) external { require(address(trustedSyscoinClaimManager) == address(0) && address(_syscoinClaimManager) != address(0)); trustedSyscoinClaimManager = _syscoinClaimManager; } // @dev - Start a battle session function beginBattleSession(bytes32 superblockHash, address submitter, address challenger) external onlyFrom(address(trustedSyscoinClaimManager)) { BattleSession storage session = sessions[superblockHash]; require(session.submitter == address(0)); session.submitter = submitter; session.challenger = challenger; session.merkleRoots.length = 0; session.lastActionTimestamp = block.timestamp; emit NewBattle(superblockHash, submitter, challenger); } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract previous block field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader, uint pos) private pure returns (uint) { uint hashPrevBlock; uint index = 0x04+pos; assembly { hashPrevBlock := mload(add(add(_blockHeader, 32), index)) } return flip32Bytes(hashPrevBlock); } // @dev - extract timestamp field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader, uint pos) private pure returns (uint32 time) { return bytesToUint32Flipped(_blockHeader, 0x44+pos); } // @dev - extract bits field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader, uint pos) private pure returns (uint32 bits) { return bytesToUint32Flipped(_blockHeader, 0x48+pos); } // @dev - converts raw bytes representation of a Syscoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) private view returns (BlockHeader memory bh) { bh.bits = getBits(_rawBytes, pos); bh.blockHash = bytes32(dblShaFlipMem(_rawBytes, pos, 80)); bh.timestamp = getTimestamp(_rawBytes, pos); bh.prevBlock = bytes32(getHashPrevBlock(_rawBytes, pos)); } function parseAuxPoW(bytes memory rawBytes, uint pos) private view returns (AuxPoW memory auxpow) { bytes memory coinbaseScript; uint slicePos; // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header (slicePos, coinbaseScript) = getSlicePos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; // parent block hash, skip and manually hash below pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.syscoinHashIndex = getBytesLE(rawBytes, pos, 32); pos += 4; // calculate block hash instead of reading it above, as some are LE and some are BE, we cannot know endianness and have to calculate from parent block header auxpow.blockHash = dblShaFlipMem(rawBytes, pos, 80); pos += 36; // skip parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); auxpow.pos = pos+4; uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(coinbaseScript); } function sha256mem(bytes memory _rawBytes, uint offset, uint len) public view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to ptr the next available memory position (stored in memory position 0x40). let ptr := mload(0x40) if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) { revert(0, 0) } result := mload(ptr) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) public view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } function skipOutputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_outputs; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePos(bytes memory txBytes, uint pos) private view returns (uint slicePos, bytes memory coinbaseScript) { (slicePos, coinbaseScript) = skipInputsCoinbase(txBytes, pos + 4); slicePos = skipOutputs(txBytes, slicePos); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[] memory, uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { assembly { slice := mload(add(data, add(0x20, start))) } } function skipInputsCoinbase(bytes memory txBytes, uint pos) private view returns (uint, bytes memory) { uint n_inputs; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); // if dummy 0x00 is present this is a witness transaction if(n_inputs == 0x00){ (n_inputs, pos) = parseVarInt(txBytes, pos); // flag require(n_inputs != 0x00); // after dummy/flag the real var int comes for txins (n_inputs, pos) = parseVarInt(txBytes, pos); } require(n_inputs == 1); pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); bytes memory coinbaseScript; coinbaseScript = sliceArray(txBytes, pos, pos+script_len); pos += script_len + 4; // skip sig_script, seq return (pos, coinbaseScript); } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; uint found = 0; uint target = 0xfabe6d6d00000000000000000000000000000000000000000000000000000000; uint mask = 0xffffffff00000000000000000000000000000000000000000000000000000000; assembly { let len := mload(rawBytes) let data := add(rawBytes, 0x20) let end := add(data, len) for { } lt(data, end) { } { // while(i < end) if eq(and(mload(data), mask), target) { if eq(found, 0x0) { position := add(sub(len, sub(end, data)), 4) } found := add(found, 1) } data := add(data, 0x1) } } if (found >= 2) { return (0, position - 4, ERR_FOUND_TWICE); } else if (found == 1) { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } else { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } } // @dev - calculates the Merkle root of a tree containing Bitcoin transactions // in order to prove that `ap`'s coinbase tx is in that Bitcoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Bitcoin block that the Syscoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) private pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Syscoin block identified by _blockHash // was merge-mined in a Bitcoin block. // // @param _blockHash - SHA-256 hash of a certain Syscoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) private pure returns (uint) { return computeMerkle(_blockHash, _ap.syscoinHashIndex, _ap.chainMerkleProof); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Syscoin block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) private pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) public pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDifficulty(uint _actualTimespan, uint32 _bits) private pure returns (uint32 result) { uint actualTimespan = _actualTimespan; // Limit adjustment step if (actualTimespan < TARGET_TIMESPAN_MIN) { actualTimespan = TARGET_TIMESPAN_MIN; } else if (actualTimespan > TARGET_TIMESPAN_MAX) { actualTimespan = TARGET_TIMESPAN_MAX; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * actualTimespan; bnNew = bnNew / TARGET_TIMESPAN; if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] memory hashes) public pure returns (bytes32) { uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0, "Must provide hashes"); uint i; for (i = 0; i < length; i++) { hashes[i] = bytes32(flip32Bytes(uint(hashes[i]))); } uint j; uint k; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = (i + 1 < length) ? i + 1 : length - 1; hashes[k] = sha256(abi.encodePacked(sha256(abi.encodePacked(hashes[i], hashes[j])))); k += 1; } length = k; } return bytes32(flip32Bytes(uint(hashes[0]))); } // @dev - Verify block headers sent by challenger function doRespondBlockHeaders( BattleSession storage session, SyscoinSuperblocksI.SuperblockInfo memory superblockInfo, bytes32 merkleRoot, BlockHeader memory lastHeader ) private returns (uint) { if (session.merkleRoots.length == 3 || net == Network.REGTEST) { bytes32[] memory merkleRoots = new bytes32[](net != Network.REGTEST ? 4 : 1); uint i; for (i = 0; i < session.merkleRoots.length; i++) { merkleRoots[i] = session.merkleRoots[i]; } merkleRoots[i] = merkleRoot; if (superblockInfo.blocksMerkleRoot != makeMerkle(merkleRoots)) { return ERR_SUPERBLOCK_INVALID_MERKLE; } // if you have the last set of headers we can enfoce checks against the end // ensure the last block's timestamp matches the superblock's proposed timestamp if (superblockInfo.timestamp != lastHeader.timestamp) { return ERR_SUPERBLOCK_INVALID_TIMESTAMP; } // ensure last headers hash matches the last hash of the superblock if (lastHeader.blockHash != superblockInfo.lastHash) { return ERR_SUPERBLOCK_HASH_SUPERBLOCK; } } else { session.merkleRoots.push(merkleRoot); } return ERR_SUPERBLOCK_OK; } function respondBlockHeaders ( bytes32 superblockHash, bytes memory blockHeaders, uint numHeaders ) public { BattleSession storage session = sessions[superblockHash]; address submitter = session.submitter; require(msg.sender == submitter); uint merkleRootsLen = session.merkleRoots.length; if (net != Network.REGTEST) { if ((merkleRootsLen <= 2 && numHeaders != 16) || (merkleRootsLen == 3 && numHeaders != 12)) { revert(); } } SyscoinSuperblocksI.SuperblockInfo memory superblockInfo; (superblockInfo.blocksMerkleRoot, superblockInfo.timestamp,superblockInfo.mtpTimestamp,superblockInfo.lastHash,superblockInfo.lastBits,superblockInfo.parentId,,,superblockInfo.height) = trustedSuperblocks.getSuperblock(superblockHash); uint pos = 0; bytes32[] memory blockHashes = new bytes32[](numHeaders); BlockHeader[] memory parsedBlockHeaders = new BlockHeader[](numHeaders); uint err = ERR_SUPERBLOCK_OK; for (uint i = 0; i < parsedBlockHeaders.length; i++){ parsedBlockHeaders[i] = parseHeaderBytes(blockHeaders, pos); uint target = targetFromBits(parsedBlockHeaders[i].bits); if (isMergeMined(blockHeaders, pos)) { AuxPoW memory ap = parseAuxPoW(blockHeaders, pos); if (ap.blockHash > target) { err = ERR_PROOF_OF_WORK_AUXPOW; break; } uint auxPoWCode = checkAuxPoW(uint(parsedBlockHeaders[i].blockHash), ap); if (auxPoWCode != 1) { err = auxPoWCode; break; } pos = ap.pos; } else { if (uint(parsedBlockHeaders[i].blockHash) > target) { err = ERR_PROOF_OF_WORK; break; } pos = pos+80; } blockHashes[i] = parsedBlockHeaders[i].blockHash; } if (err != ERR_SUPERBLOCK_OK) { convictSubmitter(superblockHash, submitter, session.challenger, err); return; } err = doRespondBlockHeaders( session, superblockInfo, makeMerkle(blockHashes), parsedBlockHeaders[parsedBlockHeaders.length-1] ); if (err != ERR_SUPERBLOCK_OK) { convictSubmitter(superblockHash, submitter, session.challenger, err); } else { session.lastActionTimestamp = block.timestamp; err = validateHeaders(session, superblockInfo, parsedBlockHeaders); if (err != ERR_SUPERBLOCK_OK) { convictSubmitter(superblockHash, submitter, session.challenger, err); return; } // only convict challenger at the end if all headers have been provided if(numHeaders == 12 || net == Network.REGTEST){ convictChallenger(superblockHash, submitter, session.challenger, err); return; } emit RespondBlockHeaders(superblockHash, merkleRootsLen + 1, submitter); } } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) private pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - Validate prev bits, prev hash of block header function checkBlocks(BattleSession storage session, BlockHeader[] memory blockHeadersParsed, uint32 prevBits) private view returns (uint) { for(uint i = blockHeadersParsed.length-1;i>0;i--){ BlockHeader memory thisHeader = blockHeadersParsed[i]; BlockHeader memory prevHeader = blockHeadersParsed[i-1]; // except for the last header except all the bits to match // last chunk has 12 headers which is the only time we care to skip the last header if (blockHeadersParsed.length != 12 || i < (blockHeadersParsed.length-1)){ if (prevBits != thisHeader.bits) return ERR_SUPERBLOCK_BITS_PREVBLOCK; } if(prevHeader.blockHash != thisHeader.prevBlock) return ERR_SUPERBLOCK_HASH_PREVBLOCK; } if (prevBits != blockHeadersParsed[0].bits) { return ERR_SUPERBLOCK_BITS_PREVBLOCK; } // enforce linking against previous submitted batch of blocks if (session.merkleRoots.length >= 2) { if (session.prevSubmitBlockhash != blockHeadersParsed[0].prevBlock) return ERR_SUPERBLOCK_HASH_INTERIM_PREVBLOCK; } return ERR_SUPERBLOCK_OK; } function sort_array(uint[11] memory arr) private pure { for(uint i = 0; i < 11; i++) { for(uint j = i+1; j < 11 ;j++) { if(arr[i] > arr[j]) { uint temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } // @dev - Gets the median timestamp of the last 11 blocks function getMedianTimestamp(BlockHeader[] memory blockHeadersParsed) private pure returns (uint){ uint[11] memory timestamps; // timestamps 0->10 = blockHeadersParsed 1->11 for(uint i=0;i<11;i++){ timestamps[i] = blockHeadersParsed[i+1].timestamp; } sort_array(timestamps); return timestamps[5]; } // @dev - Validate superblock accumulated work + other block header fields function validateHeaders(BattleSession storage session, SyscoinSuperblocksI.SuperblockInfo memory superblockInfo, BlockHeader[] memory blockHeadersParsed) private returns (uint) { SyscoinSuperblocksI.SuperblockInfo memory prevSuperblockInfo; BlockHeader memory lastHeader = blockHeadersParsed[blockHeadersParsed.length-1]; (,,prevSuperblockInfo.mtpTimestamp,prevSuperblockInfo.lastHash,prevSuperblockInfo.lastBits,,,,) = trustedSuperblocks.getSuperblock(superblockInfo.parentId); // for blocks 0 -> 16 we can check the first header if(session.merkleRoots.length <= 1){ // ensure first headers prev block matches the last hash of the prev superblock if(blockHeadersParsed[0].prevBlock != prevSuperblockInfo.lastHash) return ERR_SUPERBLOCK_HASH_PREVSUPERBLOCK; } // make sure all bits are the same and timestamps are within range as well as headers are all linked uint err = checkBlocks(session, blockHeadersParsed, prevSuperblockInfo.lastBits); if(err != ERR_SUPERBLOCK_OK) return err; // for every batch of blocks up to the last one (at superblockDuration blocks we have all the headers so we can complete the game) if(blockHeadersParsed.length != 12){ // set the last block header details in the session for subsequent batch of blocks to validate it connects to this header session.prevSubmitBlockhash = lastHeader.blockHash; } // once all the headers are received we can check merkle and enforce difficulty else{ uint mtpTimestamp = getMedianTimestamp(blockHeadersParsed); // make sure calculated MTP is same as superblock MTP if(mtpTimestamp != superblockInfo.mtpTimestamp) return ERR_SUPERBLOCK_MISMATCH_TIMESTAMP_MTP; // ensure MTP of this SB is > than last SB MTP if(mtpTimestamp <= prevSuperblockInfo.mtpTimestamp) return ERR_SUPERBLOCK_TOOSMALL_TIMESTAMP_MTP; // make sure every 6th superblock adjusts difficulty // calculate the new work from prevBits minus one as if its an adjustment we need to account for new bits, if not then just add one more prevBits work if (net != Network.REGTEST) { if (((superblockInfo.height-1) % 6) == 0) { BlockHeader memory prevToLastHeader = blockHeadersParsed[blockHeadersParsed.length-2]; // ie: superblockHeight = 7 meaning blocks 661->720, we need to check timestamp from block 719 - to block 360 // get 6 superblocks previous for second timestamp (for example block 360 has the timetamp 6 superblocks ago on second adjustment) superblockInfo.timestamp = trustedSuperblocks.getSuperblockTimestamp(trustedSuperblocks.getSuperblockAt(superblockInfo.height - 6)); uint32 newBits = calculateDifficulty(prevToLastHeader.timestamp - superblockInfo.timestamp, prevSuperblockInfo.lastBits); // ensure bits of superblock match derived bits from calculateDifficulty if (superblockInfo.lastBits != newBits) { return ERR_SUPERBLOCK_BITS_SUPERBLOCK; } } else { if (superblockInfo.lastBits != prevSuperblockInfo.lastBits) { return ERR_SUPERBLOCK_BITS_LASTBLOCK; } } // make sure superblock bits match that of the last block if (superblockInfo.lastBits != lastHeader.bits) return ERR_SUPERBLOCK_BITS_LASTBLOCK; } } return ERR_SUPERBLOCK_OK; } // @dev - Trigger conviction if response is not received in time function timeout(bytes32 superblockHash) external returns (uint) { BattleSession storage session = sessions[superblockHash]; require(session.submitter != address(0)); if (block.timestamp > session.lastActionTimestamp + superblockTimeout) { convictSubmitter(superblockHash, session.submitter, session.challenger, ERR_SUPERBLOCK_TIMEOUT); trustedSyscoinClaimManager.checkClaimFinished(superblockHash); return ERR_SUPERBLOCK_TIMEOUT; } return ERR_SUPERBLOCK_NO_TIMEOUT; } // @dev - To be called when a challenger is convicted function convictChallenger(bytes32 superblockHash, address submitter, address challenger, uint err) private { trustedSyscoinClaimManager.sessionDecided(superblockHash, submitter, challenger); emit ChallengerConvicted(superblockHash, err, challenger); disable(superblockHash); } // @dev - To be called when a submitter is convicted function convictSubmitter(bytes32 superblockHash, address submitter, address challenger, uint err) private { trustedSyscoinClaimManager.sessionDecided(superblockHash, challenger, submitter); emit SubmitterConvicted(superblockHash, err, submitter); disable(superblockHash); } // @dev - Disable session // It should be called only when either the submitter or the challenger were convicted. function disable(bytes32 superblockHash) private { delete sessions[superblockHash]; } // @dev - Check if a session's submitter did not respond before timeout function getSubmitterHitTimeout(bytes32 superblockHash) external view returns (bool) { BattleSession storage session = sessions[superblockHash]; return (block.timestamp > session.lastActionTimestamp + superblockTimeout); } function getNumMerkleHashesBySession(bytes32 superblockHash) external view returns (uint) { BattleSession memory session = sessions[superblockHash]; if (session.submitter == address(0)) return 0; return sessions[superblockHash].merkleRoots.length; } function sessionExists(bytes32 superblockHash) external view returns (bool) { return sessions[superblockHash].submitter != address(0); } }
if dummy 0x00 is present this is a witness transaction after dummy/flag the real var int comes for txins
function skipInputsCoinbase(bytes memory txBytes, uint pos) private view returns (uint, bytes memory) { uint n_inputs; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); if(n_inputs == 0x00){ require(n_inputs != 0x00); (n_inputs, pos) = parseVarInt(txBytes, pos); } require(n_inputs == 1); (script_len, pos) = parseVarInt(txBytes, pos); bytes memory coinbaseScript; coinbaseScript = sliceArray(txBytes, pos, pos+script_len); return (pos, coinbaseScript); }
14,105,756
[ 1, 430, 9609, 374, 92, 713, 353, 3430, 333, 353, 279, 15628, 2492, 1839, 9609, 19, 6420, 326, 2863, 569, 509, 14535, 364, 2229, 2679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2488, 10059, 27055, 1969, 12, 3890, 3778, 2229, 2160, 16, 2254, 949, 13, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 16, 1731, 3778, 13, 203, 565, 288, 203, 3639, 2254, 290, 67, 10029, 31, 203, 3639, 2254, 2728, 67, 1897, 31, 203, 3639, 261, 82, 67, 10029, 16, 949, 13, 273, 1109, 1537, 1702, 12, 978, 2160, 16, 949, 1769, 203, 3639, 309, 12, 82, 67, 10029, 422, 374, 92, 713, 15329, 203, 5411, 2583, 12, 82, 67, 10029, 480, 374, 92, 713, 1769, 203, 5411, 261, 82, 67, 10029, 16, 949, 13, 273, 1109, 1537, 1702, 12, 978, 2160, 16, 949, 1769, 203, 3639, 289, 203, 3639, 2583, 12, 82, 67, 10029, 422, 404, 1769, 203, 203, 3639, 261, 4263, 67, 1897, 16, 949, 13, 273, 1109, 1537, 1702, 12, 978, 2160, 16, 949, 1769, 203, 3639, 1731, 3778, 31338, 3651, 31, 203, 3639, 31338, 3651, 273, 2788, 1076, 12, 978, 2160, 16, 949, 16, 949, 15, 4263, 67, 1897, 1769, 203, 203, 3639, 327, 261, 917, 16, 31338, 3651, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]