file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./partial_match/1/0x1201FAa7258A48b820619dD57Cd8FdEb25D49b2c/sources/contracts/WeightedMath.sol
* @dev Intermediate function to avoid stack-too-deep errors./ Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to 'token out'. This results in slightly larger price impact. If a token's amount out is not being charged a swap fee then it might be zero (e.g. when exiting a Pool with only a subset of tokens). In this case, `balanceRatio` will equal `FixedPoint.ONE`, and the `invariantRatio` will not change at all. We therefore skip to the next iteration, avoiding the costly `powDown` call.
function _computeExitExactTokensOutInvariantRatio( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256[] memory balanceRatiosWithoutFee, uint256 invariantRatioWithoutFees, uint256 swapFeePercentage ) private pure returns (uint256 invariantRatio) { invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); uint256 taxableAmountPlusFees = taxableAmount.divUp(swapFeePercentage.complement()); amountOutWithFee = nonTaxableAmount.add(taxableAmountPlusFees); amountOutWithFee = amountsOut[i]; if (amountOutWithFee == 0) { continue; } } uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } }
4,227,772
[ 1, 2465, 6785, 445, 358, 4543, 2110, 17, 16431, 17, 16589, 1334, 18, 19, 12738, 1656, 281, 854, 14755, 1149, 2423, 603, 296, 2316, 316, 2187, 1496, 1915, 353, 1158, 296, 2316, 316, 11, 2674, 16, 1427, 732, 2230, 518, 358, 296, 2316, 596, 10332, 1220, 1686, 316, 21980, 10974, 6205, 15800, 18, 971, 279, 1147, 1807, 3844, 596, 353, 486, 3832, 1149, 2423, 279, 7720, 14036, 1508, 518, 4825, 506, 3634, 261, 73, 18, 75, 18, 1347, 15702, 279, 8828, 598, 1338, 279, 7931, 434, 2430, 2934, 657, 333, 648, 16, 1375, 12296, 8541, 68, 903, 3959, 1375, 7505, 2148, 18, 5998, 9191, 471, 326, 1375, 267, 8688, 8541, 68, 903, 486, 2549, 622, 777, 18, 1660, 13526, 2488, 358, 326, 1024, 6532, 16, 4543, 310, 326, 6991, 715, 1375, 23509, 4164, 68, 745, 18, 2, 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, 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 ]
[ 1, 565, 445, 389, 9200, 6767, 14332, 5157, 1182, 382, 8688, 8541, 12, 203, 3639, 2254, 5034, 8526, 3778, 324, 26488, 16, 203, 3639, 2254, 5034, 8526, 3778, 5640, 16595, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 1182, 16, 203, 3639, 2254, 5034, 8526, 3778, 11013, 29635, 7441, 8073, 14667, 16, 203, 3639, 2254, 5034, 22514, 8541, 8073, 2954, 281, 16, 203, 3639, 2254, 5034, 7720, 14667, 16397, 203, 565, 262, 3238, 16618, 1135, 261, 11890, 5034, 22514, 8541, 13, 288, 203, 3639, 22514, 8541, 273, 15038, 2148, 18, 5998, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 324, 26488, 18, 2469, 31, 277, 27245, 288, 203, 203, 5411, 2254, 5034, 3844, 1182, 1190, 14667, 31, 203, 5411, 309, 261, 267, 8688, 8541, 8073, 2954, 281, 405, 11013, 29635, 7441, 8073, 14667, 63, 77, 5717, 288, 203, 7734, 2254, 5034, 1661, 7731, 429, 6275, 273, 324, 26488, 63, 77, 8009, 16411, 4164, 12, 267, 8688, 8541, 8073, 2954, 281, 18, 2919, 806, 10663, 203, 7734, 2254, 5034, 5320, 429, 6275, 273, 30980, 1182, 63, 77, 8009, 1717, 12, 5836, 7731, 429, 6275, 1769, 203, 7734, 2254, 5034, 5320, 429, 6275, 13207, 2954, 281, 273, 5320, 429, 6275, 18, 2892, 1211, 12, 22270, 14667, 16397, 18, 2919, 806, 10663, 203, 203, 7734, 3844, 1182, 1190, 14667, 273, 1661, 7731, 429, 6275, 18, 1289, 12, 8066, 429, 6275, 13207, 2954, 281, 1769, 203, 7734, 3844, 1182, 1190, 14667, 273, 30980, 1182, 63, 77, 15533, 203, 7734, 309, 261, 8949, 1182, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-25 */ pragma solidity 0.8.7; // SPDX-License-Identifier: Unlicensed pragma abicoder v2; interface IERC20 { 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); } abstract contract Context { function _msgSender() internal view virtual returns (address) { 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; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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 EliteBridge is Ownable { struct userDetails { uint amount; address token; uint lastTransaction; } // ECDSA Address using ECDSA for address; address public signer; bool public lockStatus; event SetSigner(address indexed user,address indexed signer); event Deposit(address indexed user,uint amount,address indexed token,uint time); event Claim(address indexed user,address indexed token,uint amount,uint time); event Fallback(address indexed user,uint amount,uint time); event Failsafe(address indexed user, address indexed tokenAddress,uint amount); mapping(bytes32 => bool)public msgHash; mapping(address => mapping(address => userDetails))public UserInfo; mapping (address => bool) public isApproved; constructor (address _signer) { signer = _signer; } /** * @dev Throws if lockStatus is true */ modifier isLock() { require(lockStatus == false, "Elite: Contract Locked"); _; } modifier isApprove(address _token){ require(isApproved[_token],"Un approve token"); _; } /** * @dev Throws if called by other contract */ modifier isContractCheck(address _user) { require(!isContract(_user), "Elite: Invalid address"); _; } function addToken(address _tokenAddress,uint _amount) public onlyOwner { require(_amount > 0,"Invalid amount"); IERC20(_tokenAddress).transferFrom(msg.sender,address(this),_amount); } receive()external payable { emit Fallback(msg.sender,msg.value,block.timestamp); } function approveTokenToDeposit(address _tokenAddress, bool _approveStatus) external onlyOwner { isApproved[_tokenAddress] = _approveStatus; } function deposit(address _tokenAddress, uint _amount)public isLock isApprove(_tokenAddress){ require (_amount > 0,"Incorrect params"); userDetails storage users = UserInfo[msg.sender][_tokenAddress]; IERC20(_tokenAddress).transferFrom(msg.sender,address(this),_amount); users.token = _tokenAddress; users.amount = _amount; users.lastTransaction = block.timestamp; emit Deposit(msg.sender,_amount,_tokenAddress,block.timestamp); } function claim(address _user,address _tokenAddress,uint amount, bytes calldata signature,uint _time) public isLock isApprove(_tokenAddress) { //messageHash can be used only once require(_time > block.timestamp,"signature Expiry"); bytes32 messageHash = message(_user, _tokenAddress,amount,_time); require(!msgHash[messageHash], "claim: signature duplicate"); //Verifes signature address src = verifySignature(messageHash, signature); require(signer == src, " claim: unauthorized"); IERC20(_tokenAddress).transfer(_user,amount); msgHash[messageHash] = true; emit Claim(_user,_tokenAddress,amount,block.timestamp); } /** * @dev ETHereum Signed Message, created from `hash` * @dev Returns the address that signed a hashed message (`hash`) with `signature`. */ function verifySignature(bytes32 _messageHash, bytes memory _signature) public pure returns (address signatureAddress) { bytes32 hash = ECDSA.toETHSignedMessageHash(_messageHash); signatureAddress = ECDSA.recover(hash, _signature); } /** * @dev Returns hash for given data */ function message(address _receiver, address _tokenAdderss ,uint amount,uint time) public pure returns(bytes32 messageHash) { messageHash = keccak256(abi.encodePacked(_receiver, _tokenAdderss,amount,time)); } // updaate signer address function setSigner(address _signer)public onlyOwner{ signer = _signer; emit SetSigner(msg.sender, _signer); } function failsafe(address user,address tokenAddress,uint amount)public onlyOwner{ if(tokenAddress == address(0x0)){ payable(user).transfer(amount); }else { IERC20(tokenAddress).transfer(user,amount); } emit Failsafe(user, tokenAddress,amount); } function checkBalance()public view returns(uint){ return address(this).balance; } /** * @dev contractLock: For contract status */ function contractLock(bool _lockStatus) public onlyOwner returns(bool) { lockStatus = _lockStatus; return true; } /** * @dev isContract: Returns true if account is a contract */ function isContract(address _account) public view returns(bool) { uint32 size; assembly { size:= extcodesize(_account) } if (size != 0) return true; return false; } }
messageHash can be used only onceVerifes signature
function claim(address _user,address _tokenAddress,uint amount, bytes calldata signature,uint _time) public isLock isApprove(_tokenAddress) { require(_time > block.timestamp,"signature Expiry"); bytes32 messageHash = message(_user, _tokenAddress,amount,_time); require(!msgHash[messageHash], "claim: signature duplicate"); address src = verifySignature(messageHash, signature); require(signer == src, " claim: unauthorized"); IERC20(_tokenAddress).transfer(_user,amount); msgHash[messageHash] = true; emit Claim(_user,_tokenAddress,amount,block.timestamp); }
7,775,921
[ 1, 2150, 2310, 848, 506, 1399, 1338, 3647, 3945, 430, 281, 3372, 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, 12, 2867, 389, 1355, 16, 2867, 389, 2316, 1887, 16, 11890, 3844, 16, 1731, 745, 892, 3372, 16, 11890, 389, 957, 13, 1071, 353, 2531, 353, 12053, 537, 24899, 2316, 1887, 13, 288, 203, 540, 203, 3639, 2583, 24899, 957, 405, 1203, 18, 5508, 10837, 8195, 31462, 8863, 203, 3639, 1731, 1578, 883, 2310, 273, 883, 24899, 1355, 16, 389, 2316, 1887, 16, 8949, 16, 67, 957, 1769, 203, 3639, 2583, 12, 5, 3576, 2310, 63, 2150, 2310, 6487, 315, 14784, 30, 3372, 6751, 8863, 203, 540, 203, 3639, 1758, 1705, 273, 3929, 5374, 12, 2150, 2310, 16, 3372, 1769, 203, 3639, 2583, 12, 2977, 264, 422, 1705, 16, 315, 7516, 30, 640, 8434, 8863, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 1887, 2934, 13866, 24899, 1355, 16, 8949, 1769, 203, 3639, 1234, 2310, 63, 2150, 2310, 65, 273, 638, 31, 203, 3639, 3626, 18381, 24899, 1355, 16, 67, 2316, 1887, 16, 8949, 16, 2629, 18, 5508, 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 ]
./full_match/5/0x59c472eE8d4Ef483f145280D1Bac31CAcd23AD74/sources/contracts/Volswap.sol
Convert to 18 decimal places
uint256 amountToBuy = (inputValue / ethValue) * 10 ** 18;
1,879,661
[ 1, 2723, 358, 6549, 6970, 12576, 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, 3639, 2254, 5034, 3844, 774, 38, 9835, 273, 261, 2630, 620, 342, 13750, 620, 13, 380, 1728, 2826, 6549, 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 ]
./full_match/80001/0xAc4353277e7a7382DBA96eab9c6Aeb84F5dd246e/sources/contracts/ERC721WithPermit.sol
* @dev Emitted when `buyer` purchase a single block in an artwork/
event PurchaseBlock(address indexed seller, address indexed buyer, uint256 indexed tokenId, string tokenUri);
856,086
[ 1, 1514, 11541, 1347, 1375, 70, 16213, 68, 23701, 279, 2202, 1203, 316, 392, 3688, 1252, 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 ]
[ 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, 225, 871, 26552, 1768, 12, 2867, 8808, 29804, 16, 1758, 8808, 27037, 16, 2254, 5034, 8808, 1147, 548, 16, 533, 1147, 3006, 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 ]
pragma solidity ^0.5.0; contract CryptoTycoonsVIPLib{ address payable public owner; // Accumulated jackpot fund. uint128 public jackpotSize; uint128 public rankingRewardSize; mapping (address => uint) userExpPool; mapping (address => bool) public callerMap; event RankingRewardPayment(address indexed beneficiary, uint amount); modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } modifier onlyCaller { bool isCaller = callerMap[msg.sender]; require(isCaller, "onlyCaller methods called by non-caller."); _; } constructor() public{ owner = msg.sender; callerMap[owner] = true; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () external payable { } function kill() external onlyOwner { selfdestruct(owner); } function addCaller(address caller) public onlyOwner{ bool isCaller = callerMap[caller]; if (isCaller == false){ callerMap[caller] = true; } } function deleteCaller(address caller) external onlyOwner { bool isCaller = callerMap[caller]; if (isCaller == true) { callerMap[caller] = false; } } function addUserExp(address addr, uint256 amount) public onlyCaller{ uint exp = userExpPool[addr]; exp = exp + amount; userExpPool[addr] = exp; } function getUserExp(address addr) public view returns(uint256 exp){ return userExpPool[addr]; } function getVIPLevel(address user) public view returns (uint256 level) { uint exp = userExpPool[user]; if(exp >= 25 ether && exp < 125 ether){ level = 1; } else if(exp >= 125 ether && exp < 250 ether){ level = 2; } else if(exp >= 250 ether && exp < 1250 ether){ level = 3; } else if(exp >= 1250 ether && exp < 2500 ether){ level = 4; } else if(exp >= 2500 ether && exp < 12500 ether){ level = 5; } else if(exp >= 12500 ether && exp < 25000 ether){ level = 6; } else if(exp >= 25000 ether && exp < 125000 ether){ level = 7; } else if(exp >= 125000 ether && exp < 250000 ether){ level = 8; } else if(exp >= 250000 ether && exp < 1250000 ether){ level = 9; } else if(exp >= 1250000 ether){ level = 10; } else{ level = 0; } return level; } function getVIPBounusRate(address user) public view returns (uint256 rate){ uint level = getVIPLevel(user); return level; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyCaller { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } function payJackpotReward(address payable to) external onlyCaller{ to.transfer(jackpotSize); jackpotSize = 0; } function getJackpotSize() external view returns (uint256){ return jackpotSize; } function increaseRankingReward(uint amount) public onlyCaller{ require (amount <= address(this).balance, "Increase amount larger than balance."); require (rankingRewardSize + amount <= address(this).balance, "Not enough funds."); rankingRewardSize += uint128(amount); } function payRankingReward(address payable to) external onlyCaller { uint128 prize = rankingRewardSize / 2; rankingRewardSize = rankingRewardSize - prize; if(to.send(prize)){ emit RankingRewardPayment(to, prize); } } function getRankingRewardSize() external view returns (uint128){ return rankingRewardSize; } } contract CryptoTycoonsConstants{ /// *** Constants section // Each bet is deducted 1% in favour of the house, but no less than some minimum. // The lower bound is dictated by gas costs of the settleBet transaction, providing // headroom for up to 10 Gwei prices. uint constant HOUSE_EDGE_PERCENT = 1; uint constant RANK_FUNDS_PERCENT = 7; uint constant INVITER_BENEFIT_PERCENT = 7; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether; // Bets lower than this amount do not participate in jackpot rolls (and are // not deducted JACKPOT_FEE). uint constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 10 ether; // Standard contract ownership transfer. address payable public owner; address payable private nextOwner; // Croupier account. mapping (address => bool ) croupierMap; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit; address payable public VIPLibraryAddress; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event VIPPayback(address indexed beneficiary, uint amount); event WithdrawFunds(address indexed beneficiary, uint amount); constructor (uint _maxProfit) public { owner = msg.sender; secretSigner = owner; maxProfit = _maxProfit; croupierMap[owner] = true; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { bool isCroupier = croupierMap[msg.sender]; require(isCroupier, "OnlyCroupier methods called by non-croupier."); _; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () external payable { } // Standard contract ownership transfer implementation, function approveNextOwner(address payable _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } function getSecretSigner() external onlyOwner view returns(address){ return secretSigner; } function addCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == false) { croupierMap[newCroupier] = true; } } function deleteCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == true) { croupierMap[newCroupier] = false; } } function setVIPLibraryAddress(address payable addr) external onlyOwner{ VIPLibraryAddress = addr; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // Funds withdrawal to cover costs of AceDice operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); if (beneficiary.send(withdrawAmount)){ emit WithdrawFunds(beneficiary, withdrawAmount); } } function kill() external onlyOwner { // require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function thisBalance() public view returns(uint) { return address(this).balance; } function payTodayReward(address payable to) external onlyOwner { CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); vipLib.payRankingReward(to); } function getRankingRewardSize() external view returns (uint128) { CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); return vipLib.getRankingRewardSize(); } function handleVIPPaybackAndExp(CryptoTycoonsVIPLib vipLib, address payable gambler, uint amount) internal returns(uint vipPayback) { // CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); vipLib.addUserExp(gambler, amount); uint rate = vipLib.getVIPBounusRate(gambler); if (rate <= 0) return 0; vipPayback = amount * rate / 10000; if(vipPayback > 0){ emit VIPPayback(gambler, vipPayback); } } function increaseRankingFund(CryptoTycoonsVIPLib vipLib, uint amount) internal{ uint rankingFunds = uint128(amount * HOUSE_EDGE_PERCENT / 100 * RANK_FUNDS_PERCENT /100); // uint128 rankingRewardFee = uint128(amount * HOUSE_EDGE_PERCENT / 100 * 9 /100); VIPLibraryAddress.transfer(rankingFunds); vipLib.increaseRankingReward(rankingFunds); } function getMyAccuAmount() external view returns (uint){ CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); return vipLib.getUserExp(msg.sender); } function getJackpotSize() external view returns (uint){ CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); return vipLib.getJackpotSize(); } function verifyCommit(uint commit, uint8 v, bytes32 r, bytes32 s) internal view { // Check that commit is valid - it has not expired and its signature is valid. // require (block.number <= commitLastBlock, "Commit has expired."); //bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes memory message = abi.encodePacked(commit); bytes32 messageHash = keccak256(abi.encodePacked(prefix, keccak256(message))); require (secretSigner == ecrecover(messageHash, v, r, s), "ECDSA signature is not valid."); } function calcHouseEdge(uint amount) public pure returns (uint houseEdge) { // 0.02 houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } } function calcJackpotFee(uint amount) internal pure returns (uint jackpotFee) { // 0.001 if (amount >= MIN_JACKPOT_BET) { jackpotFee = JACKPOT_FEE; } } function calcRankFundsFee(uint amount) internal pure returns (uint rankFundsFee) { // 0.01 * 0.07 rankFundsFee = amount * RANK_FUNDS_PERCENT / 10000; } function calcInviterBenefit(uint amount) internal pure returns (uint invitationFee) { // 0.01 * 0.07 invitationFee = amount * INVITER_BENEFIT_PERCENT / 10000; } function processBet( uint betMask, uint reveal, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable; } contract CardRPS is CryptoTycoonsConstants(10 ether) { event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount, uint playerNum1, uint playerNum2, uint npcNum1, uint npcNum2, uint betAmount, uint rouletteIndex); event JackpotPayment(address indexed beneficiary, uint amount, uint playerNum1, uint playerNum2, uint npcNum1, uint npcNum2, uint betAmount); struct RandomNumber{ uint8 playerNum1; uint8 playerNum2; uint8 npcNum1; uint8 npcNum2; uint8 rouletteIndex; } function processBet( uint betMask, uint reveal, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable { address payable gambler = msg.sender; // Validate input data ranges. uint amount = msg.value; // require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); if (inviter != address(0)){ require(gambler != inviter, "cannot invite myself"); } uint commit = uint(keccak256(abi.encodePacked(reveal))); verifyCommit(commit, v, r, s); bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(block.number))); processReward(gambler, amount, entropy, inviter); } function processReward( address payable gambler, uint amount, bytes32 entropy, address payable inviter) internal{ CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); // 1. increate vip exp uint _vipPayback = handleVIPPaybackAndExp(vipLib, msg.sender, amount); // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). uint seed = uint(entropy); // Do a roll by taking a modulo of entropy. Compute winning amount. RandomNumber memory randomNumber = RandomNumber(0, 0, 0, 0, 0); // uint mask = 2 ** 8; randomNumber.playerNum1 = uint8(seed % 3); seed = seed / 2 ** 8; randomNumber.playerNum2 = uint8(seed % 3); seed = seed / 2 ** 8; randomNumber.npcNum1 = uint8(seed % 3); seed = seed / 2 ** 8; randomNumber.npcNum2 = uint8(seed % 3); seed = seed / 2 ** 8; randomNumber.rouletteIndex = uint8(seed % 12); seed = seed / 2 ** 8; uint jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } handleJackpotReward(vipLib, randomNumber, entropy, gambler, jackpotFee, amount); if(inviter != address(0)){ // pay 10% of house edge to inviter inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 7 /100); } payBettingReward(gambler, randomNumber, amount, houseEdge, jackpotFee, _vipPayback); increaseRankingFund(vipLib, amount); } function handleJackpotReward( CryptoTycoonsVIPLib vipLib, RandomNumber memory randomNumber, bytes32 entropy, address payable gambler, uint jackpotFee, uint amount) private { uint jackpotWin = 0; // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { VIPLibraryAddress.transfer(jackpotFee); vipLib.increaseJackpot(jackpotFee); // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! // uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if ((uint(entropy) / 100) % JACKPOT_MODULO == 0) { jackpotWin = vipLib.getJackpotSize(); vipLib.payJackpotReward(gambler); } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin, randomNumber.playerNum1, randomNumber.playerNum2, randomNumber.npcNum1, randomNumber.npcNum2, amount); } } function payBettingReward( address payable gambler, RandomNumber memory randomNumber, uint amount, uint houseEdge, uint jackpotFee, uint vipPayback) private { uint8 winValue = calculateWinValue(randomNumber); // 0 -> draw, 1 -> user win, 2 -> npc win uint winAmount = 0; if (winValue == 0) { // draw winAmount = amount - houseEdge - jackpotFee; } else if (winValue == 1) { // user win winAmount = (amount - houseEdge - jackpotFee) * getRouletteRate(randomNumber.rouletteIndex) / 10; } else { } winAmount += vipPayback; if(winAmount > 0){ if (gambler.send(winAmount)) { emit Payment(gambler, winAmount, randomNumber.playerNum1, randomNumber.playerNum2, randomNumber.npcNum1, randomNumber.npcNum2, amount, randomNumber.rouletteIndex); } else { emit FailedPayment(gambler, amount); } }else{ emit Payment(gambler, winAmount, randomNumber.playerNum1, randomNumber.playerNum2, randomNumber.npcNum1, randomNumber.npcNum2, amount, randomNumber.rouletteIndex); } // Send the funds to gambler. // sendFunds(gambler, winAmount == 0 ? 1 wei : winAmount, winAmount, // randomNumber.playerNum1, // randomNumber.playerNum2, // randomNumber.npcNum1, // randomNumber.npcNum2, // amount, // randomNumber.rouletteIndex); } function calculateWinValue(RandomNumber memory randomNumber) private pure returns (uint8){ uint8 playerNum1 = randomNumber.playerNum1; uint8 playerNum2 = randomNumber.playerNum2; uint8 npcNum1 = randomNumber.npcNum1; uint8 npcNum2 = randomNumber.npcNum2; uint8 winValue = 0; if (playerNum1 == npcNum1){ // num 0 -> scissors, 1 -> rock, 2 -> papper if (playerNum2 == npcNum2){ winValue = 0; } else if(playerNum2 == 0 && npcNum2 == 2){ winValue = 1; // user win } else if(playerNum2 == 1 && npcNum2 == 0){ winValue = 1; // user win } else if(playerNum2 == 2 && npcNum2 == 1){ winValue = 1; // user win } else{ winValue = 2; // npc win } } else if(playerNum1 == 0 && npcNum1 == 2){ winValue = 1; // user win } else if(playerNum1 == 1 && npcNum1 == 0){ winValue = 1; // user win } else if(playerNum1 == 2 && npcNum1 == 1){ winValue = 1; // user win } else{ winValue = 2; // npc win } return winValue; } function getRouletteRate(uint index) private pure returns (uint8){ uint8 rate = 11; if (index == 0){ rate = 50; } else if(index== 1){ rate = 11; } else if(index== 2){ rate = 20; } else if(index== 3){ rate = 15; } else if(index== 4){ rate = 20; } else if(index== 5){ rate = 11; } else if(index== 6){ rate = 20; } else if(index== 7){ rate = 15; } else if(index== 8){ rate = 20; } else if(index== 9){ rate = 11; } else if(index== 10){ rate = 20; } else if(index== 11){ rate = 15; } return rate; } }
Funds withdrawal to cover costs of AceDice operation.
function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); if (beneficiary.send(withdrawAmount)){ emit WithdrawFunds(beneficiary, withdrawAmount); } }
1,755,177
[ 1, 42, 19156, 598, 9446, 287, 358, 5590, 22793, 434, 432, 311, 40, 1812, 1674, 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, 598, 9446, 42, 19156, 12, 2867, 8843, 429, 27641, 74, 14463, 814, 16, 2254, 598, 9446, 6275, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 261, 1918, 9446, 6275, 1648, 1758, 12, 2211, 2934, 12296, 16, 315, 382, 11908, 3844, 10974, 2353, 11013, 1199, 1769, 203, 3639, 309, 261, 70, 4009, 74, 14463, 814, 18, 4661, 12, 1918, 9446, 6275, 3719, 95, 203, 5411, 3626, 3423, 9446, 42, 19156, 12, 70, 4009, 74, 14463, 814, 16, 598, 9446, 6275, 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 ]
./full_match/1/0xC1b7ad370496863A561C6A6b76abAD6e596d558A/sources/UniMeV.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract UniMeV is ERC20, Ownable { uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; IDexRouter public dexRouter; address public lpPair; bool private swapping; uint256 public swapTokensAtAmount; address operationsAddress; mapping (address => bool) public bot; uint256 public botsCaught; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyOperationsFee; uint256 public buyLiquidityFee; uint256 public sellTotalFees; uint256 public sellOperationsFee; uint256 public sellLiquidityFee; uint256 public tokensForOperations; uint256 public tokensForLiquidity; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event EnabledTrading(); event RemovedLimits(); event ExcludeFromFees(address indexed account, bool isExcluded); event UpdatedMaxBuyAmount(uint256 newAmount); event UpdatedMaxSellAmount(uint256 newAmount); event UpdatedMaxWalletAmount(uint256 newAmount); event UpdatedOperationsAddress(address indexed newWallet); event MaxTransactionExclusion(address _address, bool excluded); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); event CaughtEarlyBuyer(address sniper); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event TransferForeignToken(address token, uint256 amount); constructor() ERC20(unicode"UniMeV", unicode"UMEV") { IDexRouter _dexRouter = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); dexRouter = _dexRouter; lpPair = IDexFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH()); _excludeFromMaxTransaction(address(lpPair), true); _setAutomatedMarketMakerPair(address(lpPair), true); uint256 totalSupply = 1 * 1e9 * 1e18; maxBuyAmount = totalSupply * 15 / 1000; maxSellAmount = totalSupply * 15 / 1000; maxWalletAmount = totalSupply * 15 / 1000; swapTokensAtAmount = totalSupply * 1 / 10000; buyOperationsFee = 5; buyLiquidityFee = 0; buyTotalFees = buyOperationsFee + buyLiquidityFee; sellOperationsFee = 40; sellLiquidityFee = 0; sellTotalFees = sellOperationsFee + sellLiquidityFee; _excludeFromMaxTransaction(newOwner, true); _excludeFromMaxTransaction(address(this), true); _excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); operationsAddress = address(newOwner); _createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner); } receive() external payable {} function enableTrading() external onlyOwner { require(!tradingActive, "Cannot reenable trading"); tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; emit EnabledTrading(); } function removeLimits() external onlyOwner { limitsInEffect = false; transferDelayEnabled = false; emit RemovedLimits(); } function manageBoughtEarly(address wallet, bool flag) external onlyOwner { bot[wallet] = flag; } function massManageBoughtEarly(address[] calldata wallets, bool flag) external onlyOwner { for(uint256 i = 0; i < wallets.length; i++){ bot[wallets[i]] = flag; } } function massManageBoughtEarly(address[] calldata wallets, bool flag) external onlyOwner { for(uint256 i = 0; i < wallets.length; i++){ bot[wallets[i]] = flag; } } function disableTransferDelay() external onlyOwner { transferDelayEnabled = false; } function updateMaxBuyAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 2 / 1000)/1e18, "Cannot set max buy amount lower than 0.2%"); maxBuyAmount = newNum * (10**18); emit UpdatedMaxBuyAmount(maxBuyAmount); } function updateMaxSellAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 2 / 1000)/1e18, "Cannot set max sell amount lower than 0.2%"); maxSellAmount = newNum * (10**18); emit UpdatedMaxSellAmount(maxSellAmount); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 3 / 1000)/1e18, "Cannot set max wallet amount lower than 0.3%"); maxWalletAmount = newNum * (10**18); emit UpdatedMaxWalletAmount(maxWalletAmount); } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply."); swapTokensAtAmount = newAmount; } function _excludeFromMaxTransaction(address updAds, bool isExcluded) private { _isExcludedMaxTransactionAmount[updAds] = isExcluded; emit MaxTransactionExclusion(updAds, isExcluded); } function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner { require(wallets.length == amountsInTokens.length, "arrays must be the same length"); for(uint256 i = 0; i < wallets.length; i++){ address wallet = wallets[i]; uint256 amount = amountsInTokens[i]; super._transfer(msg.sender, wallet, amount); } } function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner { require(wallets.length == amountsInTokens.length, "arrays must be the same length"); for(uint256 i = 0; i < wallets.length; i++){ address wallet = wallets[i]; uint256 amount = amountsInTokens[i]; super._transfer(msg.sender, wallet, amount); } } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != lpPair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != lpPair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != lpPair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function updateBuyFees(uint256 _operationsFee, uint256 _liquidityFee) external onlyOwner { buyOperationsFee = _operationsFee; buyLiquidityFee = _liquidityFee; buyTotalFees = buyOperationsFee + buyLiquidityFee; require(buyTotalFees <= 50, "Must keep fees at 50% or less"); } function updateSellFees(uint256 _operationsFee, uint256 _liquidityFee) external onlyOwner { sellOperationsFee = _operationsFee; sellLiquidityFee = _liquidityFee; sellTotalFees = sellOperationsFee + sellLiquidityFee; require(sellTotalFees <= 50, "Must keep fees at 50% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } require(!bot[from] && !bot[to], "Bots cannot transfer tokens in or out except to owner or dead address."); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); _approve(address(this), address(dexRouter), tokenAmount); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(dexRouter), tokenAmount); address(this), tokenAmount, address(0xdead), block.timestamp ); } dexRouter.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations; if(contractBalance > swapTokensAtAmount * 60){ contractBalance = swapTokensAtAmount * 60; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations; tokensForLiquidity = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } if(address(this).balance > 0){ } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations; if(contractBalance > swapTokensAtAmount * 60){ contractBalance = swapTokensAtAmount * 60; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations; tokensForLiquidity = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } if(address(this).balance > 0){ } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations; if(contractBalance > swapTokensAtAmount * 60){ contractBalance = swapTokensAtAmount * 60; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations; tokensForLiquidity = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } if(address(this).balance > 0){ } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations; if(contractBalance > swapTokensAtAmount * 60){ contractBalance = swapTokensAtAmount * 60; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations; tokensForLiquidity = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } if(address(this).balance > 0){ } } (success,) = address(operationsAddress).call{value: address(this).balance}(""); function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } function withdrawStuckETH() external onlyOwner { bool success; } (success,) = address(msg.sender).call{value: address(this).balance}(""); function setOperationsAddress(address _operationsAddress) external onlyOwner { require(_operationsAddress != address(0), "_operationsAddress address cannot be 0"); operationsAddress = payable(_operationsAddress); } function forceSwapBack() external onlyOwner { require(balanceOf(address(this)) >= 0, "No tokens to swap"); swapping = true; swapBack(); swapping = false; emit OwnerForcedSwapBack(block.timestamp); } }
3,179,538
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1351, 77, 4667, 58, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 2254, 5034, 1071, 943, 38, 9835, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 55, 1165, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 6275, 31, 203, 203, 565, 1599, 338, 8259, 1071, 302, 338, 8259, 31, 203, 565, 1758, 1071, 12423, 4154, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 203, 565, 1758, 5295, 1887, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 2512, 31, 203, 565, 2254, 5034, 1071, 2512, 87, 24512, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 9343, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 9343, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 2430, 1290, 9343, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 48, 18988, 24237, 31, 203, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2954, 281, 31, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; library Bytes { function toBytes(address x) internal pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } function toAddress(uint _offst, bytes memory _input) internal pure returns (address _output) { assembly { _output := mload(add(_input, _offst)) } } function toBytes(uint256 x) internal pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } function toUint256(uint _offst, bytes memory _input) internal pure returns (uint256 _output) { assembly { _output := mload(add(_input, _offst)) } } /** * Converts byte-arrays to an array of integers */ function toArrayUint256(bytes memory _amounts) internal pure returns (uint256[] memory) { // Format amounts uint256 chunks = _amounts.length / 32; uint256[] memory amountsFormatted = new uint256[](chunks); for (uint256 i = 0; i < chunks; i++) { amountsFormatted[i] = toUint256(i * 32 + 32, _amounts); } return amountsFormatted; } /** * Converts byte-array to an array of addresses */ function toArrayAddress(bytes memory _addresses) internal pure returns (address[] memory) { uint256 chunks = _addresses.length / 32; address[] memory addressesFormatted = new address[](chunks); for (uint256 i = 0; i < chunks; i++) { addressesFormatted[i] = toAddress(i * 32 + 32, _addresses); } return addressesFormatted; } function mergeBytes(bytes memory a, bytes memory b) internal pure returns (bytes memory c) { // From https://ethereum.stackexchange.com/a/40456 uint alen = a.length; uint totallen = alen + b.length; uint loopsa = (a.length + 31) / 32; uint loopsb = (b.length + 31) / 32; assembly { let m := mload(0x40) mstore(m, totallen) for { let i := 0 } lt(i, loopsa) { i := add(1, i) } { mstore(add(m, mul(32, add(1, i))), mload(add(a, mul(32, add(1, i))))) } for { let i := 0 } lt(i, loopsb) { i := add(1, i) } { mstore(add(m, add(mul(32, add(1, i)), alen)), mload(add(b, mul(32, add(1, i))))) } mstore(0x40, add(m, add(32, totallen))) c := m } } }
* Converts byte-arrays to an array of integers/ Format amounts
function toArrayUint256(bytes memory _amounts) internal pure returns (uint256[] memory) { uint256 chunks = _amounts.length / 32; uint256[] memory amountsFormatted = new uint256[](chunks); for (uint256 i = 0; i < chunks; i++) { amountsFormatted[i] = toUint256(i * 32 + 32, _amounts); } return amountsFormatted; }
1,075,915
[ 1, 5692, 1160, 17, 16223, 358, 392, 526, 434, 12321, 19, 4077, 30980, 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, 4434, 5487, 5034, 12, 3890, 3778, 389, 8949, 87, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 13, 203, 565, 288, 203, 3639, 2254, 5034, 6055, 273, 389, 8949, 87, 18, 2469, 342, 3847, 31, 203, 3639, 2254, 5034, 8526, 3778, 30980, 18298, 273, 394, 2254, 5034, 8526, 12, 14691, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 6055, 31, 277, 27245, 288, 203, 5411, 30980, 18298, 63, 77, 65, 273, 358, 5487, 5034, 12, 77, 380, 3847, 397, 3847, 16, 389, 8949, 87, 1769, 203, 3639, 289, 203, 3639, 327, 30980, 18298, 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 ]
pragma solidity >=0.5.0 <0.6.0; /* Arrays When you want a collection of something, you can use an array. There are two types of arrays in Solidity: fixed arrays and dynamic arrays: // Array with a fixed length of 2 elements: uint[2] fixedArray; // another fixed Array, can contain 5 strings: string[5] stringArray; // a dynamic Array - has no fixed size, can keep growing: uint[] dynamicArray; You can also create an array of structs. Using the previous chapter's Person struct: Person[] people; // dynamic Array, we can keep adding to it Remember that state variables are stored permanently in the blockchain? So creating a dynamic array of structs like this can be useful for storing structured data in your contract, kind of like a database. Public Arrays You can declare an array as public, and Solidity will automatically create a getter method for it. The syntax looks like: Person[] public people; Other contracts would then be able to read from, but not write to, this array. So this is a useful pattern for storing public data in your contract. */ contract ZombieFactory { uint myUnsignedInteger = 100; // is equal to uint256, others uint8, uint16, uint32. uint dnDigits = 16; uint dnaModulus = 10 ** dnaDigits; Zombie[] public zombies; struct Zombie { string name; uint dna; } }
Array with a fixed length of 2 elements:
uint[2] fixedArray;
1,753,797
[ 1, 1076, 598, 279, 5499, 769, 434, 576, 2186, 30, 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, 11890, 63, 22, 65, 5499, 1076, 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 ]
/* B.PROTOCOL TERMS OF USE ======================= THE TERMS OF USE CONTAINED HEREIN (THESE “TERMS”) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the “PROTOCOL”) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS (“DLPs”). PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS. IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL. Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age. License; No Warranties; Limitation of Liability; (a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause. (b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", “WITH ALL FAULTS” and “AS AVAILABLE” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. (c) IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.5.12; contract Math { // --- Math --- function add(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function sub(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function mul(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } uint constant RAY = 10 ** 27; function rdiv(uint x, uint y) internal pure returns (uint z) { z = mul(x, RAY) / y; } function rmul(uint x, uint y) internal pure returns (uint z) { z = mul(x, y) / RAY; } function rpow(uint x, uint n, uint b) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := b} default {z := 0}} default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0); } } contract LibNote { event LogNote( bytes4 indexed sig, address indexed usr, bytes32 indexed arg1, bytes32 indexed arg2, bytes data ) anonymous; modifier note { _; assembly { // log an 'anonymous' event with a constant 6 words of calldata // and four indexed topics: selector, caller, arg1 and arg2 let mark := msize() // end of memory ensures zero mstore(0x40, add(mark, 288)) // update free memory pointer mstore(mark, 0x20) // bytes type data offset mstore(add(mark, 0x20), 224) // bytes size (padded) calldatacopy(add(mark, 0x40), 0, 224) // bytes payload log4(mark, 288, // calldata shl(224, shr(224, calldataload(0))), // msg.sig caller(), // msg.sender calldataload(4), // arg1 calldataload(36) // arg2 ) } } } contract BCdpScoreLike { function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) external; } contract BCdpScoreConnector { BCdpScoreLike public score; mapping(uint => uint) public left; constructor(BCdpScoreLike score_) public { score = score_; } function setScore(BCdpScoreLike bcdpScore) internal { score = bcdpScore; } function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) internal { if(left[cdp] == 0) score.updateScore(cdp, ilk, dink, dart, time); } function quitScore(uint cdp) internal { if(left[cdp] == 0) left[cdp] = now; } } contract UrnHandler { constructor(address vat) public { VatLike(vat).hope(msg.sender); } } contract DssCdpManager is LibNote { address public vat; uint public cdpi; // Auto incremental mapping (uint => address) public urns; // CDPId => UrnHandler mapping (uint => List) public list; // CDPId => Prev & Next CDPIds (double linked list) mapping (uint => address) public owns; // CDPId => Owner mapping (uint => bytes32) public ilks; // CDPId => Ilk mapping (address => uint) public first; // Owner => First CDPId mapping (address => uint) public last; // Owner => Last CDPId mapping (address => uint) public count; // Owner => Amount of CDPs mapping ( address => mapping ( uint => mapping ( address => uint ) ) ) public cdpCan; // Owner => CDPId => Allowed Addr => True/False mapping ( address => mapping ( address => uint ) ) public urnCan; // Urn => Allowed Addr => True/False struct List { uint prev; uint next; } event NewCdp(address indexed usr, address indexed own, uint indexed cdp); modifier cdpAllowed( uint cdp ) { require(msg.sender == owns[cdp] || cdpCan[owns[cdp]][cdp][msg.sender] == 1, "cdp-not-allowed"); _; } modifier urnAllowed( address urn ) { require(msg.sender == urn || urnCan[urn][msg.sender] == 1, "urn-not-allowed"); _; } constructor(address vat_) public { vat = vat_; } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0); } // Allow/disallow a usr address to manage the cdp. function cdpAllow( uint cdp, address usr, uint ok ) public cdpAllowed(cdp) { cdpCan[owns[cdp]][cdp][usr] = ok; } // Allow/disallow a usr address to quit to the the sender urn. function urnAllow( address usr, uint ok ) public { urnCan[msg.sender][usr] = ok; } // Open a new cdp for a given usr address. function open( bytes32 ilk, address usr ) public note returns (uint) { require(usr != address(0), "usr-address-0"); cdpi = add(cdpi, 1); urns[cdpi] = address(new UrnHandler(vat)); owns[cdpi] = usr; ilks[cdpi] = ilk; // Add new CDP to double linked list and pointers if (first[usr] == 0) { first[usr] = cdpi; } if (last[usr] != 0) { list[cdpi].prev = last[usr]; list[last[usr]].next = cdpi; } last[usr] = cdpi; count[usr] = add(count[usr], 1); emit NewCdp(msg.sender, usr, cdpi); return cdpi; } // Give the cdp ownership to a dst address. function give( uint cdp, address dst ) public note cdpAllowed(cdp) { require(dst != address(0), "dst-address-0"); require(dst != owns[cdp], "dst-already-owner"); // Remove transferred CDP from double linked list of origin user and pointers if (list[cdp].prev != 0) { list[list[cdp].prev].next = list[cdp].next; // Set the next pointer of the prev cdp (if exists) to the next of the transferred one } if (list[cdp].next != 0) { // If wasn't the last one list[list[cdp].next].prev = list[cdp].prev; // Set the prev pointer of the next cdp to the prev of the transferred one } else { // If was the last one last[owns[cdp]] = list[cdp].prev; // Update last pointer of the owner } if (first[owns[cdp]] == cdp) { // If was the first one first[owns[cdp]] = list[cdp].next; // Update first pointer of the owner } count[owns[cdp]] = sub(count[owns[cdp]], 1); // Transfer ownership owns[cdp] = dst; // Add transferred CDP to double linked list of destiny user and pointers list[cdp].prev = last[dst]; list[cdp].next = 0; if (last[dst] != 0) { list[last[dst]].next = cdp; } if (first[dst] == 0) { first[dst] = cdp; } last[dst] = cdp; count[dst] = add(count[dst], 1); } // Frob the cdp keeping the generated DAI or collateral freed in the cdp urn address. function frob( uint cdp, int dink, int dart ) public note cdpAllowed(cdp) { address urn = urns[cdp]; VatLike(vat).frob( ilks[cdp], urn, urn, urn, dink, dart ); } // Transfer wad amount of cdp collateral from the cdp address to a dst address. function flux( uint cdp, address dst, uint wad ) public note cdpAllowed(cdp) { VatLike(vat).flux(ilks[cdp], urns[cdp], dst, wad); } // Transfer wad amount of any type of collateral (ilk) from the cdp address to a dst address. // This function has the purpose to take away collateral from the system that doesn't correspond to the cdp but was sent there wrongly. function flux( bytes32 ilk, uint cdp, address dst, uint wad ) public note cdpAllowed(cdp) { VatLike(vat).flux(ilk, urns[cdp], dst, wad); } // Transfer wad amount of DAI from the cdp address to a dst address. function move( uint cdp, address dst, uint rad ) public note cdpAllowed(cdp) { VatLike(vat).move(urns[cdp], dst, rad); } // Quit the system, migrating the cdp (ink, art) to a different dst urn function quit( uint cdp, address dst ) public note cdpAllowed(cdp) urnAllowed(dst) { (uint ink, uint art) = VatLike(vat).urns(ilks[cdp], urns[cdp]); VatLike(vat).fork( ilks[cdp], urns[cdp], dst, toInt(ink), toInt(art) ); } // Import a position from src urn to the urn owned by cdp function enter( address src, uint cdp ) public note urnAllowed(src) cdpAllowed(cdp) { (uint ink, uint art) = VatLike(vat).urns(ilks[cdp], src); VatLike(vat).fork( ilks[cdp], src, urns[cdp], toInt(ink), toInt(art) ); } // Move a position from cdpSrc urn to the cdpDst urn function shift( uint cdpSrc, uint cdpDst ) public note cdpAllowed(cdpSrc) cdpAllowed(cdpDst) { require(ilks[cdpSrc] == ilks[cdpDst], "non-matching-cdps"); (uint ink, uint art) = VatLike(vat).urns(ilks[cdpSrc], urns[cdpSrc]); VatLike(vat).fork( ilks[cdpSrc], urns[cdpSrc], urns[cdpDst], toInt(ink), toInt(art) ); } } interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } 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), "ds-auth-unauthorized"); _; } 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); } } } contract VatLike { function urns(bytes32, address) public view returns (uint, uint); function hope(address) external; function flux(bytes32, address, address, uint) public; function move(address, address, uint) public; function frob(bytes32, address, address, address, int, int) public; function fork(bytes32, address, address, int, int) public; function ilks(bytes32 ilk) public view returns(uint Art, uint rate, uint spot, uint line, uint dust); function dai(address usr) external view returns(uint); } contract CatLike { function ilks(bytes32) public returns(address flip, uint256 chop, uint256 lump); } contract EndLike { function cat() public view returns(CatLike); } contract PriceFeedLike { function read(bytes32 ilk) external view returns(bytes32); } contract LiquidationMachine is DssCdpManager, BCdpScoreConnector, Math { VatLike public vat; EndLike public end; address public pool; PriceFeedLike public real; mapping(uint => uint) public tic; // time of bite mapping(uint => uint) public cushion; // how much was topped in art units uint constant public GRACE = 1 hours; uint constant public WAD = 1e18; mapping (uint => bool) public out; modifier onlyPool { require(msg.sender == pool, "not-pool"); _; } constructor(VatLike vat_, EndLike end_, address pool_, PriceFeedLike real_) public { vat = vat_; end = end_; pool = pool_; real = real_; } function setPool(address newPool) internal { pool = newPool; } function quitBLiquidation(uint cdp) internal { untop(cdp); out[cdp] = true; } function topup(uint cdp, uint dtopup) external onlyPool { if(out[cdp]) return; address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; (, uint rate,,,) = vat.ilks(ilk); uint dtab = mul(rate, dtopup); vat.move(pool, address(this), dtab); vat.frob(ilk, urn, urn, address(this), 0, -toInt(dtopup)); cushion[cdp] = add(cushion[cdp], dtopup); } function bitten(uint cdp) public view returns(bool) { return tic[cdp] + GRACE > now; } function untop(uint cdp) internal { require(! bitten(cdp), "untop: cdp was already bitten"); uint top = cushion[cdp]; if(top == 0) return; // nothing to do bytes32 ilk = ilks[cdp]; address urn = urns[cdp]; (, uint rate,,,) = vat.ilks(ilk); uint dtab = mul(rate, top); cushion[cdp] = 0; // move topping to pool vat.frob(ilk, urn, urn, urn, 0, toInt(top)); vat.move(urn, pool, dtab); } function untopByPool(uint cdp) external onlyPool { untop(cdp); } function doBite(uint dart, bytes32 ilk, address urn, uint dink) internal { (, uint rate,,,) = vat.ilks(ilk); uint dtab = mul(rate, dart); vat.move(pool, address(this), dtab); vat.frob(ilk, urn, urn, address(this), 0, -toInt(dart)); vat.frob(ilk, urn, msg.sender, urn, -toInt(dink), 0); } function calcDink(uint dart, uint rate, bytes32 ilk) internal returns(uint dink) { (, uint chop,) = end.cat().ilks(ilk); uint tab = mul(mul(dart, rate), chop) / WAD; bytes32 realtimePrice = real.read(ilk); dink = rmul(tab, WAD) / uint(realtimePrice); } function bite(uint cdp, uint dart) external onlyPool returns(uint dink){ address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; (uint ink, uint art) = vat.urns(ilk, urn); art = add(art, cushion[cdp]); (, uint rate, uint spotValue,,) = vat.ilks(ilk); require(dart <= art, "debt is too low"); // verify cdp is unsafe now if(! bitten(cdp)) { require(mul(art, rate) > mul(ink, spotValue), "bite: cdp is safe"); require(cushion[cdp] > 0, "bite: not-topped"); tic[cdp] = now; } dink = calcDink(dart, rate, ilk); updateScore(cdp, ilk, -toInt(dink), -toInt(dart), now); uint usedCushion = mul(cushion[cdp], dart) / art; cushion[cdp] = sub(cushion[cdp], usedCushion); uint bart = sub(dart, usedCushion); doBite(bart, ilk, urn, dink); } } contract BCdpManager is BCdpScoreConnector, LiquidationMachine, DSAuth { constructor(address vat_, address end_, address pool_, address real_, address score_) public DssCdpManager(vat_) LiquidationMachine(VatLike(vat_), EndLike(end_), pool_, PriceFeedLike(real_)) BCdpScoreConnector(BCdpScoreLike(score_)) { } // Frob the cdp keeping the generated DAI or collateral freed in the cdp urn address. function frob( uint cdp, int dink, int dart ) public cdpAllowed(cdp) { bytes32 ilk = ilks[cdp]; untop(cdp); updateScore(cdp, ilk, dink, dart, now); super.frob(cdp, dink, dart); } // Quit the system, migrating the cdp (ink, art) to a different dst urn function quit( uint cdp, address dst ) public cdpAllowed(cdp) urnAllowed(dst) { address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; untop(cdp); (uint ink, uint art) = vat.urns(ilk, urn); updateScore(cdp, ilk, -toInt(ink), -toInt(art), now); super.quit(cdp, dst); } // Import a position from src urn to the urn owned by cdp function enter( address src, uint cdp ) public urnAllowed(src) cdpAllowed(cdp) { bytes32 ilk = ilks[cdp]; untop(cdp); (uint ink, uint art) = vat.urns(ilk, src); updateScore(cdp, ilk, toInt(ink), toInt(art), now); super.enter(src, cdp); } // Move a position from cdpSrc urn to the cdpDst urn function shift( uint cdpSrc, uint cdpDst ) public cdpAllowed(cdpSrc) cdpAllowed(cdpDst) { bytes32 ilkSrc = ilks[cdpSrc]; untop(cdpSrc); untop(cdpDst); address src = urns[cdpSrc]; (uint inkSrc, uint artSrc) = vat.urns(ilkSrc, src); updateScore(cdpSrc, ilkSrc, -toInt(inkSrc), -toInt(artSrc), now); updateScore(cdpDst, ilkSrc, toInt(inkSrc), toInt(artSrc), now); super.shift(cdpSrc, cdpDst); } ///////////////// B specific control functions ///////////////////////////// function quitB(uint cdp) external cdpAllowed(cdp) note { quitScore(cdp); quitBLiquidation(cdp); } function setScoreContract(BCdpScoreLike _score) external auth { super.setScore(_score); } function setPoolContract(address _pool) external auth { super.setPool(_pool); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ScoringMachine is Ownable { struct AssetScore { // total score so far uint score; // current balance uint balance; // time when last update was uint last; } // user is bytes32 (will be the sha3 of address or cdp number) mapping(bytes32 => mapping(bytes32 => AssetScore[])) public checkpoints; mapping(bytes32 => mapping(bytes32 => AssetScore)) public userScore; bytes32 constant public GLOBAL_USER = bytes32(0x0); uint public start; // start time of the campaign; function spin() external onlyOwner { // start a new round start = now; } function assetScore(AssetScore storage score, uint time, uint spinStart) internal view returns(uint) { uint last = score.last; uint currentScore = score.score; if(last < spinStart) { last = spinStart; currentScore = 0; } return add(currentScore, mul(score.balance, sub(time, last))); } function addCheckpoint(bytes32 user, bytes32 asset) internal { checkpoints[user][asset].push(userScore[user][asset]); } function updateAssetScore(bytes32 user, bytes32 asset, int dbalance, uint time) internal { AssetScore storage score = userScore[user][asset]; if(score.last < start) addCheckpoint(user, asset); score.score = assetScore(score, time, start); score.balance = add(score.balance, dbalance); score.last = time; } function updateScore(bytes32 user, bytes32 asset, int dbalance, uint time) internal { updateAssetScore(user, asset, dbalance, time); updateAssetScore(GLOBAL_USER, asset, dbalance, time); } function getScore(bytes32 user, bytes32 asset, uint time, uint spinStart, uint checkPointHint) public view returns(uint score) { if(time >= userScore[user][asset].last) return assetScore(userScore[user][asset], time, spinStart); // else - check the checkpoints uint checkpointsLen = checkpoints[user][asset].length; if(checkpointsLen == 0) return 0; // hint is invalid if(checkpoints[user][asset][checkPointHint].last < time) checkPointHint = checkpointsLen - 1; for(uint i = checkPointHint ; ; i--){ if(checkpoints[user][asset][i].last <= time) return assetScore(checkpoints[user][asset][i], time, spinStart); } // this supposed to be unreachable return 0; } function getCurrentBalance(bytes32 user, bytes32 asset) public view returns(uint balance) { balance = userScore[user][asset].balance; } // Math functions without errors // ============================== function add(uint x, uint y) internal pure returns (uint z) { z = x + y; if(!(z >= x)) return 0; return z; } function add(uint x, int y) internal pure returns (uint z) { z = x + uint(y); if(!(y >= 0 || z <= x)) return 0; if(!(y <= 0 || z >= x)) return 0; return z; } function sub(uint x, uint y) internal pure returns (uint z) { if(!(y <= x)) return 0; z = x - y; return z; } function mul(uint x, uint y) internal pure returns (uint z) { if (x == 0) return 0; z = x * y; if(!(z / x == y)) return 0; return z; } } contract BCdpScore is ScoringMachine { BCdpManager public manager; modifier onlyManager { require(msg.sender == address(manager), "not-manager"); _; } function setManager(address newManager) external onlyOwner { manager = BCdpManager(newManager); } function user(uint cdp) public pure returns(bytes32) { return keccak256(abi.encodePacked("BCdpScore", cdp)); } function artAsset(bytes32 ilk) public pure returns(bytes32) { return keccak256(abi.encodePacked("BCdpScore", "art", ilk)); } function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) external onlyManager { dink; // shh compiler warning updateScore(user(cdp), artAsset(ilk), dart, time); } function slashScore(uint maliciousCdp) external { address urn = manager.urns(maliciousCdp); bytes32 ilk = manager.ilks(maliciousCdp); (, uint realArt) = manager.vat().urns(ilk, urn); bytes32 maliciousUser = user(maliciousCdp); bytes32 asset = artAsset(ilk); uint left = BCdpScoreConnector(address(manager)).left(maliciousCdp); realArt = left > 0 ? 0 : realArt; uint startTime = left > 0 ? left : now; uint calculatedArt = getCurrentBalance(maliciousUser, asset); require(realArt < calculatedArt, "slashScore-cdp-is-ok"); int dart = int(realArt) - int(calculatedArt); uint time = sub(startTime, 30 days); if(time < start) time = start; updateScore(maliciousUser, asset, dart, time); } function getArtScore(uint cdp, bytes32 ilk, uint time, uint spinStart) public view returns(uint) { return getScore(user(cdp), artAsset(ilk), time, spinStart, 0); } function getArtGlobalScore(bytes32 ilk, uint time, uint spinStart) public view returns(uint) { return getScore(GLOBAL_USER, artAsset(ilk), time, spinStart, 0); } } contract JarConnector is Math { BCdpScore public score; BCdpManager public man; bytes32[] public ilks; // ilk => supported mapping(bytes32 => bool) public milks; // end of every round uint[2] public end; // start time of every round uint[2] public start; uint public round; constructor( bytes32[] memory _ilks, uint[2] memory _duration ) public { ilks = _ilks; for(uint i = 0; i < _ilks.length; i++) { milks[_ilks[i]] = true; } end[0] = now + _duration[0]; end[1] = now + _duration[0] + _duration[1]; round = 0; } function setManager(address _manager) public { require(man == BCdpManager(0), "manager-already-set"); man = BCdpManager(_manager); score = BCdpScore(address(man.score())); } // callable by anyone function spin() public { if(round == 0) { round++; score.spin(); start[0] = score.start(); } if(round == 1 && now > end[0]) { round++; score.spin(); start[1] = score.start(); } if(round == 2 && now > end[1]) { round++; // score is not counted anymore, and this must be followed by contract upgrade score.spin(); } } function getUserScore(bytes32 user) external view returns (uint) { if(round == 0) return 0; uint cdp = uint(user); bytes32 ilk = man.ilks(cdp); // Should return 0 score for unsupported ilk if( ! milks[ilk]) return 0; if(round == 1) return 2 * score.getArtScore(cdp, ilk, now, start[0]); uint firstRoundScore = 2 * score.getArtScore(cdp, ilk, start[1], start[0]); uint time = now; if(round > 2) time = end[1]; return add(score.getArtScore(cdp, ilk, time, start[1]), firstRoundScore); } function getGlobalScore() external view returns (uint) { if(round == 0) return 0; if(round == 1) return 2 * getArtGlobalScore(now, start[0]); uint firstRoundScore = 2 * getArtGlobalScore(start[1], start[0]); uint time = now; if(round > 2) time = end[1]; return add(getArtGlobalScore(time, start[1]), firstRoundScore); } function getGlobalScore(bytes32 ilk) external view returns (uint) { if(round == 0) return 0; if(round == 1) return 2 * score.getArtGlobalScore(ilk, now, start[0]); uint firstRoundScore = 2 * score.getArtGlobalScore(ilk, start[1], start[0]); uint time = now; if(round > 2) time = end[1]; return add(score.getArtGlobalScore(ilk, time, start[1]), firstRoundScore); } function getArtGlobalScore(uint time, uint spinStart) internal view returns (uint totalScore) { for(uint i = 0; i < ilks.length; i++) { totalScore = add(totalScore, score.getArtGlobalScore(ilks[i], time, spinStart)); } } function toUser(bytes32 user) external view returns (address) { return man.owns(uint(user)); } } contract JugLike { function ilks(bytes32 ilk) public view returns(uint duty, uint rho); function base() public view returns(uint); } contract SpotLike { function par() external view returns (uint256); function ilks(bytes32 ilk) external view returns (address pip, uint mat); } contract OSMLike { function peep() external view returns(bytes32, bool); function hop() external view returns(uint16); function zzz() external view returns(uint64); } contract DaiToUsdPriceFeed { function getMarketPrice(uint marketId) public view returns (uint); } contract Pool is Math, DSAuth, LibNote { uint public constant DAI_MARKET_ID = 3; address[] public members; mapping(bytes32 => bool) public ilks; uint public minArt; // min debt to share among members uint public shrn; // share profit % numerator uint public shrd; // share profit % denumerator mapping(address => uint) public rad; // mapping from member to its dai balance in rad VatLike public vat; BCdpManager public man; SpotLike public spot; JugLike public jug; address public jar; DaiToUsdPriceFeed public dai2usd; mapping(uint => CdpData) internal cdpData; mapping(bytes32 => OSMLike) public osm; // mapping from ilk to osm struct CdpData { uint art; // topup in art units uint cushion; // cushion in rad units address[] members; // liquidators that are in uint[] bite; // how much was already bitten } modifier onlyMember { bool member = false; for(uint i = 0 ; i < members.length ; i++) { if(members[i] == msg.sender) { member = true; break; } } require(member, "not-member"); _; } constructor(address vat_, address jar_, address spot_, address jug_, address dai2usd_) public { spot = SpotLike(spot_); jug = JugLike(jug_); vat = VatLike(vat_); jar = jar_; dai2usd = DaiToUsdPriceFeed(dai2usd_); } function getCdpData(uint cdp) external view returns(uint art, uint cushion, address[] memory members_, uint[] memory bite) { art = cdpData[cdp].art; cushion = cdpData[cdp].cushion; members_ = cdpData[cdp].members; bite = cdpData[cdp].bite; } function setCdpManager(BCdpManager man_) external auth note { man = man_; vat.hope(address(man)); } function setOsm(bytes32 ilk_, address osm_) external auth note { osm[ilk_] = OSMLike(osm_); } function setMembers(address[] calldata members_) external auth note { members = members_; } function setIlk(bytes32 ilk, bool set) external auth note { ilks[ilk] = set; } function setMinArt(uint minArt_) external auth note { minArt = minArt_; } function setDaiToUsdPriceFeed(address dai2usd_) external auth note { dai2usd = DaiToUsdPriceFeed(dai2usd_); } function setProfitParams(uint num, uint den) external auth note { require(num < den, "invalid-profit-params"); shrn = num; shrd = den; } function emergencyExecute(address target, bytes calldata data) external auth note { (bool succ,) = target.call(data); require(succ, "emergencyExecute: failed"); } function deposit(uint radVal) external onlyMember note { vat.move(msg.sender, address(this), radVal); rad[msg.sender] = add(rad[msg.sender], radVal); } function withdraw(uint radVal) external note { require(rad[msg.sender] >= radVal, "withdraw: insufficient-balance"); rad[msg.sender] = sub(rad[msg.sender], radVal); vat.move(address(this), msg.sender, radVal); } function getIndex(address[] storage array, address elm) internal view returns(uint) { for(uint i = 0 ; i < array.length ; i++) { if(array[i] == elm) return i; } return uint(-1); } function removeElement(address[] memory array, uint index) internal pure returns(address[] memory newArray) { if(index >= array.length) { newArray = array; } else { newArray = new address[](array.length - 1); for(uint i = 0 ; i < array.length ; i++) { if(i == index) continue; if(i < index) newArray[i] = array[i]; else newArray[i-1] = array[i]; } } } function chooseMember(uint cdp, uint radVal, address[] memory candidates) public view returns(address[] memory winners) { if(candidates.length == 0) return candidates; // A bit of randomness to choose winners. We don't need pure randomness, its ok even if a // liquidator can predict his winning in the future. uint chosen = uint(keccak256(abi.encodePacked(cdp, now / 1 hours))) % candidates.length; address winner = candidates[chosen]; if(rad[winner] < radVal) return chooseMember(cdp, radVal, removeElement(candidates, chosen)); winners = new address[](1); winners[0] = candidates[chosen]; return winners; } function chooseMembers(uint radVal, address[] memory candidates) public view returns(address[] memory winners) { if(candidates.length == 0) return candidates; uint need = add(1, radVal / candidates.length); for(uint i = 0 ; i < candidates.length ; i++) { if(rad[candidates[i]] < need) { return chooseMembers(radVal, removeElement(candidates, i)); } } winners = candidates; } function calcCushion(bytes32 ilk, uint ink, uint art, uint nextSpot) public view returns(uint dart, uint dtab) { (, uint prev, uint currSpot,,) = vat.ilks(ilk); if(currSpot <= nextSpot) return (0, 0); uint hop = uint(osm[ilk].hop()); uint next = add(uint(osm[ilk].zzz()), hop); (uint duty, uint rho) = jug.ilks(ilk); require(next >= rho, "calcCushion: next-in-the-past"); // note that makerdao governance could change jug.base() before the actual // liquidation happens. but there is 48 hours time lock on makerdao votes // so liquidators should withdraw their funds if they think such event will // happen uint nextRate = rmul(rpow(add(jug.base(), duty), next - rho, RAY), prev); uint nextnextRate = rmul(rpow(add(jug.base(), duty), hop, RAY), nextRate); if(mul(nextRate, art) > mul(ink, currSpot)) return (0, 0); // prevent L attack if(mul(nextRate, art) <= mul(ink, nextSpot)) return (0, 0); uint maxArt = mul(ink, nextSpot) / nextnextRate; dart = sub(art, maxArt); dart = add(1 ether, dart); // compensate for rounding errors dtab = mul(dart, prev); // provide a cushion according to current rate } function hypoTopAmount(uint cdp) internal view returns(uint dart, uint dtab, uint art, bool should) { address urn = man.urns(cdp); bytes32 ilk = man.ilks(cdp); uint ink; (ink, art) = vat.urns(ilk, urn); if(! ilks[ilk]) return (0, 0, art, false); (bytes32 peep, bool valid) = osm[ilk].peep(); // price feed invalid if(! valid) return (0, 0, art, false); // too early to topup should = (now >= add(uint(osm[ilk].zzz()), uint(osm[ilk].hop())/2)); (, uint mat) = spot.ilks(ilk); uint par = spot.par(); uint nextVatSpot = rdiv(rdiv(mul(uint(peep), uint(10 ** 9)), par), mat); (dart, dtab) = calcCushion(ilk, ink, art, nextVatSpot); } function topAmount(uint cdp) public view returns(uint dart, uint dtab, uint art) { bool should; (dart, dtab, art, should) = hypoTopAmount(cdp); if(! should) return (0, 0, art); } function resetCdp(uint cdp) internal { address[] memory winners = cdpData[cdp].members; if(winners.length == 0) return; uint art = cdpData[cdp].art; uint cushion = cdpData[cdp].cushion; uint perUserArt = cdpData[cdp].art / winners.length; for(uint i = 0 ; i < winners.length ; i++) { if(perUserArt <= cdpData[cdp].bite[i]) continue; // nothing to refund uint refundArt = sub(perUserArt, cdpData[cdp].bite[i]); rad[winners[i]] = add(rad[winners[i]], mul(refundArt, cushion)/art); } cdpData[cdp].art = 0; cdpData[cdp].cushion = 0; delete cdpData[cdp].members; delete cdpData[cdp].bite; } function setCdp(uint cdp, address[] memory winners, uint art, uint dradVal) internal { uint drad = add(1, dradVal / winners.length); // round up for(uint i = 0 ; i < winners.length ; i++) { rad[winners[i]] = sub(rad[winners[i]], drad); } cdpData[cdp].art = art; cdpData[cdp].cushion = dradVal; cdpData[cdp].members = winners; cdpData[cdp].bite = new uint[](winners.length); } function topupInfo(uint cdp) public view returns(uint dart, uint dtab, uint art, bool should, address[] memory winners) { (dart, dtab, art, should) = hypoTopAmount(cdp); if(art < minArt) { winners = chooseMember(cdp, uint(dtab), members); } else winners = chooseMembers(uint(dtab), members); } function topup(uint cdp) external onlyMember note { require(man.cushion(cdp) == 0, "topup: already-topped"); require(! man.bitten(cdp), "topup: already-bitten"); (uint dart, uint dtab, uint art, bool should, address[] memory winners) = topupInfo(cdp); require(should, "topup: no-need"); require(dart > 0, "topup: 0-dart"); resetCdp(cdp); require(winners.length > 0, "topup: members-are-broke"); // for small amounts, only winner can topup if(art < minArt) require(winners[0] == msg.sender, "topup: only-winner-can-topup"); setCdp(cdp, winners, uint(art), uint(dtab)); man.topup(cdp, uint(dart)); } function untop(uint cdp) external onlyMember note { require(man.cushion(cdp) == 0, "untop: should-be-untopped-by-user"); require(! man.bitten(cdp), "topup: in-bite-process"); resetCdp(cdp); } function bite(uint cdp, uint dart, uint minInk) external onlyMember note returns(uint dMemberInk){ uint index = getIndex(cdpData[cdp].members, msg.sender); uint availBite = availBite(cdp, index); require(dart <= availBite, "bite: debt-too-small"); cdpData[cdp].bite[index] = add(cdpData[cdp].bite[index], dart); uint radBefore = vat.dai(address(this)); uint dink = man.bite(cdp, dart); uint radAfter = vat.dai(address(this)); // update user rad rad[msg.sender] = sub(rad[msg.sender], sub(radBefore, radAfter)); // DAI to USD rate, scale 1e18 uint d2uPrice = dai2usd.getMarketPrice(DAI_MARKET_ID); // dMemberInk = debt * 1.065 * d2uPrice // dMemberInk = dink * (shrn/shrd) * (d2uPrice/1e18) dMemberInk = mul(mul(dink, shrn), d2uPrice) / mul(shrd, uint(1 ether)); // To protect edge case when 1 DAI > 1.13 USD if(dMemberInk > dink) dMemberInk = dink; // Remaining to Jar uint userInk = sub(dink, dMemberInk); require(dMemberInk >= minInk, "bite: low-dink"); bytes32 ilk = man.ilks(cdp); vat.flux(ilk, address(this), jar, userInk); vat.flux(ilk, address(this), msg.sender, dMemberInk); } function availBite(uint cdp, address member) public view returns (uint) { uint index = getIndex(cdpData[cdp].members, member); return availBite(cdp, index); } function availBite(uint cdp, uint index) internal view returns (uint) { if(index == uint(-1)) return 0; uint numMembers = cdpData[cdp].members.length; uint maxArt = cdpData[cdp].art / numMembers; // give dust to first member if(index == 0) { uint dust = cdpData[cdp].art % numMembers; maxArt = add(maxArt, dust); } uint availArt = sub(maxArt, cdpData[cdp].bite[index]); return availArt; } }
update user rad DAI to USD rate, scale 1e18 dMemberInk = debt * 1.065 * d2uPrice dMemberInk = dink * (shrn/shrd) * (d2uPrice/1e18) To protect edge case when 1 DAI > 1.13 USD Remaining to Jar
function bite(uint cdp, uint dart, uint minInk) external onlyMember note returns(uint dMemberInk){ uint index = getIndex(cdpData[cdp].members, msg.sender); uint availBite = availBite(cdp, index); require(dart <= availBite, "bite: debt-too-small"); cdpData[cdp].bite[index] = add(cdpData[cdp].bite[index], dart); uint radBefore = vat.dai(address(this)); uint dink = man.bite(cdp, dart); uint radAfter = vat.dai(address(this)); rad[msg.sender] = sub(rad[msg.sender], sub(radBefore, radAfter)); uint d2uPrice = dai2usd.getMarketPrice(DAI_MARKET_ID); dMemberInk = mul(mul(dink, shrn), d2uPrice) / mul(shrd, uint(1 ether)); if(dMemberInk > dink) dMemberInk = dink; uint userInk = sub(dink, dMemberInk); require(dMemberInk >= minInk, "bite: low-dink"); bytes32 ilk = man.ilks(cdp); vat.flux(ilk, address(this), jar, userInk); vat.flux(ilk, address(this), msg.sender, dMemberInk); }
13,764,142
[ 1, 2725, 729, 6719, 463, 18194, 358, 587, 9903, 4993, 16, 3159, 404, 73, 2643, 302, 4419, 382, 79, 273, 18202, 88, 225, 404, 18, 7677, 25, 225, 302, 22, 89, 5147, 302, 4419, 382, 79, 273, 302, 754, 225, 261, 674, 27639, 19, 674, 13623, 13, 225, 261, 72, 22, 89, 5147, 19, 21, 73, 2643, 13, 2974, 17151, 3591, 648, 1347, 404, 463, 18194, 405, 404, 18, 3437, 587, 9903, 2663, 3280, 358, 15644, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 324, 1137, 12, 11890, 7976, 84, 16, 2254, 302, 485, 16, 2254, 1131, 382, 79, 13, 3903, 1338, 4419, 4721, 1135, 12, 11890, 302, 4419, 382, 79, 15329, 203, 3639, 2254, 770, 273, 8088, 12, 4315, 84, 751, 63, 4315, 84, 8009, 7640, 16, 1234, 18, 15330, 1769, 203, 3639, 2254, 15783, 38, 1137, 273, 15783, 38, 1137, 12, 4315, 84, 16, 770, 1769, 203, 3639, 2583, 12, 72, 485, 1648, 15783, 38, 1137, 16, 315, 70, 1137, 30, 18202, 88, 17, 16431, 17, 12019, 8863, 203, 203, 3639, 7976, 84, 751, 63, 4315, 84, 8009, 70, 1137, 63, 1615, 65, 273, 527, 12, 4315, 84, 751, 63, 4315, 84, 8009, 70, 1137, 63, 1615, 6487, 302, 485, 1769, 203, 203, 3639, 2254, 6719, 4649, 273, 17359, 18, 2414, 77, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 302, 754, 273, 3161, 18, 70, 1137, 12, 4315, 84, 16, 302, 485, 1769, 203, 3639, 2254, 6719, 4436, 273, 17359, 18, 2414, 77, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 6719, 63, 3576, 18, 15330, 65, 273, 720, 12, 6012, 63, 3576, 18, 15330, 6487, 720, 12, 6012, 4649, 16, 6719, 4436, 10019, 203, 203, 3639, 2254, 302, 22, 89, 5147, 273, 5248, 77, 22, 407, 72, 18, 588, 3882, 278, 5147, 12, 9793, 45, 67, 12693, 1584, 67, 734, 1769, 203, 203, 3639, 302, 4419, 382, 79, 273, 14064, 12, 16411, 12, 72, 754, 16, 699, 27639, 3631, 302, 22, 89, 5147, 13, 342, 14064, 12, 674, 13623, 16, 2254, 12, 2 ]
./partial_match/1/0x4C7E5feD8751809F43e5E0108978BdB5b37e0945/sources/TornomyTokenGateway.sol
* @title InitializableUpgradeabilityProxy @dev Extends BaseUpgradeabilityProxy with an initializer for initializing implementation and init data./
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } }
9,158,020
[ 1, 4435, 6934, 10784, 2967, 3886, 225, 6419, 5839, 3360, 10784, 2967, 3886, 598, 392, 12562, 364, 22584, 4471, 471, 1208, 501, 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 ]
[ 1, 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, 16351, 10188, 6934, 10784, 2967, 3886, 353, 3360, 10784, 2967, 3886, 288, 203, 565, 445, 4046, 12, 2867, 389, 28339, 16, 1731, 3778, 389, 892, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 24899, 30810, 1435, 422, 1758, 12, 20, 10019, 203, 3639, 1815, 12, 9883, 7618, 2689, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2668, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 26112, 300, 404, 10019, 203, 3639, 389, 542, 13621, 24899, 28339, 1769, 203, 3639, 309, 261, 67, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 261, 6430, 2216, 16, 13, 273, 389, 28339, 18, 22216, 1991, 24899, 892, 1769, 203, 5411, 2583, 12, 4768, 1769, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 4046, 12, 2867, 389, 28339, 16, 1731, 3778, 389, 892, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 24899, 30810, 1435, 422, 1758, 12, 20, 10019, 203, 3639, 1815, 12, 9883, 7618, 2689, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2668, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 26112, 300, 404, 10019, 203, 3639, 389, 542, 13621, 24899, 28339, 1769, 203, 3639, 309, 261, 67, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 261, 6430, 2216, 16, 13, 273, 389, 28339, 18, 22216, 1991, 24899, 892, 1769, 203, 5411, 2583, 12, 4768, 1769, 203, 3639, 289, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { ICollectionFactory } from "../interfaces/ICollectionFactory.sol"; import { ICollection } from "../interfaces/ICollection.sol"; import { ICollectionCloneable } from "../interfaces/ICollectionCloneable.sol"; import { ICollectionNFTCloneableV1 } from "../interfaces/ICollectionNFTCloneableV1.sol"; import { ICollectionNFTEligibilityPredicate } from "../interfaces/ICollectionNFTEligibilityPredicate.sol"; import { ICollectionNFTMintFeePredicate } from "../interfaces/ICollectionNFTMintFeePredicate.sol"; import { IERC2981Royalties } from "../interfaces/IERC2981Royalties.sol"; import { IHashes } from "../interfaces/IHashes.sol"; import { IOwnable } from "../interfaces/IOwnable.sol"; import { OwnableCloneable } from "./OwnableCloneable.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title CollectionNFTCloneableV1 * @author DEX Labs * @notice This contract is the cloneable template for Hashes Collections. * It is an ERC-721 contract which is preconfigured to work within * the Hashes ecosystem. Creation logic has been moved to an initialization * function so it works with the cloneable factory pattern. */ contract CollectionNFTCloneableV1 is ICollection, ICollectionCloneable, ICollectionNFTCloneableV1, OwnableCloneable, ERC721Enumerable, IERC2981Royalties, ReentrancyGuard { using SafeMath for uint16; using SafeMath for uint64; using SafeMath for uint128; using SafeMath for uint256; bool _initialized; /// @notice A structure for storing a token ID in a map. struct TokenIdEntry { bool exists; uint128 tokenId; } /// @notice A structure for decoding and storing data from the factory initializer struct InitializerSettings { string tokenName; string tokenSymbol; string baseTokenURI; uint256 cap; ICollectionNFTEligibilityPredicate mintEligibilityPredicateContract; ICollectionNFTMintFeePredicate mintFeePredicateContract; uint16 royaltyBps; address signatureBlockAddress; } /// @notice nonce Monotonically-increasing number (token ID). uint256 public nonce; /// @notice cap The supply cap for this token. Set to 0 for unlimited. uint256 public cap; /// @notice baseTokenURI The base token URI for this token. string public baseTokenURI; /// @notice tokenName The name of the ERC-721 token. string private tokenName; /// @notice tokenSymbol The symbol of the ERC-721 token. string private tokenSymbol; /// @notice creatorAddress The address of the collection creator. address public creatorAddress; /// @notice signatureBlockAddress An optional address which (when set) will cause all tokens to be /// minted from this address and then immediately transfered to the mint message sender. address public signatureBlockAddress; // Interface for contract which contains a function isTokenEligibleToMint(tokenId, hashesTokenId) // used for determining mint eligibility for a Hashes token. ICollectionNFTEligibilityPredicate public mintEligibilityPredicateContract; // Interface for contract which contains a function getTokenMintFee(tokenId, hashesTokenId) // used for determining the mint fee for a Hashes token. ICollectionNFTMintFeePredicate public mintFeePredicateContract; /// @notice hashesIdToCollectionTokenIdMapping Mapping of Hashes ID to collection token ID. mapping(uint256 => TokenIdEntry) public hashesIdToCollectionTokenIdMapping; /// @notice royaltyBps The sales royalty amount (in hundredths of a percent). uint16 public royaltyBps; uint16 private _hashesDAOMintFeePercent; uint16 private _hashesDAORoyaltyFeePercent; uint16 private _maximumCollectionRoyaltyPercent; /// @notice isSignatureBlockCompleted Whether the signature block address has interacted with this /// contract to verify their support of this contract and establish provenance. bool public isSignatureBlockCompleted; IHashes hashesToken; /// @notice CollectionInitialized Emitted when a Collection is initialized. event CollectionInitialized( string tokenName, string tokenSymbol, string baseTokenURI, uint256 cap, address mintEligibilityPredicateAddress, address mintFeePredicateAddress, uint16 royaltyBps, address signatureBlockAddress, uint64 indexed initializationBlock ); /// @notice Minted Emitted when a Hashes Collection is minted. event Minted(address indexed minter, uint256 indexed tokenId, uint256 indexed hashesTokenId); /// @notice BaseTokenURISet Emitted when the base token URI is updated. event BaseTokenURISet(string baseTokenURI); /// @notice Withdraw Emitted when a withdraw event is triggered. event Withdraw(uint256 indexed creatorAmount, uint256 indexed hashesDAOAmount); /// @notice CreatorTransferred Emitted when the creator address is transferred. event CreatorTransferred(address indexed previousCreator, address indexed newCreator); /// @notice RoyaltyBpsSet Emitted when the royalty bps is set. event RoyaltyBpsSet(uint16 royaltyBps); /// @notice Burned Emitted when a token is burned. event Burned(address indexed burner, uint256 indexed tokenId); /// @notice SignatureBlockCompleted Emitted when the signature block is completed. event SignatureBlockCompleted(address indexed signatureBlockAddress); /// @notice SignatureBlockAddressSet Emitted when the signature block address is set. event SignatureBlockAddressSet(address indexed signatureBlockAddress); modifier initialized() { require(_initialized, "CollectionNFTCloneableV1: hasn't been initialized yet."); _; } modifier onlyOwnerOrHashesDAO() { require( _msgSender() == owner() || _msgSender() == IOwnable(address(hashesToken)).owner(), "CollectionNFTCloneableV1: must be contract owner or HashesDAO" ); _; } modifier onlyCreator() { require(_msgSender() == creatorAddress, "CollectionNFTCloneableV1: must be contract creator"); _; } /** * @notice Constructor for the cloneable Hashes Collection contract. The ERC-721 token * name and symbol aren't used since they are provided in the initialize function. */ constructor() ERC721("TOKEN_NAME_PLACEHOLDER", "TOKEN_SYMBOL_PLACEHOLDER") {} receive() external payable {} /** * @notice This function is used by the Factory to verify the format of ecosystem settings * @param _settings ABI encoded ecosystem settings data. This expected encoding for * ecosystem name 'NFT_v1' is the following: * * 'uint16' hashesDAOMintFeePercent - The percentage of mint fees owable to HashesDAO. * 'uint16' hashesDAORoyaltyFeePercent - The percentage of royalties owable to HashesDAO. This will * be the percentage of the royalties percent set by the creator. * 'uint16' maximumCollectionRoyaltyPercent - The highest allowable royalty percentage * settable by creators for cloned instances of this contract. * @return The boolean result of the validation. */ function verifyEcosystemSettings(bytes memory _settings) external pure override returns (bool) { ( uint16 _settingsHashesDAOMintFeePercent, uint16 _settingsHashesDAORoyaltyFeePercent, uint16 _settingsMaximumCollectionRoyaltyPercent ) = abi.decode(_settings, (uint16, uint16, uint16)); return _settingsHashesDAOMintFeePercent <= 10000 && _settingsHashesDAORoyaltyFeePercent <= 10000 && _settingsMaximumCollectionRoyaltyPercent <= 10000; } /** * @notice This function initializes a cloneable implementation contract. * @param _hashesToken The Hashes NFT contract address. * @param _factoryMaintainerAddress The address of the current factory maintainer * which will be the Owner role of this collection. * @param _createCollectionCaller The address which has called createCollection on the factory. * This will be the Creator role of this collection. * @param _initializationData ABI encoded initialization data. This expected encoding is a struct * with the following properties: * * 'string' tokenName - The name of the resulting ERC-721 token. * 'string' tokenSymbol - The symbol of the resulting ERC-721 token. * 'string' baseTokenURI - The initial base token URI of the resulting ERC-721 token. * 'uint256' cap - The maximum token supply of the resulting ERC-721 token. Set 0 for no limit. * 'address' mintEligibilityPredicateContract - The address of a contract which contains a * function isTokenEligibleToMint(uint256 tokenId, uint256 hashesTokenId) used to * determine whether the chosen Hashes token ID is eligible for minting. Contracts * which define this logic should implement the interface ICollectionNFTEligibilityPredicate. * 'address' mintFeePredicateContract - The address of a contract which contains a function * getTokenMintFee(tokenId, hashesTokenId) used to determine the mint fee for the * chosen Hashes token ID. Contracts which define this logic should implement the * interface ICollectionNFTMintFeePredicate. * 'uint16' royaltyBps - The sales royalty that should be collected. A percentage of this * will be allocated for the HashesDAO to withdraw. * 'address' signatureBlockAddress - An optional address which can be used to establish * creator provenance. When set, the specified address (could be the artist for example) * can call completeSignatureBlock to establish provenance and sign off on the contract * values. To skip using this mechanism, set the value of this field to the 0x0 address. */ function initialize( IHashes _hashesToken, address _factoryMaintainerAddress, address _createCollectionCaller, bytes memory _initializationData ) external override { require(!_initialized, "CollectionNFTCloneableV1: already inititialized."); initializeOwnership(_factoryMaintainerAddress); creatorAddress = _createCollectionCaller; // Use this struct workaround to get around Stack Too Deep issues InitializerSettings memory _initializerSettings; (_initializerSettings) = abi.decode(_initializationData, (InitializerSettings)); tokenName = _initializerSettings.tokenName; tokenSymbol = _initializerSettings.tokenSymbol; baseTokenURI = _initializerSettings.baseTokenURI; cap = _initializerSettings.cap; mintEligibilityPredicateContract = _initializerSettings.mintEligibilityPredicateContract; mintFeePredicateContract = _initializerSettings.mintFeePredicateContract; royaltyBps = _initializerSettings.royaltyBps; signatureBlockAddress = _initializerSettings.signatureBlockAddress; uint64 _initializationBlock = safe64(block.number, "CollectionNFTCloneableV1: exceeds 64 bits."); bytes memory settingsBytes = ICollectionFactory(_msgSender()).getEcosystemSettings( keccak256(abi.encodePacked("NFT_v1")), _initializationBlock ); (_hashesDAOMintFeePercent, _hashesDAORoyaltyFeePercent, _maximumCollectionRoyaltyPercent) = abi.decode( settingsBytes, (uint16, uint16, uint16) ); require( royaltyBps <= _maximumCollectionRoyaltyPercent, "CollectionNFTCloneableV1: royalty percentage must be less than or equal to maximum allowed setting" ); _initialized = true; hashesToken = _hashesToken; emit CollectionInitialized( tokenName, tokenSymbol, baseTokenURI, cap, address(mintEligibilityPredicateContract), address(mintFeePredicateContract), royaltyBps, signatureBlockAddress, _initializationBlock ); } /** * @notice The function used to mint instances of this Hashes Collection ERC-721 token. * Minting requires passing in a specific Hashes token id which is owned by the minter. * Each Hashes token id may only be used to mint once towards a specific collection. * The minting eligibility and fee structure are determined per Hashes token id * by the Hashes Collection owner through predicate functions. The Hashes DAO will receive * a minting fee percentage of each mint, unless a DAO hash was used to mint. * @param _hashesTokenId The Hashes token Id being used to mint. */ function mint(uint256 _hashesTokenId) external payable override initialized nonReentrant { require(cap == 0 || nonce < cap, "CollectionNFTCloneableV1: supply cap has been reached"); require( _msgSender() == hashesToken.ownerOf(_hashesTokenId), "CollectionNFTCloneableV1: must be owner of supplied hashes token ID to mint" ); require( !hashesIdToCollectionTokenIdMapping[_hashesTokenId].exists, "CollectionNFTCloneableV1: supplied token ID has already been used to mint with this collection" ); // get mint eligibility through static call bool isHashesTokenIdEligibleToMint = mintEligibilityPredicateContract.isTokenEligibleToMint( nonce, _hashesTokenId ); require(isHashesTokenIdEligibleToMint, "CollectionNFTCloneableV1: supplied token ID is ineligible to mint"); // get mint fee through static call uint256 currentMintFee = mintFeePredicateContract.getTokenMintFee(nonce, _hashesTokenId); require(msg.value >= currentMintFee, "CollectionNFTCloneableV1: must pass sufficient mint fee."); hashesIdToCollectionTokenIdMapping[_hashesTokenId] = TokenIdEntry({ exists: true, tokenId: safe128(nonce, "CollectionNFTCloneableV1: exceeds 128 bits.") }); uint256 feeForHashesDAO = (currentMintFee.mul(_hashesDAOMintFeePercent)) / 10000; uint256 authorFee = currentMintFee.sub(feeForHashesDAO); uint256 mintFeePaid; if (authorFee > 0) { // If the minting fee is non-zero mintFeePaid = mintFeePaid.add(authorFee); (bool sent, ) = creatorAddress.call{ value: authorFee }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to creator address"); } // Only apply the minting tax for non-DAO hashes (tokenID >= 1000 or deactivated DAO tokens) if (feeForHashesDAO > 0 && (_hashesTokenId >= 1000 || hashesToken.deactivated(_hashesTokenId))) { // If the hashes DAO minting fee is non-zero // Send minting tax to HashesDAO (bool sent, ) = IOwnable(address(hashesToken)).owner().call{ value: feeForHashesDAO }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to HashesDAO"); mintFeePaid = mintFeePaid.add(feeForHashesDAO); } if (msg.value > mintFeePaid) { // If minter passed ETH value greater than the minting // fee paid/computed above // Refund the remaining ether balance to the sender. Since there are no // other payable functions, this remainder will always be the senders. (bool sent, ) = _msgSender().call{ value: msg.value.sub(mintFeePaid) }(""); require(sent, "CollectionNFTCloneableV1: failed to refund ETH."); } _safeMint(_msgSender(), nonce++); emit Minted(_msgSender(), nonce - 1, _hashesTokenId); } /** * @notice The function allows the token owner or approved address to burn the token. * @param _tokenId The token Id to be burned. */ function burn(uint256 _tokenId) external override initialized { require( _isApprovedOrOwner(_msgSender(), _tokenId), "CollectionNFTCloneableV1: caller is not owner nor approved." ); _burn(_tokenId); emit Burned(_msgSender(), _tokenId); } /** * @notice The signatureBlockAddress can call this function to establish provenance and effectively * sign off on the contract. Can be useful in cases where the creator address is different * from the artist address. */ function completeSignatureBlock() external override initialized { require(!isSignatureBlockCompleted, "CollectionNFTCloneableV1: signature block has already been completed"); require( signatureBlockAddress != address(0), "CollectionNFTCloneableV1: signature block address has not been set." ); require( _msgSender() == signatureBlockAddress, "CollectionNFTCloneableV1: only signature block address can complete signature block" ); isSignatureBlockCompleted = true; emit SignatureBlockCompleted(signatureBlockAddress); } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { // Send royalties to this contract address. Note: this will only work for // marketplaces which implement the ERC2981 royalty standard. Off-chain // configuration may be required for certain marketplaces. return (address(this), (value.mul(royaltyBps)).div(10000)); } /** * @notice The function used to renounce contract ownership. This can be performed * by either the Owner or HashesDAO. This departs slightly from the traditional * implementation where only the Owner has this permission. HashesDAO may * need to perform this actions in the case of the factory maintainer changing, * getting lost, or being taken over by a bad actor. */ function renounceOwnership() public override ownershipInitialized onlyOwnerOrHashesDAO { _setOwner(address(0)); } /** * @notice The function used to transfer contract ownership. This can be performed by * either the owner or HashesDAO. This departs slightly from the traditional * implementation where only the Owner has this permission. HashesDAO may * need to perform this actions in the case of the factory maintainer changing, * getting lost, or being taken over by a bad actor. * @param newOwner The new owner address. */ function transferOwnership(address newOwner) public override ownershipInitialized onlyOwnerOrHashesDAO { require(newOwner != address(0), "CollectionNFTCloneableV1: new owner is the zero address"); _setOwner(newOwner); } /** * @notice The function used to set the base token URI. Only collection creator may call. * @param _baseTokenURI The base token URI. */ function setBaseTokenURI(string memory _baseTokenURI) external override initialized onlyCreator { baseTokenURI = _baseTokenURI; emit BaseTokenURISet(_baseTokenURI); } /** * @notice The function used to set the sales royalty bps. Only collection creator may call. * @param _royaltyBps The sales royalty percent in hundredths of a percent. */ function setRoyaltyBps(uint16 _royaltyBps) external override initialized onlyCreator { require( _royaltyBps <= _maximumCollectionRoyaltyPercent, "CollectionNFTCloneableV1: royalty percentage must be less than or equal to maximum allowed setting" ); royaltyBps = _royaltyBps; emit RoyaltyBpsSet(_royaltyBps); } /** * @notice The function used to transfer the creator address. Only collection creator may call. * This is especially important since this concerns withdrawl permissions. * @param _creatorAddress The new creator address. */ function transferCreator(address _creatorAddress) external override initialized onlyCreator { address oldCreator = creatorAddress; creatorAddress = _creatorAddress; emit CreatorTransferred(oldCreator, _creatorAddress); } function setSignatureBlockAddress(address _signatureBlockAddress) external override initialized onlyCreator { require(!isSignatureBlockCompleted, "CollectionNFTCloneableV1: signature block has already been completed"); signatureBlockAddress = _signatureBlockAddress; emit SignatureBlockAddressSet(_signatureBlockAddress); } /** * @notice The function used to withdraw funds to the Collection creator and HashesDAO addresses. * The balance of the contract is equal to the royalties and gifts owed to the creator and HashesDAO. */ function withdraw() external override initialized { // The contract balance is equal to the royalties or gifts which need to be allocated // to both the creator and HashesDAO. uint256 _contractBalance = address(this).balance; // The amount owed to the DAO will be the total royalties times the royalty // fee percent value (in bps). uint256 _daoRoyaltiesOwed = (_contractBalance.mul(_hashesDAORoyaltyFeePercent)).div(10000); // The amount owed to the creator will then be the total balance of the contract minus the DAO // royalties owed. uint256 _creatorRoyaltiesOwed = _contractBalance.sub(_daoRoyaltiesOwed); if (_creatorRoyaltiesOwed > 0) { (bool sent, ) = creatorAddress.call{ value: _creatorRoyaltiesOwed }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to creator address"); } if (_daoRoyaltiesOwed > 0) { (bool sent, ) = IOwnable(address(hashesToken)).owner().call{ value: _daoRoyaltiesOwed }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to HashesDAO"); } emit Withdraw(_creatorRoyaltiesOwed, _daoRoyaltiesOwed); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || ERC721Enumerable.supportsInterface(interfaceId); } /** * @notice The function used to get the Hashes Collection token URI. * @param _tokenId The Hashes Collection token Id. */ function tokenURI(uint256 _tokenId) public view override initialized returns (string memory) { // Ensure that the token ID is valid and that the hash isn't empty. require(_tokenId < nonce, "CollectionNFTCloneableV1: Can't provide a token URI for a non-existent collection."); // Return the base token URI concatenated with the token ID. return string(abi.encodePacked(baseTokenURI, _toDecimalString(_tokenId))); } /** * @notice The function used to get the name of the Hashes Collection token */ function name() public view override initialized returns (string memory) { return tokenName; } /** * @notice The function used to get the symbol of the Hashes Collection token */ function symbol() public view override initialized returns (string memory) { return tokenSymbol; } function _toDecimalString(uint256 _value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } function safe64(uint256 n, string memory errorMessage) internal pure returns (uint64) { require(n < 2**64, errorMessage); return uint64(n); } function safe128(uint256 n, string memory errorMessage) internal pure returns (uint128) { require(n < 2**128, errorMessage); return uint128(n); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionFactory { function addImplementationAddress( bytes32 _hashedEcosystemName, address _implementationAddress, bool cloneable ) external; function createCollection(address _implementationAddress, bytes memory _initializationData) external; function setFactoryMaintainerAddress(address _factoryMaintainerAddress) external; function removeImplementationAddresses( bytes32[] memory _hashedEcosystemNames, address[] memory _implementationAddresses, uint256[] memory _indexes ) external; function removeCollection( address _implementationAddress, address _collectionAddress, uint256 _index ) external; function createEcosystemSettings(string memory _ecosystemName, bytes memory _settings) external; function updateEcosystemSettings(bytes32 _hashedEcosystemName, bytes memory _settings) external; function getEcosystemSettings(bytes32 _hashedEcosystemName, uint64 _blockNumber) external view returns (bytes memory); function getEcosystems() external view returns (bytes32[] memory); function getEcosystems(uint256 _start, uint256 _end) external view returns (bytes32[] memory); function getCollections(address _implementationAddress) external view returns (address[] memory); function getCollections( address _implementationAddress, uint256 _start, uint256 _end ) external view returns (address[] memory); function getImplementationAddresses(bytes32 _hashedEcosystemName) external view returns (address[] memory); function getImplementationAddresses( bytes32 _hashedEcosystemName, uint256 _start, uint256 _end ) external view returns (address[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollection { function verifyEcosystemSettings(bytes memory _settings) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IHashes } from "./IHashes.sol"; interface ICollectionCloneable { function initialize( IHashes _hashesToken, address _factoryMaintainerAddress, address _createCollectionCaller, bytes memory _initializationData ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionNFTCloneableV1 { function mint(uint256 _hashesTokenId) external payable; function burn(uint256 _tokenId) external; function completeSignatureBlock() external; function setBaseTokenURI(string memory _baseTokenURI) external; function setRoyaltyBps(uint16 _royaltyBps) external; function transferCreator(address _creatorAddress) external; function setSignatureBlockAddress(address _signatureBlockAddress) external; function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionNFTEligibilityPredicate { function isTokenEligibleToMint(uint256 _tokenId, uint256 _hashesTokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionNFTMintFeePredicate { function getTokenMintFee(uint256 _tokenId, uint256 _hashesTokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IHashes is IERC721Enumerable { function deactivateTokens( address _owner, uint256 _proposalId, bytes memory _signature ) external returns (uint256); function deactivated(uint256 _tokenId) external view returns (bool); function activationFee() external view returns (uint256); function verify( uint256 _tokenId, address _minter, string memory _phrase ) external view returns (bool); function getHash(uint256 _tokenId) external view returns (bytes32); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IOwnable { function renounceOwnership() external; function transferOwnership(address newOwner) external; function owner() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/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. * * This is a modified version of the openzeppelin Ownable contract which works * with the cloneable contract pattern. Instead of initializing ownership in the * constructor, we have an empty constructor and then perform setup in the * initializeOwnership function. */ abstract contract OwnableCloneable is Context { bool ownableInitialized; address private _owner; modifier ownershipInitialized() { require(ownableInitialized, "OwnableCloneable: hasn't been initialized yet."); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the initialize caller as the initial owner. */ function initializeOwnership(address initialOwner) public virtual { require(!ownableInitialized, "OwnableCloneable: already initialized."); ownableInitialized = true; _setOwner(initialOwner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual ownershipInitialized returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "OwnableCloneable: 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 ownershipInitialized 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 ownershipInitialized onlyOwner { require(newOwner != address(0), "OwnableCloneable: new owner is the zero address"); _setOwner(newOwner); } // This is set to internal so overriden versions of renounce/transfer ownership // can also be carried out by DAO address. function _setOwner(address newOwner) internal ownershipInitialized { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
* @notice The function allows the token owner or approved address to burn the token. @param _tokenId The token Id to be burned./
function burn(uint256 _tokenId) external override initialized { require( _isApprovedOrOwner(_msgSender(), _tokenId), "CollectionNFTCloneableV1: caller is not owner nor approved." ); _burn(_tokenId); emit Burned(_msgSender(), _tokenId); }
9,942,444
[ 1, 1986, 445, 5360, 326, 1147, 3410, 578, 20412, 1758, 358, 18305, 326, 1147, 18, 225, 389, 2316, 548, 1021, 1147, 3124, 358, 506, 18305, 329, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 3849, 6454, 288, 203, 3639, 2583, 12, 203, 5411, 389, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 389, 2316, 548, 3631, 203, 5411, 315, 2532, 50, 4464, 10930, 429, 58, 21, 30, 4894, 353, 486, 3410, 12517, 20412, 1199, 203, 3639, 11272, 203, 3639, 389, 70, 321, 24899, 2316, 548, 1769, 203, 203, 3639, 3626, 605, 321, 329, 24899, 3576, 12021, 9334, 389, 2316, 548, 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 ]
/* Author: Victor Mezrin [email protected] */ pragma solidity ^0.4.24; /** * @title CommonModifiersInterface * @dev Base contract which contains common checks. */ contract CommonModifiersInterface { /** * @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _targetAddress) internal constant returns (bool); /** * @dev modifier to allow actions only when the _targetAddress is a contract. */ modifier onlyContractAddress(address _targetAddress) { require(isContract(_targetAddress) == true); _; } } /** * @title CommonModifiers * @dev Base contract which contains common checks. */ contract CommonModifiers is CommonModifiersInterface { /** * @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _targetAddress) internal constant returns (bool) { require (_targetAddress != address(0x0)); uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_targetAddress) } return (length > 0); } } /** * @title AssetIDInterface * @dev Interface of a contract that assigned to an asset (JNT, JUSD etc.) * @dev Contracts for the same asset (like JNT, JUSD etc.) will have the same AssetID. * @dev This will help to avoid misconfiguration of contracts */ contract AssetIDInterface { function getAssetID() public constant returns (string); function getAssetIDHash() public constant returns (bytes32); } /** * @title AssetID * @dev Base contract implementing AssetIDInterface */ contract AssetID is AssetIDInterface { /* Storage */ string assetID; /* Constructor */ constructor (string _assetID) public { require(bytes(_assetID).length > 0); assetID = _assetID; } /* Getters */ function getAssetID() public constant returns (string) { return assetID; } function getAssetIDHash() public constant returns (bytes32) { return keccak256(assetID); } } /** * @title OwnableInterface * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableInterface { /** * @dev The getter for "owner" contract variable */ function getOwner() public constant returns (address); /** * @dev Throws if called by any account other than the current owner. */ modifier onlyOwner() { require (msg.sender == getOwner()); _; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is OwnableInterface { /* Storage */ address owner = address(0x0); address proposedOwner = address(0x0); /* Events */ event OwnerAssignedEvent(address indexed newowner); event OwnershipOfferCreatedEvent(address indexed currentowner, address indexed proposedowner); event OwnershipOfferAcceptedEvent(address indexed currentowner, address indexed proposedowner); event OwnershipOfferCancelledEvent(address indexed currentowner, address indexed proposedowner); /** * @dev The constructor sets the initial `owner` to the passed account. */ constructor () public { owner = msg.sender; emit OwnerAssignedEvent(owner); } /** * @dev Old owner requests transfer ownership to the new owner. * @param _proposedOwner The address to transfer ownership to. */ function createOwnershipOffer(address _proposedOwner) external onlyOwner { require (proposedOwner == address(0x0)); require (_proposedOwner != address(0x0)); require (_proposedOwner != address(this)); proposedOwner = _proposedOwner; emit OwnershipOfferCreatedEvent(owner, _proposedOwner); } /** * @dev Allows the new owner to accept an ownership offer to contract control. */ //noinspection UnprotectedFunction function acceptOwnershipOffer() external { require (proposedOwner != address(0x0)); require (msg.sender == proposedOwner); address _oldOwner = owner; owner = proposedOwner; proposedOwner = address(0x0); emit OwnerAssignedEvent(owner); emit OwnershipOfferAcceptedEvent(_oldOwner, owner); } /** * @dev Old owner cancels transfer ownership to the new owner. */ function cancelOwnershipOffer() external { require (proposedOwner != address(0x0)); require (msg.sender == owner || msg.sender == proposedOwner); address _oldProposedOwner = proposedOwner; proposedOwner = address(0x0); emit OwnershipOfferCancelledEvent(owner, _oldProposedOwner); } /** * @dev The getter for "owner" contract variable */ function getOwner() public constant returns (address) { return owner; } /** * @dev The getter for "proposedOwner" contract variable */ function getProposedOwner() public constant returns (address) { return proposedOwner; } } /** * @title ManageableInterface * @dev Contract that allows to grant permissions to any address * @dev In real life we are no able to perform all actions with just one Ethereum address * @dev because risks are too high. * @dev Instead owner delegates rights to manage an contract to the different addresses and * @dev stay able to revoke permissions at any time. */ contract ManageableInterface { /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed(address _manager, string _permissionName) public constant returns (bool); /** * @dev Modifier to use in derived contracts */ modifier onlyAllowedManager(string _permissionName) { require(isManagerAllowed(msg.sender, _permissionName) == true); _; } } contract Manageable is OwnableInterface, ManageableInterface { /* Storage */ mapping (address => bool) managerEnabled; // hard switch for a manager - on/off mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions /* Events */ event ManagerEnabledEvent(address indexed manager); event ManagerDisabledEvent(address indexed manager); event ManagerPermissionGrantedEvent(address indexed manager, bytes32 permission); event ManagerPermissionRevokedEvent(address indexed manager, bytes32 permission); /* Configure contract */ /** * @dev Function to add new manager * @param _manager address New manager */ function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == false); managerEnabled[_manager] = true; emit ManagerEnabledEvent(_manager); } /** * @dev Function to remove existing manager * @param _manager address Existing manager */ function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == true); managerEnabled[_manager] = false; emit ManagerDisabledEvent(_manager); } /** * @dev Function to grant new permission to the manager * @param _manager address Existing manager * @param _permissionName string Granted permission name */ function grantManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == false); managerPermissions[_manager][_permissionName] = true; emit ManagerPermissionGrantedEvent(_manager, keccak256(_permissionName)); } /** * @dev Function to revoke permission of the manager * @param _manager address Existing manager * @param _permissionName string Revoked permission name */ function revokeManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == true); managerPermissions[_manager][_permissionName] = false; emit ManagerPermissionRevokedEvent(_manager, keccak256(_permissionName)); } /* Getters */ /** * @dev Function to check manager status * @param _manager address Manager`s address * @return True if manager is enabled */ function isManagerEnabled( address _manager ) public constant onlyValidManagerAddress(_manager) returns (bool) { return managerEnabled[_manager]; } /** * @dev Function to check permissions of a manager * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager has been granted needed permission */ function isPermissionGranted( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return managerPermissions[_manager][_permissionName]; } /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]); } /* Helpers */ /** * @dev Modifier to check manager address */ modifier onlyValidManagerAddress(address _manager) { require(_manager != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidPermissionName(string _permissionName) { require(bytes(_permissionName).length != 0); _; } } /** * @title PausableInterface * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract PausableInterface { /** * Events */ event PauseEvent(); event UnpauseEvent(); /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() public; /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() public; /** * @dev The getter for "paused" contract variable */ function getPaused() public constant returns (bool); /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenContractNotPaused() { require(getPaused() == false); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenContractPaused { require(getPaused() == true); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract Pausable is ManageableInterface, PausableInterface { /** * Storage */ bool paused = true; /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() public onlyAllowedManager('pause_contract') whenContractNotPaused { paused = true; emit PauseEvent(); } /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() public onlyAllowedManager('unpause_contract') whenContractPaused { paused = false; emit UnpauseEvent(); } /** * @dev The getter for "paused" contract variable */ function getPaused() public constant returns (bool) { return paused; } } /** * @title BytecodeExecutorInterface interface * @dev Implementation of a contract that execute any bytecode on behalf of the contract * @dev Last resort for the immutable and not-replaceable contract :) */ contract BytecodeExecutorInterface { /* Events */ event CallExecutedEvent(address indexed target, uint256 suppliedGas, uint256 ethValue, bytes32 transactionBytecodeHash); event DelegatecallExecutedEvent(address indexed target, uint256 suppliedGas, bytes32 transactionBytecodeHash); /* Functions */ function executeCall(address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode) external; function executeDelegatecall(address _target, uint256 _suppliedGas, bytes _transactionBytecode) external; } /** * @title BytecodeExecutor * @dev Implementation of a contract that execute any bytecode on behalf of the contract * @dev Last resort for the immutable and not-replaceable contract :) */ contract BytecodeExecutor is ManageableInterface, BytecodeExecutorInterface { /* Storage */ bool underExecution = false; /* BytecodeExecutorInterface */ function executeCall( address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode ) external onlyAllowedManager('execute_call') { require(underExecution == false); underExecution = true; // Avoid recursive calling _target.call.gas(_suppliedGas).value(_ethValue)(_transactionBytecode); underExecution = false; emit CallExecutedEvent(_target, _suppliedGas, _ethValue, keccak256(_transactionBytecode)); } function executeDelegatecall( address _target, uint256 _suppliedGas, bytes _transactionBytecode ) external onlyAllowedManager('execute_delegatecall') { require(underExecution == false); underExecution = true; // Avoid recursive calling _target.delegatecall.gas(_suppliedGas)(_transactionBytecode); underExecution = false; emit DelegatecallExecutedEvent(_target, _suppliedGas, keccak256(_transactionBytecode)); } } contract CrydrViewBaseInterface { /* Events */ event CrydrControllerChangedEvent(address indexed crydrcontroller); /* Configuration */ function setCrydrController(address _crydrController) external; function getCrydrController() public constant returns (address); function getCrydrViewStandardName() public constant returns (string); function getCrydrViewStandardNameHash() public constant returns (bytes32); } /** * @title CrydrViewERC20MintableInterface * @dev Contract is able to create Mint/Burn events with the cal from controller */ contract CrydrViewERC20MintableInterface { event MintEvent(address indexed owner, uint256 value); event BurnEvent(address indexed owner, uint256 value); function emitMintEvent(address _owner, uint256 _value) external; function emitBurnEvent(address _owner, uint256 _value) external; } /** * @title CrydrViewERC20LoggableInterface * @dev Contract is able to create Transfer/Approval events with the cal from controller */ contract CrydrViewERC20LoggableInterface { function emitTransferEvent(address _from, address _to, uint256 _value) external; function emitApprovalEvent(address _owner, address _spender, uint256 _value) external; } /** * @title CrydrStorageBalanceInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageBalanceInterface { /* Events */ event AccountBalanceIncreasedEvent(address indexed account, uint256 value); event AccountBalanceDecreasedEvent(address indexed account, uint256 value); /* Low-level change of balance. Implied that totalSupply kept in sync. */ function increaseBalance(address _account, uint256 _value) public; function decreaseBalance(address _account, uint256 _value) public; function getBalance(address _account) public constant returns (uint256); function getTotalSupply() public constant returns (uint256); } /** * @title CrydrStorageBlocksInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageBlocksInterface { /* Events */ event AccountBlockedEvent(address indexed account); event AccountUnblockedEvent(address indexed account); event AccountFundsBlockedEvent(address indexed account, uint256 value); event AccountFundsUnblockedEvent(address indexed account, uint256 value); /* Low-level change of blocks and getters */ function blockAccount(address _account) public; function unblockAccount(address _account) public; function getAccountBlocks(address _account) public constant returns (uint256); function blockAccountFunds(address _account, uint256 _value) public; function unblockAccountFunds(address _account, uint256 _value) public; function getAccountBlockedFunds(address _account) public constant returns (uint256); } /** * @title CrydrStorageAllowanceInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageAllowanceInterface { /* Events */ event AccountAllowanceIncreasedEvent(address indexed owner, address indexed spender, uint256 value); event AccountAllowanceDecreasedEvent(address indexed owner, address indexed spender, uint256 value); /* Low-level change of allowance */ function increaseAllowance(address _owner, address _spender, uint256 _value) public; function decreaseAllowance(address _owner, address _spender, uint256 _value) public; function getAllowance(address _owner, address _spender) public constant returns (uint256); } /** * @title CrydrStorageERC20Interface interface * @dev Interface of a contract that manages balance of an CryDR and have optimization for ERC20 controllers */ contract CrydrStorageERC20Interface { /* Events */ event CrydrTransferredEvent(address indexed from, address indexed to, uint256 value); event CrydrTransferredFromEvent(address indexed spender, address indexed from, address indexed to, uint256 value); event CrydrSpendingApprovedEvent(address indexed owner, address indexed spender, uint256 value); /* ERC20 optimization. _msgsender - account that invoked CrydrView */ function transfer(address _msgsender, address _to, uint256 _value) public; function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public; function approve(address _msgsender, address _spender, uint256 _value) public; } /** * @title CrydrControllerBaseInterface interface * @dev Interface of a contract that implement business-logic of an CryDR, mediates CryDR views and storage */ contract CrydrControllerBaseInterface { /* Events */ event CrydrStorageChangedEvent(address indexed crydrstorage); event CrydrViewAddedEvent(address indexed crydrview, bytes32 standardname); event CrydrViewRemovedEvent(address indexed crydrview, bytes32 standardname); /* Configuration */ function setCrydrStorage(address _newStorage) external; function getCrydrStorageAddress() public constant returns (address); function setCrydrView(address _newCrydrView, string _viewApiStandardName) external; function removeCrydrView(string _viewApiStandardName) external; function getCrydrViewAddress(string _viewApiStandardName) public constant returns (address); function isCrydrViewAddress(address _crydrViewAddress) public constant returns (bool); function isCrydrViewRegistered(string _viewApiStandardName) public constant returns (bool); /* Helpers */ modifier onlyValidCrydrViewStandardName(string _viewApiStandard) { require(bytes(_viewApiStandard).length > 0); _; } modifier onlyCrydrView() { require(isCrydrViewAddress(msg.sender) == true); _; } } /** * @title CrydrControllerBase * @dev Implementation of a contract with business-logic of an CryDR, mediates CryDR views and storage */ contract CrydrControllerBase is CommonModifiersInterface, ManageableInterface, PausableInterface, CrydrControllerBaseInterface { /* Storage */ address crydrStorage = address(0x0); mapping (string => address) crydrViewsAddresses; mapping (address => bool) isRegisteredView; /* CrydrControllerBaseInterface */ function setCrydrStorage( address _crydrStorage ) external onlyContractAddress(_crydrStorage) onlyAllowedManager('set_crydr_storage') whenContractPaused { require(_crydrStorage != address(this)); require(_crydrStorage != address(crydrStorage)); crydrStorage = _crydrStorage; emit CrydrStorageChangedEvent(_crydrStorage); } function getCrydrStorageAddress() public constant returns (address) { return address(crydrStorage); } function setCrydrView( address _newCrydrView, string _viewApiStandardName ) external onlyContractAddress(_newCrydrView) onlyValidCrydrViewStandardName(_viewApiStandardName) onlyAllowedManager('set_crydr_view') whenContractPaused { require(_newCrydrView != address(this)); require(crydrViewsAddresses[_viewApiStandardName] == address(0x0)); CrydrViewBaseInterface crydrViewInstance = CrydrViewBaseInterface(_newCrydrView); bytes32 standardNameHash = crydrViewInstance.getCrydrViewStandardNameHash(); require(standardNameHash == keccak256(_viewApiStandardName)); crydrViewsAddresses[_viewApiStandardName] = _newCrydrView; isRegisteredView[_newCrydrView] = true; emit CrydrViewAddedEvent(_newCrydrView, keccak256(_viewApiStandardName)); } function removeCrydrView( string _viewApiStandardName ) external onlyValidCrydrViewStandardName(_viewApiStandardName) onlyAllowedManager('remove_crydr_view') whenContractPaused { require(crydrViewsAddresses[_viewApiStandardName] != address(0x0)); address removedView = crydrViewsAddresses[_viewApiStandardName]; // make changes to the storage crydrViewsAddresses[_viewApiStandardName] == address(0x0); isRegisteredView[removedView] = false; emit CrydrViewRemovedEvent(removedView, keccak256(_viewApiStandardName)); } function getCrydrViewAddress( string _viewApiStandardName ) public constant onlyValidCrydrViewStandardName(_viewApiStandardName) returns (address) { require(crydrViewsAddresses[_viewApiStandardName] != address(0x0)); return crydrViewsAddresses[_viewApiStandardName]; } function isCrydrViewAddress( address _crydrViewAddress ) public constant returns (bool) { require(_crydrViewAddress != address(0x0)); return isRegisteredView[_crydrViewAddress]; } function isCrydrViewRegistered( string _viewApiStandardName ) public constant onlyValidCrydrViewStandardName(_viewApiStandardName) returns (bool) { return (crydrViewsAddresses[_viewApiStandardName] != address(0x0)); } } /** * @title CrydrControllerBlockableInterface interface * @dev Interface of a contract that allows block/unlock accounts */ contract CrydrControllerBlockableInterface { /* blocking/unlocking */ function blockAccount(address _account) public; function unblockAccount(address _account) public; function blockAccountFunds(address _account, uint256 _value) public; function unblockAccountFunds(address _account, uint256 _value) public; } /** * @title CrydrControllerBlockable interface * @dev Implementation of a contract that allows blocking/unlocking accounts */ contract CrydrControllerBlockable is ManageableInterface, CrydrControllerBaseInterface, CrydrControllerBlockableInterface { /* blocking/unlocking */ function blockAccount( address _account ) public onlyAllowedManager('block_account') { CrydrStorageBlocksInterface(getCrydrStorageAddress()).blockAccount(_account); } function unblockAccount( address _account ) public onlyAllowedManager('unblock_account') { CrydrStorageBlocksInterface(getCrydrStorageAddress()).unblockAccount(_account); } function blockAccountFunds( address _account, uint256 _value ) public onlyAllowedManager('block_account_funds') { CrydrStorageBlocksInterface(getCrydrStorageAddress()).blockAccountFunds(_account, _value); } function unblockAccountFunds( address _account, uint256 _value ) public onlyAllowedManager('unblock_account_funds') { CrydrStorageBlocksInterface(getCrydrStorageAddress()).unblockAccountFunds(_account, _value); } } /** * @title CrydrControllerMintableInterface interface * @dev Interface of a contract that allows minting/burning of tokens */ contract CrydrControllerMintableInterface { /* Events */ event MintEvent(address indexed owner, uint256 value); event BurnEvent(address indexed owner, uint256 value); /* minting/burning */ function mint(address _account, uint256 _value) public; function burn(address _account, uint256 _value) public; } /** * @title CrydrControllerMintable interface * @dev Implementation of a contract that allows minting/burning of tokens * @dev We do not use events Transfer(0x0, owner, amount) for minting as described in the EIP20 * @dev because that are not transfers */ contract CrydrControllerMintable is ManageableInterface, PausableInterface, CrydrControllerBaseInterface, CrydrControllerMintableInterface { /* minting/burning */ function mint( address _account, uint256 _value ) public whenContractNotPaused onlyAllowedManager('mint_crydr') { // input parameters checked by the storage CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_account, _value); emit MintEvent(_account, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitMintEvent(_account, _value); CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(address(0x0), _account, _value); } } function burn( address _account, uint256 _value ) public whenContractNotPaused onlyAllowedManager('burn_crydr') { // input parameters checked by the storage CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_account, _value); emit BurnEvent(_account, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitBurnEvent(_account, _value); CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_account, address(0x0), _value); } } } /** * @title CrydrControllerERC20Interface interface * @dev Interface of a contract that implement business-logic of an ERC20 CryDR */ contract CrydrControllerERC20Interface { /* ERC20 support. _msgsender - account that invoked CrydrView */ function transfer(address _msgsender, address _to, uint256 _value) public; function getTotalSupply() public constant returns (uint256); function getBalance(address _owner) public constant returns (uint256); function approve(address _msgsender, address _spender, uint256 _value) public; function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public; function getAllowance(address _owner, address _spender) public constant returns (uint256); } /** * @title CrydrControllerERC20Interface interface * @dev Interface of a contract that implement business-logic of an ERC20 CryDR */ contract CrydrControllerERC20 is PausableInterface, CrydrControllerBaseInterface, CrydrControllerERC20Interface { /* ERC20 support. _msgsender - account that invoked CrydrView */ function transfer( address _msgsender, address _to, uint256 _value ) public onlyCrydrView whenContractNotPaused { CrydrStorageERC20Interface(getCrydrStorageAddress()).transfer(_msgsender, _to, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_msgsender, _to, _value); } } function getTotalSupply() public constant returns (uint256) { return CrydrStorageBalanceInterface(getCrydrStorageAddress()).getTotalSupply(); } function getBalance(address _owner) public constant returns (uint256) { return CrydrStorageBalanceInterface(getCrydrStorageAddress()).getBalance(_owner); } function approve( address _msgsender, address _spender, uint256 _value ) public onlyCrydrView whenContractNotPaused { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 // We decided to enforce users to set 0 before set new value uint256 allowance = CrydrStorageAllowanceInterface(getCrydrStorageAddress()).getAllowance(_msgsender, _spender); require((allowance > 0 && _value == 0) || (allowance == 0 && _value > 0)); CrydrStorageERC20Interface(getCrydrStorageAddress()).approve(_msgsender, _spender, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitApprovalEvent(_msgsender, _spender, _value); } } function transferFrom( address _msgsender, address _from, address _to, uint256 _value ) public onlyCrydrView whenContractNotPaused { CrydrStorageERC20Interface(getCrydrStorageAddress()).transferFrom(_msgsender, _from, _to, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value); } } function getAllowance(address _owner, address _spender) public constant returns (uint256 ) { return CrydrStorageAllowanceInterface(getCrydrStorageAddress()).getAllowance(_owner, _spender); } } /** * @title CrydrControllerForcedTransferInterface interface * @dev Interface of a contract that allows manager to transfer funds from one account to another */ contract CrydrControllerForcedTransferInterface { /* Events */ event ForcedTransferEvent(address indexed from, address indexed to, uint256 value); /* Methods */ function forcedTransfer(address _from, address _to, uint256 _value) public; function forcedTransferAll(address _from, address _to) public; } /** * @title CrydrControllerForcedTransfer * @dev Implementation of a contract that allows manager to transfer funds from one account to another */ contract CrydrControllerForcedTransfer is ManageableInterface, PausableInterface, CrydrControllerBaseInterface, CrydrControllerForcedTransferInterface { /* minting/burning */ function forcedTransfer( address _from, address _to, uint256 _value ) public whenContractNotPaused onlyAllowedManager('forced_transfer') { // input parameters checked by the storage CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_from, _value); CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_to, _value); emit ForcedTransferEvent(_from, _to, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value); } } function forcedTransferAll( address _from, address _to ) public whenContractNotPaused onlyAllowedManager('forced_transfer') { // input parameters checked by the storage uint256 value = CrydrStorageBalanceInterface(getCrydrStorageAddress()).getBalance(_from); CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_from, value); CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_to, value); emit ForcedTransferEvent(_from, _to, value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, value); } } } /** * @title JNTPaymentGatewayInterface * @dev Allows to charge users by JNT */ contract JNTPaymentGatewayInterface { /* Events */ event JNTChargedEvent(address indexed payableservice, address indexed from, address indexed to, uint256 value); /* Actions */ function chargeJNT(address _from, address _to, uint256 _value) public; } /** * @title JNTPaymentGateway * @dev Allows to charge users by JNT */ contract JNTPaymentGateway is ManageableInterface, CrydrControllerBaseInterface, JNTPaymentGatewayInterface { function chargeJNT( address _from, address _to, uint256 _value ) public onlyAllowedManager('jnt_payable_service') { CrydrStorageERC20Interface(getCrydrStorageAddress()).transfer(_from, _to, _value); emit JNTChargedEvent(msg.sender, _from, _to, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value); } } } /** * @title JNTController * @dev Mediates views and storage of JNT, provides additional methods for Jibrel contracts */ contract JNTController is CommonModifiers, AssetID, Ownable, Manageable, Pausable, BytecodeExecutor, CrydrControllerBase, CrydrControllerBlockable, CrydrControllerMintable, CrydrControllerERC20, CrydrControllerForcedTransfer, JNTPaymentGateway { /* Constructor */ constructor () AssetID('JNT') public {} }
input parameters checked by the storage
function burn( address _account, uint256 _value ) public whenContractNotPaused onlyAllowedManager('burn_crydr') { CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_account, _value); emit BurnEvent(_account, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitBurnEvent(_account, _value); CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_account, address(0x0), _value); } }
1,064,190
[ 1, 2630, 1472, 5950, 635, 326, 2502, 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, 225, 445, 18305, 12, 203, 565, 1758, 389, 4631, 16, 2254, 5034, 389, 1132, 203, 225, 262, 203, 565, 1071, 203, 565, 1347, 8924, 1248, 28590, 203, 565, 1338, 5042, 1318, 2668, 70, 321, 67, 71, 1176, 3069, 6134, 203, 225, 288, 203, 203, 565, 385, 1176, 3069, 3245, 13937, 1358, 12, 588, 39, 1176, 3069, 3245, 1887, 1435, 2934, 323, 11908, 13937, 24899, 4631, 16, 389, 1132, 1769, 203, 203, 565, 3626, 605, 321, 1133, 24899, 4631, 16, 389, 1132, 1769, 203, 565, 309, 261, 291, 39, 1176, 3069, 1767, 10868, 2668, 12610, 3462, 6134, 422, 638, 13, 288, 203, 1377, 385, 1176, 3069, 1767, 654, 39, 3462, 49, 474, 28628, 12, 588, 39, 1176, 3069, 1767, 1887, 2668, 12610, 3462, 6134, 2934, 18356, 38, 321, 1133, 24899, 4631, 16, 389, 1132, 1769, 203, 1377, 385, 1176, 3069, 1767, 654, 39, 3462, 1343, 8455, 1358, 12, 588, 39, 1176, 3069, 1767, 1887, 2668, 12610, 3462, 6134, 2934, 18356, 5912, 1133, 24899, 4631, 16, 1758, 12, 20, 92, 20, 3631, 389, 1132, 1769, 203, 565, 289, 203, 225, 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 ]
/* MIT License Copyright (c) 2021 Reflexer Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.7; import "./GebUniswapV3ManagerBase.sol"; abstract contract OracleLike { function priceSource() virtual public view returns (address); function getResultWithValidity() virtual public view returns (uint256, bool); } abstract contract OracleRelayerLike { function redemptionPrice() virtual public returns (uint256); function collateralTypes(bytes32) virtual public view returns ( OracleLike orcl, uint256 safetyCRatio, uint256 liquidationCRatio ); } contract GebUniswapV3OracleAdapter is OracleForUniswapLike { // --- Constants --- uint256 public constant WAD_COMPLEMENT = 10 ** 9; OracleRelayerLike public immutable oracleRelayer; bytes32 public immutable collateral; /** * @notice Constructor that sets initial parameters for this contract * @param _oracleRelayer The address of the oracleRelayer * @param _collateral The collateral for this oracle */ constructor(OracleRelayerLike _oracleRelayer, bytes32 _collateral) public { oracleRelayer = _oracleRelayer; collateral = _collateral; } /** * @notice Function to get both the redemption price and the other pool token's price * @return redemptionPrice a WAD representing the redemption price * @return collateralPrice a WAD representing the collateral price * @return valid a boolean indicating weather the contract is valid */ function getResultsWithValidity() public override returns (uint256, uint256, bool){ uint256 redemptionPrice = oracleRelayer.redemptionPrice(); (OracleLike priceSource, , ) = oracleRelayer.collateralTypes(collateral); (uint256 collateralPrice, bool valid) = priceSource.getResultWithValidity(); require(valid, "GebUniswapV3LiquidityManager/invalid-col-price-feed"); return (redemptionPrice / WAD_COMPLEMENT, collateralPrice, true); } }
* @notice Constructor that sets initial parameters for this contract @param _oracleRelayer The address of the oracleRelayer @param _collateral The collateral for this oracle/
constructor(OracleRelayerLike _oracleRelayer, bytes32 _collateral) public { oracleRelayer = _oracleRelayer; collateral = _collateral; }
5,524,303
[ 1, 6293, 716, 1678, 2172, 1472, 364, 333, 6835, 225, 389, 280, 16066, 1971, 1773, 1021, 1758, 434, 326, 20865, 1971, 1773, 225, 389, 12910, 2045, 287, 1021, 4508, 2045, 287, 364, 333, 20865, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 23601, 1971, 1773, 8804, 389, 280, 16066, 1971, 1773, 16, 1731, 1578, 389, 12910, 2045, 287, 13, 1071, 288, 203, 3639, 20865, 1971, 1773, 273, 389, 280, 16066, 1971, 1773, 31, 203, 3639, 4508, 2045, 287, 273, 389, 12910, 2045, 287, 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 ]
pragma solidity ^0.4.24; // Amis Dex OnChainOrderBook follows ERC20 Standards contract ERC20 { function totalSupply() constant returns (uint); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } // Amis Dex on-chain order book matching engine Version 0.1.2. // https://github.com/amisolution/ERC20-AMIS/contracts/OnChainOrderBookV012b.sol // This smart contract is a variation of a neat ERC20 token as base, ETH as quoted, // and standard fees with incentivized reward token. // This contract allows minPriceExponent, baseMinInitialSize, and baseMinRemainingSize // to be set at init() time appropriately for the token decimals and likely value. // contract OnChainOrderBookV012b { enum BookType { ERC20EthV1 } enum Direction { Invalid, Buy, Sell } enum Status { Unknown, Rejected, Open, Done, NeedsGas, Sending, // not used by contract - web UI only FailedSend, // not used by contract - web UI only FailedTxn // not used by contract - web UI only } enum ReasonCode { None, InvalidPrice, InvalidSize, InvalidTerms, InsufficientFunds, WouldTake, Unmatched, TooManyMatches, ClientCancel } enum Terms { GTCNoGasTopup, GTCWithGasTopup, ImmediateOrCancel, MakerOnly } struct Order { // these are immutable once placed: address client; uint16 price; // packed representation of side + price uint sizeBase; Terms terms; // these are mutable until Done or Rejected: Status status; ReasonCode reasonCode; uint128 executedBase; // gross amount executed in base currency (before fee deduction) uint128 executedCntr; // gross amount executed in quoted currency (before fee deduction) uint128 feesBaseOrCntr; // base for buy, cntr for sell uint128 feesRwrd; } struct OrderChain { uint128 firstOrderId; uint128 lastOrderId; } struct OrderChainNode { uint128 nextOrderId; uint128 prevOrderId; } // Rebuild the expected state of the contract given: // - ClientPaymentEvent log history // - ClientOrderEvent log history // - Calling getOrder for the other immutable order fields of orders referenced by ClientOrderEvent enum ClientPaymentEventType { Deposit, Withdraw, TransferFrom, Transfer } enum BalanceType { Base, Cntr, Rwrd } event ClientPaymentEvent( address indexed client, ClientPaymentEventType clientPaymentEventType, BalanceType balanceType, int clientBalanceDelta ); enum ClientOrderEventType { Create, Continue, Cancel } event ClientOrderEvent( address indexed client, ClientOrderEventType clientOrderEventType, uint128 orderId, uint maxMatches ); enum MarketOrderEventType { // orderCount++, depth += depthBase Add, // orderCount--, depth -= depthBase Remove, // orderCount--, depth -= depthBase, traded += tradeBase // (depth change and traded change differ when tiny remaining amount refunded) CompleteFill, // orderCount unchanged, depth -= depthBase, traded += tradeBase PartialFill } // Technically not needed but these events can be used to maintain an order book or // watch for fills. Note that the orderId and price are those of the maker. event MarketOrderEvent( uint256 indexed eventTimestamp, uint128 indexed orderId, MarketOrderEventType marketOrderEventType, uint16 price, uint depthBase, uint tradeBase ); // the base token (e.g. AMIS) ERC20 baseToken; // minimum order size (inclusive) uint baseMinInitialSize; // set at init // if following partial match, the remaining gets smaller than this, remove from Order Book and refund: // generally we make this 10% of baseMinInitialSize uint baseMinRemainingSize; // set at init // maximum order size (exclusive) // chosen so that even multiplied by the max price (or divided by the min price), // and then multiplied by ethRwrdRate, it still fits in 2^127, allowing us to save // some gas by storing executed + fee fields as uint128. // even with 18 decimals, this still allows order sizes up to 1,000,000,000. // if we encounter a token with e.g. 36 decimals we'll have to revisit ... uint constant baseMaxSize = 10 ** 30; // the counter currency or ETH traded pair // (no address because it is ETH) // avoid the book getting cluttered up with tiny amounts not worth the gas uint constant cntrMinInitialSize = 10 finney; // see comments for baseMaxSize uint constant cntrMaxSize = 10 ** 30; // the reward token that can be used to pay fees (AMIS / ORA / CRSW) ERC20 rwrdToken; // set at init // used to convert ETH amount to reward tokens when paying fee with reward tokens uint constant ethRwrdRate = 1000; // funds that belong to clients (base, counter, and reward) mapping (address => uint) balanceBaseForClient; mapping (address => uint) balanceCntrForClient; mapping (address => uint) balanceRwrdForClient; // fee charged on liquidity taken, expressed as a divisor // (e.g. 2000 means 1/2000, or 0.05%) uint constant feeDivisor = 2000; // fees charged are given to: address feeCollector; // set at init // all orders ever created mapping (uint128 => Order) orderForOrderId; // Effectively a compact mapping from price to whether there are any open orders at that price. // See "Price Calculation Constants" below as to why 85. uint256[85] occupiedPriceBitmaps; // These allow us to walk over the orders in the book at a given price level (and add more). mapping (uint16 => OrderChain) orderChainForOccupiedPrice; mapping (uint128 => OrderChainNode) orderChainNodeForOpenOrderId; // These allow a client to (reasonably) efficiently find their own orders // without relying on events (which even indexed are a bit expensive to search // and cannot be accessed from smart contracts). See walkOrders. mapping (address => uint128) mostRecentOrderIdForClient; mapping (uint128 => uint128) clientPreviousOrderIdBeforeOrderId; // Price Calculation Constants. // // We pack direction and price into a crafty decimal floating point representation // for efficient indexing by price, the main thing we lose by doing so is precision - // we only have 3 significant figures in our prices. // // An unpacked price consists of: // // direction - invalid / buy / sell // mantissa - ranges from 100 to 999 representing 0.100 to 0.999 // exponent - ranges from minimumPriceExponent to minimumPriceExponent + 11 // (e.g. -5 to +6 for a typical pair where minPriceExponent = -5) // // The packed representation has 21601 different price values: // // 0 = invalid (can be used as marker value) // 1 = buy at maximum price (0.999 * 10 ** 6) // ... = other buy prices in descending order // 5400 = buy at 1.00 // ... = other buy prices in descending order // 10800 = buy at minimum price (0.100 * 10 ** -5) // 10801 = sell at minimum price (0.100 * 10 ** -5) // ... = other sell prices in descending order // 16201 = sell at 1.00 // ... = other sell prices in descending order // 21600 = sell at maximum price (0.999 * 10 ** 6) // 21601+ = do not use // // If we want to map each packed price to a boolean value (which we do), // we require 85 256-bit words. Or 42.5 for each side of the book. int8 minPriceExponent; // set at init uint constant invalidPrice = 0; // careful: max = largest unpacked value, not largest packed value uint constant maxBuyPrice = 1; uint constant minBuyPrice = 10800; uint constant minSellPrice = 10801; uint constant maxSellPrice = 21600; // Constructor. // // Sets feeCollector to the creator. Creator needs to call init() to finish setup. // function OnChainOrderBookV012b() { address creator = msg.sender; feeCollector = creator; } // "Public" Management - set address of base and reward tokens. // // Can only be done once (normally immediately after creation) by the fee collector. // // Used instead of a constructor to make deployment easier. // // baseMinInitialSize is the minimum order size in token-wei; // the minimum resting size will be one tenth of that. // // minPriceExponent controls the range of prices supported by the contract; // the range will be 0.100*10**minPriceExponent to 0.999*10**(minPriceExponent + 11) // but careful; this is in token-wei : wei, ignoring the number of decimals of the token // e.g. -5 implies 1 token-wei worth between 0.100e-5 to 0.999e+6 wei // which implies same token:eth exchange rate if token decimals are 18 like eth, // but if token decimals are 8, that would imply 1 token worth 10 wei to 0.000999 ETH. // function init(ERC20 _baseToken, ERC20 _rwrdToken, uint _baseMinInitialSize, int8 _minPriceExponent) public { require(msg.sender == feeCollector); require(address(baseToken) == 0); require(address(_baseToken) != 0); require(address(rwrdToken) == 0); require(address(_rwrdToken) != 0); require(_baseMinInitialSize >= 10); require(_baseMinInitialSize < baseMaxSize / 1000000); require(_minPriceExponent >= -20 && _minPriceExponent <= 20); if (_minPriceExponent < 2) { require(_baseMinInitialSize >= 10 ** uint(3-int(minPriceExponent))); } baseMinInitialSize = _baseMinInitialSize; // dust prevention. truncation ok, know >= 10 baseMinRemainingSize = _baseMinInitialSize / 10; minPriceExponent = _minPriceExponent; // attempt to catch bad tokens: require(_baseToken.totalSupply() > 0); baseToken = _baseToken; require(_rwrdToken.totalSupply() > 0); rwrdToken = _rwrdToken; } // "Public" Management - change fee collector // // The new fee collector only gets fees charged after this point. // function changeFeeCollector(address newFeeCollector) public { address oldFeeCollector = feeCollector; require(msg.sender == oldFeeCollector); require(newFeeCollector != oldFeeCollector); feeCollector = newFeeCollector; } // Public Info View - what is being traded here, what are the limits? // function getBookInfo() public constant returns ( BookType _bookType, address _baseToken, address _rwrdToken, uint _baseMinInitialSize, uint _cntrMinInitialSize, int8 _minPriceExponent, uint _feeDivisor, address _feeCollector ) { return ( BookType.ERC20EthV1, address(baseToken), address(rwrdToken), baseMinInitialSize, // can assume min resting size is one tenth of this cntrMinInitialSize, minPriceExponent, feeDivisor, feeCollector ); } // Public Funds View - get balances held by contract on behalf of the client, // or balances approved for deposit but not yet claimed by the contract. // // Excludes funds in open orders. // // Helps a web ui get a consistent snapshot of balances. // // It would be nice to return the off-exchange ETH balance too but there's a // bizarre bug in geth (and apparently as a result via MetaMask) that leads // to unpredictable behaviour when looking up client balances in constant // functions - see e.g. https://github.com/ethereum/solidity/issues/2325 . // function getClientBalances(address client) public constant returns ( uint bookBalanceBase, uint bookBalanceCntr, uint bookBalanceRwrd, uint approvedBalanceBase, uint approvedBalanceRwrd, uint ownBalanceBase, uint ownBalanceRwrd ) { bookBalanceBase = balanceBaseForClient[client]; bookBalanceCntr = balanceCntrForClient[client]; bookBalanceRwrd = balanceRwrdForClient[client]; approvedBalanceBase = baseToken.allowance(client, address(this)); approvedBalanceRwrd = rwrdToken.allowance(client, address(this)); ownBalanceBase = baseToken.balanceOf(client); ownBalanceRwrd = rwrdToken.balanceOf(client); } // Public Funds moves - deposit previously-approved base tokens. // function transferFromBase() public { address client = msg.sender; address book = address(this); // we trust the ERC20 token contract not to do nasty things like call back into us - // if we cannot trust the token then why are we allowing it to be traded? uint amountBase = baseToken.allowance(client, book); require(amountBase > 0); // NB: needs change for older ERC20 tokens that don't return bool require(baseToken.transferFrom(client, book, amountBase)); // belt and braces assert(baseToken.allowance(client, book) == 0); balanceBaseForClient[client] += amountBase; ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Base, int(amountBase)); } // Public Funds moves - withdraw base tokens (as a transfer). // function transferBase(uint amountBase) public { address client = msg.sender; require(amountBase > 0); require(amountBase <= balanceBaseForClient[client]); // overflow safe since we checked less than balance above balanceBaseForClient[client] -= amountBase; // we trust the ERC20 token contract not to do nasty things like call back into us - require(baseToken.transfer(client, amountBase)); ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Base, -int(amountBase)); } // Public Funds moves - deposit counter quoted currency (ETH or DAI). // function depositCntr() public payable { address client = msg.sender; uint amountCntr = msg.value; require(amountCntr > 0); // overflow safe - if someone owns pow(2,255) ETH we have bigger problems balanceCntrForClient[client] += amountCntr; ClientPaymentEvent(client, ClientPaymentEventType.Deposit, BalanceType.Cntr, int(amountCntr)); } // Public Funds Move - withdraw counter quoted currency (ETH or DAI). // function withdrawCntr(uint amountCntr) public { address client = msg.sender; require(amountCntr > 0); require(amountCntr <= balanceCntrForClient[client]); // overflow safe - checked less than balance above balanceCntrForClient[client] -= amountCntr; // safe - not enough gas to do anything interesting in fallback, already adjusted balance client.transfer(amountCntr); ClientPaymentEvent(client, ClientPaymentEventType.Withdraw, BalanceType.Cntr, -int(amountCntr)); } // Public Funds Move - deposit previously-approved incentivized reward tokens. // function transferFromRwrd() public { address client = msg.sender; address book = address(this); uint amountRwrd = rwrdToken.allowance(client, book); require(amountRwrd > 0); // we created the incentivized reward token so we know it supports ERC20 properly and is not evil require(rwrdToken.transferFrom(client, book, amountRwrd)); // belt and braces assert(rwrdToken.allowance(client, book) == 0); balanceRwrdForClient[client] += amountRwrd; ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Rwrd, int(amountRwrd)); } // Public Funds Manipulation - withdraw base tokens (as a transfer). // function transferRwrd(uint amountRwrd) public { address client = msg.sender; require(amountRwrd > 0); require(amountRwrd <= balanceRwrdForClient[client]); // overflow safe - checked less than balance above balanceRwrdForClient[client] -= amountRwrd; // we created the incentivized reward token so we know it supports ERC20 properly and is not evil require(rwrdToken.transfer(client, amountRwrd)); ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Rwrd, -int(amountRwrd)); } // Public Order View - get full details of an order. // // If the orderId does not exist, status will be Unknown. // function getOrder(uint128 orderId) public constant returns ( address client, uint16 price, uint sizeBase, Terms terms, Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr, uint feesBaseOrCntr, uint feesRwrd) { Order storage order = orderForOrderId[orderId]; return (order.client, order.price, order.sizeBase, order.terms, order.status, order.reasonCode, order.executedBase, order.executedCntr, order.feesBaseOrCntr, order.feesRwrd); } // Public Order View - get mutable details of an order. // // If the orderId does not exist, status will be Unknown. // function getOrderState(uint128 orderId) public constant returns ( Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr, uint feesBaseOrCntr, uint feesRwrd) { Order storage order = orderForOrderId[orderId]; return (order.status, order.reasonCode, order.executedBase, order.executedCntr, order.feesBaseOrCntr, order.feesRwrd); } // Public Order View - enumerate all recent orders + all open orders for one client. // // Not really designed for use from a smart contract transaction. // Baseline concept: // - client ensures order ids are generated so that most-signficant part is time-based; // - client decides they want all orders after a certain point-in-time, // and chooses minClosedOrderIdCutoff accordingly; // - before that point-in-time they just get open and needs gas orders // - client calls walkClientOrders with maybeLastOrderIdReturned = 0 initially; // - then repeats with the orderId returned by walkClientOrders; // - (and stops if it returns a zero orderId); // // Note that client is only used when maybeLastOrderIdReturned = 0. // function walkClientOrders( address client, uint128 maybeLastOrderIdReturned, uint128 minClosedOrderIdCutoff ) public constant returns ( uint128 orderId, uint16 price, uint sizeBase, Terms terms, Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr, uint feesBaseOrCntr, uint feesRwrd) { if (maybeLastOrderIdReturned == 0) { orderId = mostRecentOrderIdForClient[client]; } else { orderId = clientPreviousOrderIdBeforeOrderId[maybeLastOrderIdReturned]; } while (true) { if (orderId == 0) return; Order storage order = orderForOrderId[orderId]; if (orderId >= minClosedOrderIdCutoff) break; if (order.status == Status.Open || order.status == Status.NeedsGas) break; orderId = clientPreviousOrderIdBeforeOrderId[orderId]; } return (orderId, order.price, order.sizeBase, order.terms, order.status, order.reasonCode, order.executedBase, order.executedCntr, order.feesBaseOrCntr, order.feesRwrd); } // Internal Price Calculation - turn packed price into a friendlier unpacked price. // function unpackPrice(uint16 price) internal constant returns ( Direction direction, uint16 mantissa, int8 exponent ) { uint sidedPriceIndex = uint(price); uint priceIndex; if (sidedPriceIndex < 1 || sidedPriceIndex > maxSellPrice) { direction = Direction.Invalid; mantissa = 0; exponent = 0; return; } else if (sidedPriceIndex <= minBuyPrice) { direction = Direction.Buy; priceIndex = minBuyPrice - sidedPriceIndex; } else { direction = Direction.Sell; priceIndex = sidedPriceIndex - minSellPrice; } uint zeroBasedMantissa = priceIndex % 900; uint zeroBasedExponent = priceIndex / 900; mantissa = uint16(zeroBasedMantissa + 100); exponent = int8(zeroBasedExponent) + minPriceExponent; return; } // Internal Price Calculation - is a packed price on the buy side? // // Throws an error if price is invalid. // function isBuyPrice(uint16 price) internal constant returns (bool isBuy) { // yes, this looks odd, but max here is highest _unpacked_ price return price >= maxBuyPrice && price <= minBuyPrice; } // Internal Price Calculation - turn a packed buy price into a packed sell price. // // Invalid price remains invalid. // function computeOppositePrice(uint16 price) internal constant returns (uint16 opposite) { if (price < maxBuyPrice || price > maxSellPrice) { return uint16(invalidPrice); } else if (price <= minBuyPrice) { return uint16(maxSellPrice - (price - maxBuyPrice)); } else { return uint16(maxBuyPrice + (maxSellPrice - price)); } } // Internal Price Calculation - compute amount in counter currency that would // be obtained by selling baseAmount at the given unpacked price (if no fees). // // Notes: // - Does not validate price - caller must ensure valid. // - Could overflow producing very unexpected results if baseAmount very // large - caller must check this. // - This rounds the amount towards zero. // - May truncate to zero if baseAmount very small - potentially allowing // zero-cost buys or pointless sales - caller must check this. // function computeCntrAmountUsingUnpacked( uint baseAmount, uint16 mantissa, int8 exponent ) internal constant returns (uint cntrAmount) { if (exponent < 0) { return baseAmount * uint(mantissa) / 1000 / 10 ** uint(-exponent); } else { return baseAmount * uint(mantissa) / 1000 * 10 ** uint(exponent); } } // Internal Price Calculation - compute amount in counter currency that would // be obtained by selling baseAmount at the given packed price (if no fees). // // Notes: // - Does not validate price - caller must ensure valid. // - Direction of the packed price is ignored. // - Could overflow producing very unexpected results if baseAmount very // large - caller must check this. // - This rounds the amount towards zero (regardless of Buy or Sell). // - May truncate to zero if baseAmount very small - potentially allowing // zero-cost buys or pointless sales - caller must check this. // function computeCntrAmountUsingPacked( uint baseAmount, uint16 price ) internal constant returns (uint) { var (, mantissa, exponent) = unpackPrice(price); return computeCntrAmountUsingUnpacked(baseAmount, mantissa, exponent); } // Public Order Placement - create order and try to match it and/or add it to the book. // function createOrder( uint128 orderId, uint16 price, uint sizeBase, Terms terms, uint maxMatches ) public { address client = msg.sender; require(orderId != 0 && orderForOrderId[orderId].client == 0); ClientOrderEvent(client, ClientOrderEventType.Create, orderId, maxMatches); orderForOrderId[orderId] = Order(client, price, sizeBase, terms, Status.Unknown, ReasonCode.None, 0, 0, 0, 0); uint128 previousMostRecentOrderIdForClient = mostRecentOrderIdForClient[client]; mostRecentOrderIdForClient[client] = orderId; clientPreviousOrderIdBeforeOrderId[orderId] = previousMostRecentOrderIdForClient; Order storage order = orderForOrderId[orderId]; var (direction, mantissa, exponent) = unpackPrice(price); if (direction == Direction.Invalid) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidPrice; return; } if (sizeBase < baseMinInitialSize || sizeBase > baseMaxSize) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidSize; return; } uint sizeCntr = computeCntrAmountUsingUnpacked(sizeBase, mantissa, exponent); if (sizeCntr < cntrMinInitialSize || sizeCntr > cntrMaxSize) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidSize; return; } if (terms == Terms.MakerOnly && maxMatches != 0) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidTerms; return; } if (!debitFunds(client, direction, sizeBase, sizeCntr)) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InsufficientFunds; return; } processOrder(orderId, maxMatches); } // Public Order Placement - cancel order // function cancelOrder(uint128 orderId) public { address client = msg.sender; Order storage order = orderForOrderId[orderId]; require(order.client == client); Status status = order.status; if (status != Status.Open && status != Status.NeedsGas) { return; } ClientOrderEvent(client, ClientOrderEventType.Cancel, orderId, 0); if (status == Status.Open) { removeOpenOrderFromBook(orderId); MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Remove, order.price, order.sizeBase - order.executedBase, 0); } refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.ClientCancel); } // Public Order Placement - continue placing an order in 'NeedsGas' state // function continueOrder(uint128 orderId, uint maxMatches) public { address client = msg.sender; Order storage order = orderForOrderId[orderId]; require(order.client == client); if (order.status != Status.NeedsGas) { return; } ClientOrderEvent(client, ClientOrderEventType.Continue, orderId, maxMatches); order.status = Status.Unknown; processOrder(orderId, maxMatches); } // Internal Order Placement - remove a still-open order from the book. // // Caller's job to update/refund the order + raise event, this just // updates the order chain and bitmask. // // Too expensive to do on each resting order match - we only do this for an // order being cancelled. See matchWithOccupiedPrice for similar logic. // function removeOpenOrderFromBook(uint128 orderId) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; OrderChain storage orderChain = orderChainForOccupiedPrice[price]; OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId]; uint128 nextOrderId = orderChainNode.nextOrderId; uint128 prevOrderId = orderChainNode.prevOrderId; if (nextOrderId != 0) { OrderChainNode storage nextOrderChainNode = orderChainNodeForOpenOrderId[nextOrderId]; nextOrderChainNode.prevOrderId = prevOrderId; } else { orderChain.lastOrderId = prevOrderId; } if (prevOrderId != 0) { OrderChainNode storage prevOrderChainNode = orderChainNodeForOpenOrderId[prevOrderId]; prevOrderChainNode.nextOrderId = nextOrderId; } else { orderChain.firstOrderId = nextOrderId; } if (nextOrderId == 0 && prevOrderId == 0) { uint bmi = price / 256; // index into array of bitmaps uint bti = price % 256; // bit position within bitmap // we know was previously occupied so XOR clears occupiedPriceBitmaps[bmi] ^= 2 ** bti; } } // Internal Order Placement - credit funds received when taking liquidity from book // function creditExecutedFundsLessFees(uint128 orderId, uint originalExecutedBase, uint originalExecutedCntr) internal { Order storage order = orderForOrderId[orderId]; uint liquidityTakenBase = order.executedBase - originalExecutedBase; uint liquidityTakenCntr = order.executedCntr - originalExecutedCntr; // Normally we deduct the fee from the currency bought (base for buy, cntr for sell), // however we also accept reward tokens from the reward balance if it covers the fee, // with the reward amount converted from the ETH amount (the counter currency here) // at a fixed exchange rate. // Overflow safe since we ensure order size < 10^30 in both currencies (see baseMaxSize). // Can truncate to zero, which is fine. uint feesRwrd = liquidityTakenCntr / feeDivisor * ethRwrdRate; uint feesBaseOrCntr; address client = order.client; uint availRwrd = balanceRwrdForClient[client]; if (feesRwrd <= availRwrd) { balanceRwrdForClient[client] = availRwrd - feesRwrd; balanceRwrdForClient[feeCollector] = feesRwrd; // Need += rather than = because could have paid some fees earlier in NeedsGas situation. // Overflow safe since we ensure order size < 10^30 in both currencies (see baseMaxSize). // Can truncate to zero, which is fine. order.feesRwrd += uint128(feesRwrd); if (isBuyPrice(order.price)) { balanceBaseForClient[client] += liquidityTakenBase; } else { balanceCntrForClient[client] += liquidityTakenCntr; } } else if (isBuyPrice(order.price)) { // See comments in branch above re: use of += and overflow safety. feesBaseOrCntr = liquidityTakenBase / feeDivisor; balanceBaseForClient[order.client] += (liquidityTakenBase - feesBaseOrCntr); order.feesBaseOrCntr += uint128(feesBaseOrCntr); balanceBaseForClient[feeCollector] += feesBaseOrCntr; } else { // See comments in branch above re: use of += and overflow safety. feesBaseOrCntr = liquidityTakenCntr / feeDivisor; balanceCntrForClient[order.client] += (liquidityTakenCntr - feesBaseOrCntr); order.feesBaseOrCntr += uint128(feesBaseOrCntr); balanceCntrForClient[feeCollector] += feesBaseOrCntr; } } // Internal Order Placement - process a created and sanity checked order. // // Used both for new orders and for gas topup. // function processOrder(uint128 orderId, uint maxMatches) internal { Order storage order = orderForOrderId[orderId]; uint ourOriginalExecutedBase = order.executedBase; uint ourOriginalExecutedCntr = order.executedCntr; var (ourDirection,) = unpackPrice(order.price); uint theirPriceStart = (ourDirection == Direction.Buy) ? minSellPrice : maxBuyPrice; uint theirPriceEnd = computeOppositePrice(order.price); MatchStopReason matchStopReason = matchAgainstBook(orderId, theirPriceStart, theirPriceEnd, maxMatches); creditExecutedFundsLessFees(orderId, ourOriginalExecutedBase, ourOriginalExecutedCntr); if (order.terms == Terms.ImmediateOrCancel) { if (matchStopReason == MatchStopReason.Satisfied) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None); return; } else if (matchStopReason == MatchStopReason.MaxMatches) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.TooManyMatches); return; } else if (matchStopReason == MatchStopReason.BookExhausted) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.Unmatched); return; } } else if (order.terms == Terms.MakerOnly) { if (matchStopReason == MatchStopReason.MaxMatches) { refundUnmatchedAndFinish(orderId, Status.Rejected, ReasonCode.WouldTake); return; } else if (matchStopReason == MatchStopReason.BookExhausted) { enterOrder(orderId); return; } } else if (order.terms == Terms.GTCNoGasTopup) { if (matchStopReason == MatchStopReason.Satisfied) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None); return; } else if (matchStopReason == MatchStopReason.MaxMatches) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.TooManyMatches); return; } else if (matchStopReason == MatchStopReason.BookExhausted) { enterOrder(orderId); return; } } else if (order.terms == Terms.GTCWithGasTopup) { if (matchStopReason == MatchStopReason.Satisfied) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None); return; } else if (matchStopReason == MatchStopReason.MaxMatches) { order.status = Status.NeedsGas; return; } else if (matchStopReason == MatchStopReason.BookExhausted) { enterOrder(orderId); return; } } assert(false); // should not be possible to reach here } // Used internally to indicate why we stopped matching an order against the book. enum MatchStopReason { None, MaxMatches, Satisfied, PriceExhausted, BookExhausted } // Internal Order Placement - Match the given order against the book. // // Resting orders matched will be updated, removed from book and funds credited to their owners. // // Only updates the executedBase and executedCntr of the given order - caller is responsible // for crediting matched funds, charging fees, marking order as done / entering it into the book. // // matchStopReason returned will be one of MaxMatches, Satisfied or BookExhausted. // // Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order. // function matchAgainstBook( uint128 orderId, uint theirPriceStart, uint theirPriceEnd, uint maxMatches ) internal returns ( MatchStopReason matchStopReason ) { Order storage order = orderForOrderId[orderId]; uint bmi = theirPriceStart / 256; // index into array of bitmaps uint bti = theirPriceStart % 256; // bit position within bitmap uint bmiEnd = theirPriceEnd / 256; // last bitmap to search uint btiEnd = theirPriceEnd % 256; // stop at this bit in the last bitmap uint cbm = occupiedPriceBitmaps[bmi]; // original copy of current bitmap uint dbm = cbm; // dirty version of current bitmap where we may have cleared bits uint wbm = cbm >> bti; // working copy of current bitmap which we keep shifting // Optimized loops could render a better matching engine yet! bool removedLastAtPrice; matchStopReason = MatchStopReason.None; while (bmi < bmiEnd) { if (wbm == 0 || bti == 256) { if (dbm != cbm) { occupiedPriceBitmaps[bmi] = dbm; } bti = 0; bmi++; cbm = occupiedPriceBitmaps[bmi]; wbm = cbm; dbm = cbm; } else { if ((wbm & 1) != 0) { // careful - copy-and-pasted in loop below ... (removedLastAtPrice, maxMatches, matchStopReason) = matchWithOccupiedPrice(order, uint16(bmi * 256 + bti), maxMatches); if (removedLastAtPrice) { dbm ^= 2 ** bti; } if (matchStopReason == MatchStopReason.PriceExhausted) { matchStopReason = MatchStopReason.None; } else if (matchStopReason != MatchStopReason.None) { // we might still have changes in dbm to write back - see later break; } } bti += 1; wbm /= 2; } } if (matchStopReason == MatchStopReason.None) { // we've reached the last bitmap we need to search, // we'll stop at btiEnd not 256 this time. while (bti <= btiEnd && wbm != 0) { if ((wbm & 1) != 0) { // careful - copy-and-pasted in loop above ... (removedLastAtPrice, maxMatches, matchStopReason) = matchWithOccupiedPrice(order, uint16(bmi * 256 + bti), maxMatches); if (removedLastAtPrice) { dbm ^= 2 ** bti; } if (matchStopReason == MatchStopReason.PriceExhausted) { matchStopReason = MatchStopReason.None; } else if (matchStopReason != MatchStopReason.None) { break; } } bti += 1; wbm /= 2; } } // Careful - if we exited the first loop early, or we went into the second loop, // (luckily can't both happen) then we haven't flushed the dirty bitmap back to // storage - do that now if we need to. if (dbm != cbm) { occupiedPriceBitmaps[bmi] = dbm; } if (matchStopReason == MatchStopReason.None) { matchStopReason = MatchStopReason.BookExhausted; } } // Internal Order Placement. // // Match our order against up to maxMatches resting orders at the given price (which // is known by the caller to have at least one resting order). // // The matches (partial or complete) of the resting orders are recorded, and their // funds are credited. // // The on chain orderbook with resting orders is updated, but the occupied price bitmap is NOT - // the caller must clear the relevant bit if removedLastAtPrice = true is returned. // // Only updates the executedBase and executedCntr of our order - caller is responsible // for e.g. crediting our matched funds, updating status. // // Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order. // // Returns: // removedLastAtPrice: // true iff there are no longer any resting orders at this price - caller will need // to update the occupied price bitmap. // // matchesLeft: // maxMatches passed in minus the number of matches made by this call // // matchStopReason: // If our order is completely matched, matchStopReason will be Satisfied. // If our order is not completely matched, matchStopReason will be either: // MaxMatches (we are not allowed to match any more times) // or: // PriceExhausted (nothing left on the book at this exact price) // function matchWithOccupiedPrice( Order storage ourOrder, uint16 theirPrice, uint maxMatches ) internal returns ( bool removedLastAtPrice, uint matchesLeft, MatchStopReason matchStopReason) { matchesLeft = maxMatches; uint workingOurExecutedBase = ourOrder.executedBase; uint workingOurExecutedCntr = ourOrder.executedCntr; uint128 theirOrderId = orderChainForOccupiedPrice[theirPrice].firstOrderId; matchStopReason = MatchStopReason.None; while (true) { if (matchesLeft == 0) { matchStopReason = MatchStopReason.MaxMatches; break; } uint matchBase; uint matchCntr; (theirOrderId, matchBase, matchCntr, matchStopReason) = matchWithTheirs((ourOrder.sizeBase - workingOurExecutedBase), theirOrderId, theirPrice); workingOurExecutedBase += matchBase; workingOurExecutedCntr += matchCntr; matchesLeft -= 1; if (matchStopReason != MatchStopReason.None) { break; } } ourOrder.executedBase = uint128(workingOurExecutedBase); ourOrder.executedCntr = uint128(workingOurExecutedCntr); if (theirOrderId == 0) { orderChainForOccupiedPrice[theirPrice].firstOrderId = 0; orderChainForOccupiedPrice[theirPrice].lastOrderId = 0; removedLastAtPrice = true; } else { // NB: in some cases (e.g. maxMatches == 0) this is a no-op. orderChainForOccupiedPrice[theirPrice].firstOrderId = theirOrderId; orderChainNodeForOpenOrderId[theirOrderId].prevOrderId = 0; removedLastAtPrice = false; } } // Internal Order Placement. // // Match up to our remaining amount against a resting order in the book. // // The match (partial, complete or effectively-complete) of the resting order // is recorded, and their funds are credited. // // Their order is NOT removed from the book by this call - the caller must do that // if the nextTheirOrderId returned is not equal to the theirOrderId passed in. // // Returns: // // nextTheirOrderId: // If we did not completely match their order, will be same as theirOrderId. // If we completely matched their order, will be orderId of next order at the // same price - or zero if this was the last order and we've now filled it. // // matchStopReason: // If our order is completely matched, matchStopReason will be Satisfied. // If our order is not completely matched, matchStopReason will be either // PriceExhausted (if nothing left at this exact price) or None (if can continue). // function matchWithTheirs( uint ourRemainingBase, uint128 theirOrderId, uint16 theirPrice) internal returns ( uint128 nextTheirOrderId, uint matchBase, uint matchCntr, MatchStopReason matchStopReason) { Order storage theirOrder = orderForOrderId[theirOrderId]; uint theirRemainingBase = theirOrder.sizeBase - theirOrder.executedBase; if (ourRemainingBase < theirRemainingBase) { matchBase = ourRemainingBase; } else { matchBase = theirRemainingBase; } matchCntr = computeCntrAmountUsingPacked(matchBase, theirPrice); // It may seem a bit odd to stop here if our remaining amount is very small - // there could still be resting orders we can match it against. During network congestion gas // cost of matching each order can become quite high - potentially high enough to // wipe out the profit the taker hopes for from trading the tiny amount left. if ((ourRemainingBase - matchBase) < baseMinRemainingSize) { matchStopReason = MatchStopReason.Satisfied; } else { matchStopReason = MatchStopReason.None; } bool theirsDead = recordTheirMatch(theirOrder, theirOrderId, theirPrice, matchBase, matchCntr); if (theirsDead) { nextTheirOrderId = orderChainNodeForOpenOrderId[theirOrderId].nextOrderId; if (matchStopReason == MatchStopReason.None && nextTheirOrderId == 0) { matchStopReason = MatchStopReason.PriceExhausted; } } else { nextTheirOrderId = theirOrderId; } } // Internal Order Placement. // // Record match (partial or complete) of resting order, and credit them their funds. // // If their order is completely matched, the order is marked as done, // and "theirsDead" is returned as true. // // The order is NOT removed from the book by this call - the caller // must do that if theirsDead is true. // // No sanity checks are made - the caller must be sure the order is // not already done and has sufficient remaining. (Yes, we'd like to // check here too but we cannot afford the gas). // function recordTheirMatch( Order storage theirOrder, uint128 theirOrderId, uint16 theirPrice, uint matchBase, uint matchCntr ) internal returns (bool theirsDead) { // they are a maker so no fees // overflow safe - see comments about baseMaxSize // executedBase cannot go > sizeBase due to logic in matchWithTheirs theirOrder.executedBase += uint128(matchBase); theirOrder.executedCntr += uint128(matchCntr); if (isBuyPrice(theirPrice)) { // they have bought base (using the counter they already paid when creating the order) balanceBaseForClient[theirOrder.client] += matchBase; } else { // they have bought counter (using the base they already paid when creating the order) balanceCntrForClient[theirOrder.client] += matchCntr; } uint stillRemainingBase = theirOrder.sizeBase - theirOrder.executedBase; // avoid leaving tiny amounts in the book - refund remaining if too small if (stillRemainingBase < baseMinRemainingSize) { refundUnmatchedAndFinish(theirOrderId, Status.Done, ReasonCode.None); // someone building an UI on top needs to know how much was match and how much was refund MarketOrderEvent(block.timestamp, theirOrderId, MarketOrderEventType.CompleteFill, theirPrice, matchBase + stillRemainingBase, matchBase); return true; } else { MarketOrderEvent(block.timestamp, theirOrderId, MarketOrderEventType.PartialFill, theirPrice, matchBase, matchBase); return false; } } // Internal Order Placement. // // Refund any unmatched funds in an order (based on executed vs size) and move to a final state. // // The order is NOT removed from the book by this call and no event is raised. // // No sanity checks are made - the caller must be sure the order has not already been refunded. // function refundUnmatchedAndFinish(uint128 orderId, Status status, ReasonCode reasonCode) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; if (isBuyPrice(price)) { uint sizeCntr = computeCntrAmountUsingPacked(order.sizeBase, price); balanceCntrForClient[order.client] += sizeCntr - order.executedCntr; } else { balanceBaseForClient[order.client] += order.sizeBase - order.executedBase; } order.status = status; order.reasonCode = reasonCode; } // Internal Order Placement. // // Enter a not completely matched order into the book, marking the order as open. // // This updates the occupied price bitmap and chain. // // No sanity checks are made - the caller must be sure the order // has some unmatched amount and has been paid for! // function enterOrder(uint128 orderId) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; OrderChain storage orderChain = orderChainForOccupiedPrice[price]; OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId]; if (orderChain.firstOrderId == 0) { orderChain.firstOrderId = orderId; orderChain.lastOrderId = orderId; orderChainNode.nextOrderId = 0; orderChainNode.prevOrderId = 0; uint bitmapIndex = price / 256; uint bitIndex = price % 256; occupiedPriceBitmaps[bitmapIndex] |= (2 ** bitIndex); } else { uint128 existingLastOrderId = orderChain.lastOrderId; OrderChainNode storage existingLastOrderChainNode = orderChainNodeForOpenOrderId[existingLastOrderId]; orderChainNode.nextOrderId = 0; orderChainNode.prevOrderId = existingLastOrderId; existingLastOrderChainNode.nextOrderId = orderId; orderChain.lastOrderId = orderId; } MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Add, price, order.sizeBase - order.executedBase, 0); order.status = Status.Open; } // Internal Order Placement. // // Charge the client for the cost of placing an order in the given direction. // // Return true if successful, false otherwise. // function debitFunds( address client, Direction direction, uint sizeBase, uint sizeCntr ) internal returns (bool success) { if (direction == Direction.Buy) { uint availableCntr = balanceCntrForClient[client]; if (availableCntr < sizeCntr) { return false; } balanceCntrForClient[client] = availableCntr - sizeCntr; return true; } else if (direction == Direction.Sell) { uint availableBase = balanceBaseForClient[client]; if (availableBase < sizeBase) { return false; } balanceBaseForClient[client] = availableBase - sizeBase; return true; } else { return false; } } // Public Book View // // Intended for public book depth enumeration from web3 (or similar). // // Not suitable for use from a smart contract transaction - gas usage // could be very high if we have many orders at the same price. // // Start at the given inclusive price (and side) and walk down the book // (getting less aggressive) until we find some open orders or reach the // least aggressive price. // // Returns the price where we found the order(s), the depth at that price // (zero if none found), order count there, and the current blockNumber. // // (The blockNumber is handy if you're taking a snapshot which you intend // to keep up-to-date with the market order events). // // To walk through the on-chain orderbook, the caller should start by calling walkBook with the // most aggressive buy price (Buy @ 999000). // If the price returned is the least aggressive buy price (Buy @ 0.000001), // the side is complete. // Otherwise, call walkBook again with the (packed) price returned + 1. // Then repeat for the sell side, starting with Sell @ 0.000001 and stopping // when Sell @ 999000 is returned. // function walkBook(uint16 fromPrice) public constant returns ( uint16 price, uint depthBase, uint orderCount, uint blockNumber ) { uint priceStart = fromPrice; uint priceEnd = (isBuyPrice(fromPrice)) ? minBuyPrice : maxSellPrice; // See comments in matchAgainstBook re: how these crazy loops work. uint bmi = priceStart / 256; uint bti = priceStart % 256; uint bmiEnd = priceEnd / 256; uint btiEnd = priceEnd % 256; uint wbm = occupiedPriceBitmaps[bmi] >> bti; while (bmi < bmiEnd) { if (wbm == 0 || bti == 256) { bti = 0; bmi++; wbm = occupiedPriceBitmaps[bmi]; } else { if ((wbm & 1) != 0) { // careful - copy-pasted in below loop price = uint16(bmi * 256 + bti); (depthBase, orderCount) = sumDepth(orderChainForOccupiedPrice[price].firstOrderId); return (price, depthBase, orderCount, block.number); } bti += 1; wbm /= 2; } } // we've reached the last bitmap we need to search, stop at btiEnd not 256 this time. while (bti <= btiEnd && wbm != 0) { if ((wbm & 1) != 0) { // careful - copy-pasted in above loop price = uint16(bmi * 256 + bti); (depthBase, orderCount) = sumDepth(orderChainForOccupiedPrice[price].firstOrderId); return (price, depthBase, orderCount, block.number); } bti += 1; wbm /= 2; } return (uint16(priceEnd), 0, 0, block.number); } // Internal Book View. // // See walkBook - adds up open depth at a price starting from an // order which is assumed to be open. Careful - unlimited gas use. // function sumDepth(uint128 orderId) internal constant returns (uint depth, uint orderCount) { while (true) { Order storage order = orderForOrderId[orderId]; depth += order.sizeBase - order.executedBase; orderCount++; orderId = orderChainNodeForOpenOrderId[orderId].nextOrderId; if (orderId == 0) { return (depth, orderCount); } } } } // helper for automating book creation contract OnChainOrderBookV012bFactory { event BookCreated (address bookAddress); function OnChainOrderBookV012bFactory() { } function createBook(ERC20 _baseToken, ERC20 _rwrdToken, address _feeCollector, uint _baseMinInitialSize, int8 _minPriceExponent) public { OnChainOrderBookV012b book = new OnChainOrderBookV012b(); book.init(_baseToken, _rwrdToken, _baseMinInitialSize, _minPriceExponent); book.changeFeeCollector(_feeCollector); BookCreated(address(book)); } }
Internal Order Placement - remove a still-open order from the book. Caller's job to update/refund the order + raise event, this just updates the order chain and bitmask. Too expensive to do on each resting order match - we only do this for an order being cancelled. See matchWithOccupiedPrice for similar logic. we know was previously occupied so XOR clears
function removeOpenOrderFromBook(uint128 orderId) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; OrderChain storage orderChain = orderChainForOccupiedPrice[price]; OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId]; uint128 nextOrderId = orderChainNode.nextOrderId; uint128 prevOrderId = orderChainNode.prevOrderId; if (nextOrderId != 0) { OrderChainNode storage nextOrderChainNode = orderChainNodeForOpenOrderId[nextOrderId]; nextOrderChainNode.prevOrderId = prevOrderId; orderChain.lastOrderId = prevOrderId; } if (prevOrderId != 0) { OrderChainNode storage prevOrderChainNode = orderChainNodeForOpenOrderId[prevOrderId]; prevOrderChainNode.nextOrderId = nextOrderId; orderChain.firstOrderId = nextOrderId; } if (nextOrderId == 0 && prevOrderId == 0) { occupiedPriceBitmaps[bmi] ^= 2 ** bti; } }
914,687
[ 1, 3061, 4347, 28498, 300, 1206, 279, 4859, 17, 3190, 1353, 628, 326, 6978, 18, 20646, 1807, 1719, 358, 1089, 19, 1734, 1074, 326, 1353, 397, 1002, 871, 16, 333, 2537, 4533, 326, 1353, 2687, 471, 24941, 18, 15869, 19326, 358, 741, 603, 1517, 3127, 310, 1353, 845, 300, 732, 1338, 741, 333, 364, 392, 1353, 3832, 13927, 18, 2164, 845, 1190, 24269, 416, 2092, 5147, 364, 7281, 4058, 18, 732, 5055, 1703, 7243, 18928, 2092, 1427, 28086, 22655, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1206, 3678, 2448, 1265, 9084, 12, 11890, 10392, 20944, 13, 2713, 288, 203, 565, 4347, 2502, 1353, 273, 1353, 1290, 21303, 63, 1019, 548, 15533, 203, 565, 2254, 2313, 6205, 273, 1353, 18, 8694, 31, 203, 565, 4347, 3893, 2502, 1353, 3893, 273, 1353, 3893, 1290, 24269, 416, 2092, 5147, 63, 8694, 15533, 203, 565, 4347, 3893, 907, 2502, 1353, 3893, 907, 273, 1353, 3893, 907, 1290, 3678, 21303, 63, 1019, 548, 15533, 203, 565, 2254, 10392, 1024, 21303, 273, 1353, 3893, 907, 18, 4285, 21303, 31, 203, 565, 2254, 10392, 2807, 21303, 273, 1353, 3893, 907, 18, 10001, 21303, 31, 203, 565, 309, 261, 4285, 21303, 480, 374, 13, 288, 203, 1377, 4347, 3893, 907, 2502, 1024, 2448, 3893, 907, 273, 1353, 3893, 907, 1290, 3678, 21303, 63, 4285, 21303, 15533, 203, 1377, 1024, 2448, 3893, 907, 18, 10001, 21303, 273, 2807, 21303, 31, 203, 1377, 1353, 3893, 18, 2722, 21303, 273, 2807, 21303, 31, 203, 565, 289, 203, 565, 309, 261, 10001, 21303, 480, 374, 13, 288, 203, 1377, 4347, 3893, 907, 2502, 2807, 2448, 3893, 907, 273, 1353, 3893, 907, 1290, 3678, 21303, 63, 10001, 21303, 15533, 203, 1377, 2807, 2448, 3893, 907, 18, 4285, 21303, 273, 1024, 21303, 31, 203, 1377, 1353, 3893, 18, 3645, 21303, 273, 1024, 21303, 31, 203, 565, 289, 203, 565, 309, 261, 4285, 21303, 422, 374, 597, 2807, 21303, 422, 374, 13, 288, 203, 1377, 18928, 2092, 5147, 5775, 10711, 63, 70, 9197, 65, 10352, 576, 2826, 324, 9096, 31, 203, 565, 289, 2 ]
./full_match/1/0x5293fc632F3a42d0c0d5f34D91f384da0e0C824e/sources/Miyagi.sol
Max transaction 1% of Supply
maxTransaction = (maxSupply * 100) / 10000;
2,980,963
[ 1, 2747, 2492, 404, 9, 434, 3425, 1283, 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, 3639, 943, 3342, 273, 261, 1896, 3088, 1283, 380, 2130, 13, 342, 12619, 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 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "../BaseLogic.sol"; import "../vendor/ISwapRouter.sol"; /// @notice Trading assets on Uniswap V3 and 1Inch V4 DEXs contract Swap is BaseLogic { address immutable public uniswapRouter; address immutable public oneInch; /// @notice Params for Uniswap V3 exact input trade on a single pool /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountIn amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param deadline trade must complete before this timestamp /// @param fee uniswap pool fee to use /// @param sqrtPriceLimitX96 maximum acceptable price struct SwapUniExactInputSingleParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amountIn; uint amountOutMinimum; uint deadline; uint24 fee; uint160 sqrtPriceLimitX96; } /// @notice Params for Uniswap V3 exact input trade routed through multiple pools /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountIn amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param deadline trade must complete before this timestamp /// @param path list of pools to use for the trade struct SwapUniExactInputParams { uint subAccountIdIn; uint subAccountIdOut; uint amountIn; uint amountOutMinimum; uint deadline; bytes path; // list of pools to hop - constructed with uni SDK } /// @notice Params for Uniswap V3 exact output trade on a single pool /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountOut amount of token to buy /// @param amountInMaximum maximum amount of sold token /// @param deadline trade must complete before this timestamp /// @param fee uniswap pool fee to use /// @param sqrtPriceLimitX96 maximum acceptable price struct SwapUniExactOutputSingleParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amountOut; uint amountInMaximum; uint deadline; uint24 fee; uint160 sqrtPriceLimitX96; } /// @notice Params for Uniswap V3 exact output trade routed through multiple pools /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountOut amount of token to buy /// @param amountInMaximum maximum amount of sold token /// @param deadline trade must complete before this timestamp /// @param path list of pools to use for the trade struct SwapUniExactOutputParams { uint subAccountIdIn; uint subAccountIdOut; uint amountOut; uint amountInMaximum; uint deadline; bytes path; } /// @notice Params for 1Inch trade /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amount amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param payload call data passed to 1Inch contract struct Swap1InchParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amount; uint amountOutMinimum; bytes payload; } struct SwapCache { address accountIn; address accountOut; address eTokenIn; address eTokenOut; AssetCache assetCacheIn; AssetCache assetCacheOut; uint balanceIn; uint balanceOut; uint amountIn; uint amountOut; uint amountInternalIn; } constructor(bytes32 moduleGitCommit_, address uniswapRouter_, address oneInch_) BaseLogic(MODULEID__SWAP, moduleGitCommit_) { uniswapRouter = uniswapRouter_; oneInch = oneInch_; } /// @notice Execute Uniswap V3 exact input trade on a single pool /// @param params struct defining trade parameters function swapUniExactInputSingle(SwapUniExactInputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountIn, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_INPUT_SINGLE ); setWithdrawAmounts(swap, params.amountIn); Utils.safeApprove(params.underlyingIn, uniswapRouter, swap.amountIn); swap.amountOut = ISwapRouter(uniswapRouter).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: params.underlyingIn, tokenOut: params.underlyingOut, fee: params.fee, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountIn: swap.amountIn, amountOutMinimum: params.amountOutMinimum, sqrtPriceLimitX96: params.sqrtPriceLimitX96 }) ); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact input trade routed through multiple pools /// @param params struct defining trade parameters function swapUniExactInput(SwapUniExactInputParams memory params) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, false); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, params.amountIn, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_INPUT ); setWithdrawAmounts(swap, params.amountIn); Utils.safeApprove(underlyingIn, uniswapRouter, swap.amountIn); swap.amountOut = ISwapRouter(uniswapRouter).exactInput( ISwapRouter.ExactInputParams({ path: params.path, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountIn: swap.amountIn, amountOutMinimum: params.amountOutMinimum }) ); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact output trade on a single pool /// @param params struct defining trade parameters function swapUniExactOutputSingle(SwapUniExactOutputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE ); swap.amountOut = params.amountOut; doSwapUniExactOutputSingle(swap, params); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact output trade routed through multiple pools /// @param params struct defining trade parameters function swapUniExactOutput(SwapUniExactOutputParams memory params) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, true); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT ); swap.amountOut = params.amountOut; doSwapUniExactOutput(swap, params, underlyingIn); finalizeSwap(swap); } /// @notice Trade on Uniswap V3 single pool and repay debt with bought asset /// @param params struct defining trade parameters (amountOut is ignored) /// @param targetDebt amount of debt that is expected to remain after trade and repay (0 to repay full debt) function swapAndRepayUniSingle(SwapUniExactOutputSingleParams memory params, uint targetDebt) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, targetDebt, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY ); swap.amountOut = getRepayAmount(swap, targetDebt); doSwapUniExactOutputSingle(swap, params); finalizeSwapAndRepay(swap); } /// @notice Trade on Uniswap V3 through multiple pools pool and repay debt with bought asset /// @param params struct defining trade parameters (amountOut is ignored) /// @param targetDebt amount of debt that is expected to remain after trade and repay (0 to repay full debt) function swapAndRepayUni(SwapUniExactOutputParams memory params, uint targetDebt) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, true); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, targetDebt, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY ); swap.amountOut = getRepayAmount(swap, targetDebt); doSwapUniExactOutput(swap, params, underlyingIn); finalizeSwapAndRepay(swap); } /// @notice Execute 1Inch V4 trade /// @param params struct defining trade parameters function swap1Inch(Swap1InchParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amount, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__1INCH ); setWithdrawAmounts(swap, params.amount); Utils.safeApprove(params.underlyingIn, oneInch, swap.amountIn); (bool success, bytes memory result) = oneInch.call(params.payload); if (!success) revertBytes(result); swap.amountOut = abi.decode(result, (uint)); require(swap.amountOut >= params.amountOutMinimum, "e/swap/min-amount-out"); finalizeSwap(swap); } function initSwap( address underlyingIn, address underlyingOut, uint amount, uint subAccountIdIn, uint subAccountIdOut, uint swapType ) private returns (SwapCache memory swap) { require(underlyingIn != underlyingOut, "e/swap/same"); address msgSender = unpackTrailingParamMsgSender(); swap.accountIn = getSubAccount(msgSender, subAccountIdIn); swap.accountOut = getSubAccount(msgSender, subAccountIdOut); updateAverageLiquidity(swap.accountIn); if (swap.accountIn != swap.accountOut) updateAverageLiquidity(swap.accountOut); emit RequestSwap( swap.accountIn, swap.accountOut, underlyingIn, underlyingOut, amount, swapType ); swap.eTokenIn = underlyingLookup[underlyingIn].eTokenAddress; swap.eTokenOut = underlyingLookup[underlyingOut].eTokenAddress; AssetStorage storage assetStorageIn = eTokenLookup[swap.eTokenIn]; AssetStorage storage assetStorageOut = eTokenLookup[swap.eTokenOut]; require(swap.eTokenIn != address(0), "e/swap/in-market-not-activated"); require(swap.eTokenOut != address(0), "e/swap/out-market-not-activated"); swap.assetCacheIn = loadAssetCache(underlyingIn, assetStorageIn); swap.assetCacheOut = loadAssetCache(underlyingOut, assetStorageOut); swap.balanceIn = callBalanceOf(swap.assetCacheIn, address(this)) ; swap.balanceOut = callBalanceOf(swap.assetCacheOut, address(this)); } function doSwapUniExactOutputSingle(SwapCache memory swap, SwapUniExactOutputSingleParams memory params) private { Utils.safeApprove(params.underlyingIn, uniswapRouter, params.amountInMaximum); uint pulledAmountIn = ISwapRouter(uniswapRouter).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: params.underlyingIn, tokenOut: params.underlyingOut, fee: params.fee, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountOut: swap.amountOut, amountInMaximum: params.amountInMaximum, sqrtPriceLimitX96: params.sqrtPriceLimitX96 }) ); require(pulledAmountIn != type(uint).max, "e/swap/exact-out-amount-in"); setWithdrawAmounts(swap, pulledAmountIn); if (swap.amountIn < params.amountInMaximum) { Utils.safeApprove(params.underlyingIn, uniswapRouter, 0); } } function doSwapUniExactOutput(SwapCache memory swap, SwapUniExactOutputParams memory params, address underlyingIn) private { Utils.safeApprove(underlyingIn, uniswapRouter, params.amountInMaximum); uint pulledAmountIn = ISwapRouter(uniswapRouter).exactOutput( ISwapRouter.ExactOutputParams({ path: params.path, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountOut: swap.amountOut, amountInMaximum: params.amountInMaximum }) ); require(pulledAmountIn != type(uint).max, "e/swap/exact-out-amount-in"); setWithdrawAmounts(swap, pulledAmountIn); if (swap.amountIn < params.amountInMaximum) { Utils.safeApprove(underlyingIn, uniswapRouter, 0); } } function setWithdrawAmounts(SwapCache memory swap, uint amount) private view { (amount, swap.amountInternalIn) = withdrawAmounts(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.accountIn, amount); require(swap.assetCacheIn.poolSize >= amount, "e/swap/insufficient-pool-size"); swap.amountIn = amount / swap.assetCacheIn.underlyingDecimalsScaler; } function finalizeSwap(SwapCache memory swap) private { uint balanceIn = checkBalances(swap); processWithdraw(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.eTokenIn, swap.accountIn, swap.amountInternalIn, balanceIn); processDeposit(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.eTokenOut, swap.accountOut, swap.amountOut); // only checking outgoing account, deposit can't lower health score checkLiquidity(swap.accountIn); } function finalizeSwapAndRepay(SwapCache memory swap) private { uint balanceIn = checkBalances(swap); processWithdraw(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.eTokenIn, swap.accountIn, swap.amountInternalIn, balanceIn); processRepay(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.accountOut, swap.amountOut); // only checking outgoing account, repay can't lower health score checkLiquidity(swap.accountIn); } function processWithdraw(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amountInternal, uint balanceIn) private { assetCache.poolSize = decodeExternalAmount(assetCache, balanceIn); decreaseBalance(assetStorage, assetCache, eTokenAddress, account, amountInternal); logAssetStatus(assetCache); } function processDeposit(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) private { uint amountDecoded = decodeExternalAmount(assetCache, amount); uint amountInternal = underlyingAmountToBalance(assetCache, amountDecoded); assetCache.poolSize += amountDecoded; increaseBalance(assetStorage, assetCache, eTokenAddress, account, amountInternal); logAssetStatus(assetCache); } function processRepay(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) private { decreaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, decodeExternalAmount(assetCache, amount)); logAssetStatus(assetCache); } function checkBalances(SwapCache memory swap) private view returns (uint) { uint balanceIn = callBalanceOf(swap.assetCacheIn, address(this)); require(balanceIn == swap.balanceIn - swap.amountIn, "e/swap/balance-in"); require(callBalanceOf(swap.assetCacheOut, address(this)) == swap.balanceOut + swap.amountOut, "e/swap/balance-out"); return balanceIn; } function decodeUniPath(bytes memory path, bool isExactOutput) private pure returns (address, address) { require(path.length >= 20 + 3 + 20, "e/swap/uni-path-length"); require((path.length - 20) % 23 == 0, "e/swap/uni-path-format"); address token0 = toAddress(path, 0); address token1 = toAddress(path, path.length - 20); return isExactOutput ? (token1, token0) : (token0, token1); } function getRepayAmount(SwapCache memory swap, uint targetDebt) private view returns (uint) { uint owed = getCurrentOwed(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.accountOut) / swap.assetCacheOut.underlyingDecimalsScaler; require (owed > targetDebt, "e/swap/target-debt"); return owed - targetDebt; } function toAddress(bytes memory data, uint start) private pure returns (address result) { // assuming data length is already validated assembly { // borrowed from BytesLib https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol result := div(mload(add(add(data, 0x20), start)), 0x1000000000000000000000000) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; import "./BaseIRM.sol"; import "./Interfaces.sol"; import "./Utils.sol"; import "./vendor/RPow.sol"; import "./IRiskManager.sol"; abstract contract BaseLogic is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} // Account auth function getSubAccount(address primary, uint subAccountId) internal pure returns (address) { require(subAccountId < 256, "e/sub-account-id-too-big"); return address(uint160(primary) ^ uint160(subAccountId)); } function isSubAccountOf(address primary, address subAccount) internal pure returns (bool) { return (uint160(primary) | 0xFF) == (uint160(subAccount) | 0xFF); } // Entered markets array function getEnteredMarketsArray(address account) internal view returns (address[] memory) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; address[] memory output = new address[](numMarketsEntered); if (numMarketsEntered == 0) return output; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; output[0] = firstMarketEntered; for (uint i = 1; i < numMarketsEntered; ++i) { output[i] = markets[i]; } return output; } function isEnteredInMarket(address account, address underlying) internal view returns (bool) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; if (numMarketsEntered == 0) return false; if (firstMarketEntered == underlying) return true; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; for (uint i = 1; i < numMarketsEntered; ++i) { if (markets[i] == underlying) return true; } return false; } function doEnterMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; if (numMarketsEntered != 0) { if (accountStorage.firstMarketEntered == underlying) return; // already entered for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) return; // already entered } } require(numMarketsEntered < MAX_ENTERED_MARKETS, "e/too-many-entered-markets"); if (numMarketsEntered == 0) accountStorage.firstMarketEntered = underlying; else markets[numMarketsEntered] = underlying; accountStorage.numMarketsEntered = numMarketsEntered + 1; emit EnterMarket(underlying, account); } // Liquidity check must be done by caller after calling this function doExitMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; uint searchIndex = type(uint).max; if (numMarketsEntered == 0) return; // already exited if (accountStorage.firstMarketEntered == underlying) { searchIndex = 0; } else { for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) { searchIndex = i; break; } } if (searchIndex == type(uint).max) return; // already exited } uint lastMarketIndex = numMarketsEntered - 1; if (searchIndex != lastMarketIndex) { if (searchIndex == 0) accountStorage.firstMarketEntered = markets[lastMarketIndex]; else markets[searchIndex] = markets[lastMarketIndex]; } accountStorage.numMarketsEntered = uint32(lastMarketIndex); if (lastMarketIndex != 0) markets[lastMarketIndex] = address(0); // zero out for storage refund emit ExitMarket(underlying, account); } // AssetConfig function resolveAssetConfig(address underlying) internal view returns (AssetConfig memory) { AssetConfig memory config = underlyingLookup[underlying]; require(config.eTokenAddress != address(0), "e/market-not-activated"); if (config.borrowFactor == type(uint32).max) config.borrowFactor = DEFAULT_BORROW_FACTOR; if (config.twapWindow == type(uint24).max) config.twapWindow = DEFAULT_TWAP_WINDOW_SECONDS; return config; } // AssetCache struct AssetCache { address underlying; uint112 totalBalances; uint144 totalBorrows; uint96 reserveBalance; uint interestAccumulator; uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; uint poolSize; // result of calling balanceOf on underlying (in external units) uint underlyingDecimalsScaler; uint maxExternalAmount; } function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) { dirty = false; assetCache.underlying = underlying; // Storage loads assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate; uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals; assetCache.interestRateModel = assetStorage.interestRateModel; assetCache.interestRate = assetStorage.interestRate; assetCache.reserveFee = assetStorage.reserveFee; assetCache.pricingType = assetStorage.pricingType; assetCache.pricingParameters = assetStorage.pricingParameters; assetCache.reserveBalance = assetStorage.reserveBalance; assetCache.totalBalances = assetStorage.totalBalances; assetCache.totalBorrows = assetStorage.totalBorrows; assetCache.interestAccumulator = assetStorage.interestAccumulator; // Derived state unchecked { assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals); assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler; } uint poolSize = callBalanceOf(assetCache, address(this)); if (poolSize <= assetCache.maxExternalAmount) { unchecked { assetCache.poolSize = poolSize * assetCache.underlyingDecimalsScaler; } } else { assetCache.poolSize = 0; } // Update interest accumulator and reserves if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) { dirty = true; uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate; // Compute new values uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27; uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator; uint newReserveBalance = assetCache.reserveBalance; uint newTotalBalances = assetCache.totalBalances; uint feeAmount = (newTotalBorrows - assetCache.totalBorrows) * (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee) / (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION); if (feeAmount != 0) { uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION); newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount); newReserveBalance += newTotalBalances - assetCache.totalBalances; } // Store new values in assetCache, only if no overflows will occur if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) { assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows); assetCache.interestAccumulator = newInterestAccumulator; assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp); if (newTotalBalances != assetCache.totalBalances) { assetCache.reserveBalance = encodeSmallAmount(newReserveBalance); assetCache.totalBalances = encodeAmount(newTotalBalances); } } } } function loadAssetCache(address underlying, AssetStorage storage assetStorage) internal returns (AssetCache memory assetCache) { if (initAssetCache(underlying, assetStorage, assetCache)) { assetStorage.lastInterestAccumulatorUpdate = assetCache.lastInterestAccumulatorUpdate; assetStorage.underlying = assetCache.underlying; // avoid an SLOAD of this slot assetStorage.reserveBalance = assetCache.reserveBalance; assetStorage.totalBalances = assetCache.totalBalances; assetStorage.totalBorrows = assetCache.totalBorrows; assetStorage.interestAccumulator = assetCache.interestAccumulator; } } function loadAssetCacheRO(address underlying, AssetStorage storage assetStorage) internal view returns (AssetCache memory assetCache) { initAssetCache(underlying, assetStorage, assetCache); } // Utils function decodeExternalAmount(AssetCache memory assetCache, uint externalAmount) internal pure returns (uint scaledAmount) { require(externalAmount <= assetCache.maxExternalAmount, "e/amount-too-large"); unchecked { scaledAmount = externalAmount * assetCache.underlyingDecimalsScaler; } } function encodeAmount(uint amount) internal pure returns (uint112) { require(amount <= MAX_SANE_AMOUNT, "e/amount-too-large-to-encode"); return uint112(amount); } function encodeSmallAmount(uint amount) internal pure returns (uint96) { require(amount <= MAX_SANE_SMALL_AMOUNT, "e/small-amount-too-large-to-encode"); return uint96(amount); } function encodeDebtAmount(uint amount) internal pure returns (uint144) { require(amount <= MAX_SANE_DEBT_AMOUNT, "e/debt-amount-too-large-to-encode"); return uint144(amount); } function computeExchangeRate(AssetCache memory assetCache) private pure returns (uint) { if (assetCache.totalBalances == 0) return 1e18; return (assetCache.poolSize + (assetCache.totalBorrows / INTERNAL_DEBT_PRECISION)) * 1e18 / assetCache.totalBalances; } function underlyingAmountToBalance(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * 1e18 / exchangeRate; } function underlyingAmountToBalanceRoundUp(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return (amount * 1e18 + (exchangeRate - 1)) / exchangeRate; } function balanceToUnderlyingAmount(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * exchangeRate / 1e18; } function callBalanceOf(AssetCache memory assetCache, address account) internal view FREEMEM returns (uint) { // We set a gas limit so that a malicious token can't eat up all gas and cause a liquidity check to fail. (bool success, bytes memory data) = assetCache.underlying.staticcall{gas: 20000}(abi.encodeWithSelector(IERC20.balanceOf.selector, account)); // If token's balanceOf() call fails for any reason, return 0. This prevents malicious tokens from causing liquidity checks to fail. // If the contract doesn't exist (maybe because selfdestructed), then data.length will be 0 and we will return 0. // Data length > 32 is allowed because some legitimate tokens append extra data that can be safely ignored. if (!success || data.length < 32) return 0; return abi.decode(data, (uint256)); } function updateInterestRate(AssetStorage storage assetStorage, AssetCache memory assetCache) internal { uint32 utilisation; { uint totalBorrows = assetCache.totalBorrows / INTERNAL_DEBT_PRECISION; uint poolAssets = assetCache.poolSize + totalBorrows; if (poolAssets == 0) utilisation = 0; // empty pool arbitrarily given utilisation of 0 else utilisation = uint32(totalBorrows * (uint(type(uint32).max) * 1e18) / poolAssets / 1e18); } bytes memory result = callInternalModule(assetCache.interestRateModel, abi.encodeWithSelector(BaseIRM.computeInterestRate.selector, assetCache.underlying, utilisation)); (int96 newInterestRate) = abi.decode(result, (int96)); assetStorage.interestRate = assetCache.interestRate = newInterestRate; } function logAssetStatus(AssetCache memory a) internal { emit AssetStatus(a.underlying, a.totalBalances, a.totalBorrows / INTERNAL_DEBT_PRECISION, a.reserveBalance, a.poolSize, a.interestAccumulator, a.interestRate, block.timestamp); } // Balances function increaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { assetStorage.users[account].balance = encodeAmount(assetStorage.users[account].balance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(uint(assetCache.totalBalances) + amount); updateInterestRate(assetStorage, assetCache); emit Deposit(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, address(0), account, amount); } function decreaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { uint origBalance = assetStorage.users[account].balance; require(origBalance >= amount, "e/insufficient-balance"); assetStorage.users[account].balance = encodeAmount(origBalance - amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances - amount); updateInterestRate(assetStorage, assetCache); emit Withdraw(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, account, address(0), amount); } function transferBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address from, address to, uint amount) internal { uint origFromBalance = assetStorage.users[from].balance; require(origFromBalance >= amount, "e/insufficient-balance"); uint newFromBalance; unchecked { newFromBalance = origFromBalance - amount; } assetStorage.users[from].balance = encodeAmount(newFromBalance); assetStorage.users[to].balance = encodeAmount(assetStorage.users[to].balance + amount); emit Withdraw(assetCache.underlying, from, amount); emit Deposit(assetCache.underlying, to, amount); emitViaProxy_Transfer(eTokenAddress, from, to, amount); } function withdrawAmounts(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) internal view returns (uint, uint) { uint amountInternal; if (amount == type(uint).max) { amountInternal = assetStorage.users[account].balance; amount = balanceToUnderlyingAmount(assetCache, amountInternal); } else { amount = decodeExternalAmount(assetCache, amount); amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount); } return (amount, amountInternal); } // Borrows // Returns internal precision function getCurrentOwedExact(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint owed) internal view returns (uint) { // Don't bother loading the user's accumulator if (owed == 0) return 0; // Can't divide by 0 here: If owed is non-zero, we must've initialised the user's interestAccumulator return owed * assetCache.interestAccumulator / assetStorage.users[account].interestAccumulator; } // When non-zero, we round *up* to the smallest external unit so that outstanding dust in a loan can be repaid. // unchecked is OK here since owed is always loaded from storage, so we know it fits into a uint144 (pre-interest accural) // Takes and returns 27 decimals precision. function roundUpOwed(AssetCache memory assetCache, uint owed) private pure returns (uint) { if (owed == 0) return 0; unchecked { uint scale = INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler; return (owed + scale - 1) / scale * scale; } } // Returns 18-decimals precision (debt amount is rounded up) function getCurrentOwed(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) internal view returns (uint) { return roundUpOwed(assetCache, getCurrentOwedExact(assetStorage, assetCache, account, assetStorage.users[account].owed)) / INTERNAL_DEBT_PRECISION; } function updateUserBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) private returns (uint newOwedExact, uint prevOwedExact) { prevOwedExact = assetStorage.users[account].owed; newOwedExact = getCurrentOwedExact(assetStorage, assetCache, account, prevOwedExact); assetStorage.users[account].owed = encodeDebtAmount(newOwedExact); assetStorage.users[account].interestAccumulator = assetCache.interestAccumulator; } function logBorrowChange(AssetCache memory assetCache, address dTokenAddress, address account, uint prevOwed, uint owed) private { prevOwed = roundUpOwed(assetCache, prevOwed) / INTERNAL_DEBT_PRECISION; owed = roundUpOwed(assetCache, owed) / INTERNAL_DEBT_PRECISION; if (owed > prevOwed) { uint change = owed - prevOwed; emit Borrow(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, address(0), account, change); } else if (prevOwed > owed) { uint change = prevOwed - owed; emit Repay(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, account, address(0), change); } } function increaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint amount) internal { amount *= INTERNAL_DEBT_PRECISION; require(assetCache.pricingType != PRICINGTYPE__FORWARDED || pTokenLookup[assetCache.underlying] == address(0), "e/borrow-not-supported"); (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); if (owed == 0) doEnterMarket(account, assetCache.underlying); owed += amount; assetStorage.users[account].owed = encodeDebtAmount(owed); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows + amount); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owed); } function decreaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); uint owedRoundedUp = roundUpOwed(assetCache, owed); require(amount <= owedRoundedUp, "e/repay-too-much"); uint owedRemaining; unchecked { owedRemaining = owedRoundedUp - amount; } if (owed > assetCache.totalBorrows) owed = assetCache.totalBorrows; assetStorage.users[account].owed = encodeDebtAmount(owedRemaining); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows - owed + owedRemaining); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owedRemaining); } function transferBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address from, address to, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint fromOwed, uint fromOwedPrev) = updateUserBorrow(assetStorage, assetCache, from); (uint toOwed, uint toOwedPrev) = updateUserBorrow(assetStorage, assetCache, to); if (toOwed == 0) doEnterMarket(to, assetCache.underlying); // If amount was rounded up, transfer exact amount owed if (amount > fromOwed && amount - fromOwed < INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler) amount = fromOwed; require(fromOwed >= amount, "e/insufficient-balance"); unchecked { fromOwed -= amount; } // Transfer any residual dust if (fromOwed < INTERNAL_DEBT_PRECISION) { amount += fromOwed; fromOwed = 0; } toOwed += amount; assetStorage.users[from].owed = encodeDebtAmount(fromOwed); assetStorage.users[to].owed = encodeDebtAmount(toOwed); logBorrowChange(assetCache, dTokenAddress, from, fromOwedPrev, fromOwed); logBorrowChange(assetCache, dTokenAddress, to, toOwedPrev, toOwed); } // Reserves function increaseReserves(AssetStorage storage assetStorage, AssetCache memory assetCache, uint amount) internal { assetStorage.reserveBalance = assetCache.reserveBalance = encodeSmallAmount(assetCache.reserveBalance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances + amount); } // Token asset transfers // amounts are in underlying units function pullTokens(AssetCache memory assetCache, address from, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransferFrom(assetCache.underlying, from, address(this), amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeAfter >= poolSizeBefore, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeAfter - poolSizeBefore; } } function pushTokens(AssetCache memory assetCache, address to, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransfer(assetCache.underlying, to, amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeBefore >= poolSizeAfter, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeBefore - poolSizeAfter; } } // Liquidity function getAssetPrice(address asset) internal returns (uint) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getPrice.selector, asset)); return abi.decode(result, (uint)); } function getAccountLiquidity(address account) internal returns (uint collateralValue, uint liabilityValue) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.computeLiquidity.selector, account)); (IRiskManager.LiquidityStatus memory status) = abi.decode(result, (IRiskManager.LiquidityStatus)); collateralValue = status.collateralValue; liabilityValue = status.liabilityValue; } function checkLiquidity(address account) internal { uint8 status = accountLookup[account].deferLiquidityStatus; if (status == DEFERLIQUIDITY__NONE) { callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.requireLiquidity.selector, account)); } else if (status == DEFERLIQUIDITY__CLEAN) { accountLookup[account].deferLiquidityStatus = DEFERLIQUIDITY__DIRTY; } } // Optional average liquidity tracking function computeNewAverageLiquidity(address account, uint deltaT) private returns (uint) { uint currDuration = deltaT >= AVERAGE_LIQUIDITY_PERIOD ? AVERAGE_LIQUIDITY_PERIOD : deltaT; uint prevDuration = AVERAGE_LIQUIDITY_PERIOD - currDuration; uint currAverageLiquidity; { (uint collateralValue, uint liabilityValue) = getAccountLiquidity(account); currAverageLiquidity = collateralValue > liabilityValue ? collateralValue - liabilityValue : 0; } return (accountLookup[account].averageLiquidity * prevDuration / AVERAGE_LIQUIDITY_PERIOD) + (currAverageLiquidity * currDuration / AVERAGE_LIQUIDITY_PERIOD); } function getUpdatedAverageLiquidity(address account) internal returns (uint) { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return 0; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return accountLookup[account].averageLiquidity; return computeNewAverageLiquidity(account, deltaT); } function getUpdatedAverageLiquidityWithDelegate(address account) internal returns (uint) { address delegate = accountLookup[account].averageLiquidityDelegate; return delegate != address(0) && accountLookup[delegate].averageLiquidityDelegate == account ? getUpdatedAverageLiquidity(delegate) : getUpdatedAverageLiquidity(account); } function updateAverageLiquidity(address account) internal { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return; accountLookup[account].lastAverageLiquidityUpdate = uint40(block.timestamp); accountLookup[account].averageLiquidity = computeNewAverageLiquidity(account, deltaT); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Base.sol"; abstract contract BaseModule is Base { // Construction // public accessors common to all modules uint immutable public moduleId; bytes32 immutable public moduleGitCommit; constructor(uint moduleId_, bytes32 moduleGitCommit_) { moduleId = moduleId_; moduleGitCommit = moduleGitCommit_; } // Accessing parameters function unpackTrailingParamMsgSender() internal pure returns (address msgSender) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) } } function unpackTrailingParams() internal pure returns (address msgSender, address proxyAddr) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) proxyAddr := shr(96, calldataload(sub(calldatasize(), 20))) } } // Emit logs via proxies function emitViaProxy_Transfer(address proxyAddr, address from, address to, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Transfer(address,address,uint256)')), bytes32(uint(uint160(from))), bytes32(uint(uint160(to))), value )); require(success, "e/log-proxy-fail"); } function emitViaProxy_Approval(address proxyAddr, address owner, address spender, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Approval(address,address,uint256)')), bytes32(uint(uint160(owner))), bytes32(uint(uint160(spender))), value )); require(success, "e/log-proxy-fail"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; abstract contract BaseIRM is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} int96 internal constant MAX_ALLOWED_INTEREST_RATE = int96(int(uint(5 * 1e27) / SECONDS_PER_YEAR)); // 500% APR int96 internal constant MIN_ALLOWED_INTEREST_RATE = 0; function computeInterestRateImpl(address, uint32) internal virtual returns (int96); function computeInterestRate(address underlying, uint32 utilisation) external returns (int96) { int96 rate = computeInterestRateImpl(underlying, utilisation); if (rate > MAX_ALLOWED_INTEREST_RATE) rate = MAX_ALLOWED_INTEREST_RATE; else if (rate < MIN_ALLOWED_INTEREST_RATE) rate = MIN_ALLOWED_INTEREST_RATE; return rate; } function reset(address underlying, bytes calldata resetParams) external virtual {} } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } interface IERC20Permit { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external; } interface IERC3156FlashBorrower { function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32); } interface IERC3156FlashLender { function maxFlashLoan(address token) external view returns (uint256); function flashFee(address token, uint256 amount) external view returns (uint256); function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Interfaces.sol"; library Utils { function safeTransferFrom(address token, address from, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } } // SPDX-License-Identifier: AGPL-3.0-or-later // From MakerDAO DSS // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; library RPow { function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; // This interface is used to avoid a circular dependency between BaseLogic and RiskManager interface IRiskManager { struct NewMarketParameters { uint16 pricingType; uint32 pricingParameters; Storage.AssetConfig config; } struct LiquidityStatus { uint collateralValue; uint liabilityValue; uint numBorrows; bool borrowIsolated; } struct AssetLiquidity { address underlying; LiquidityStatus status; } function getNewMarketParameters(address underlying) external returns (NewMarketParameters memory); function requireLiquidity(address account) external view; function computeLiquidity(address account) external view returns (LiquidityStatus memory status); function computeAssetLiquidities(address account) external view returns (AssetLiquidity[] memory assets); function getPrice(address underlying) external view returns (uint twap, uint twapPeriod); function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; //import "hardhat/console.sol"; // DEV_MODE import "./Storage.sol"; import "./Events.sol"; import "./Proxy.sol"; abstract contract Base is Storage, Events { // Modules function _createProxy(uint proxyModuleId) internal returns (address) { require(proxyModuleId != 0, "e/create-proxy/invalid-module"); require(proxyModuleId <= MAX_EXTERNAL_MODULEID, "e/create-proxy/internal-module"); // If we've already created a proxy for a single-proxy module, just return it: if (proxyLookup[proxyModuleId] != address(0)) return proxyLookup[proxyModuleId]; // Otherwise create a proxy: address proxyAddr = address(new Proxy()); if (proxyModuleId <= MAX_EXTERNAL_SINGLE_PROXY_MODULEID) proxyLookup[proxyModuleId] = proxyAddr; trustedSenders[proxyAddr] = TrustedSenderInfo({ moduleId: uint32(proxyModuleId), moduleImpl: address(0) }); emit ProxyCreated(proxyAddr, proxyModuleId); return proxyAddr; } function callInternalModule(uint moduleId, bytes memory input) internal returns (bytes memory) { (bool success, bytes memory result) = moduleLookup[moduleId].delegatecall(input); if (!success) revertBytes(result); return result; } // Modifiers modifier nonReentrant() { require(reentrancyLock == REENTRANCYLOCK__UNLOCKED, "e/reentrancy"); reentrancyLock = REENTRANCYLOCK__LOCKED; _; reentrancyLock = REENTRANCYLOCK__UNLOCKED; } modifier reentrantOK() { // documentation only _; } // Used to flag functions which do not modify storage, but do perform a delegate call // to a view function, which prohibits a standard view modifier. The flag is used to // patch state mutability in compiled ABIs and interfaces. modifier staticDelegate() { _; } // WARNING: Must be very careful with this modifier. It resets the free memory pointer // to the value it was when the function started. This saves gas if more memory will // be allocated in the future. However, if the memory will be later referenced // (for example because the function has returned a pointer to it) then you cannot // use this modifier. modifier FREEMEM() { uint origFreeMemPtr; assembly { origFreeMemPtr := mload(0x40) } _; /* assembly { // DEV_MODE: overwrite the freed memory with garbage to detect bugs let garbage := 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF for { let i := origFreeMemPtr } lt(i, mload(0x40)) { i := add(i, 32) } { mstore(i, garbage) } } */ assembly { mstore(0x40, origFreeMemPtr) } } // Error handling function revertBytes(bytes memory errMsg) internal pure { if (errMsg.length > 0) { assembly { revert(add(32, errMsg), mload(errMsg)) } } revert("e/empty-error"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Constants.sol"; abstract contract Storage is Constants { // Dispatcher and upgrades uint reentrancyLock; address upgradeAdmin; address governorAdmin; mapping(uint => address) moduleLookup; // moduleId => module implementation mapping(uint => address) proxyLookup; // moduleId => proxy address (only for single-proxy modules) struct TrustedSenderInfo { uint32 moduleId; // 0 = un-trusted address moduleImpl; // only non-zero for external single-proxy modules } mapping(address => TrustedSenderInfo) trustedSenders; // sender address => moduleId (0 = un-trusted) // Account-level state // Sub-accounts are considered distinct accounts struct AccountStorage { // Packed slot: 1 + 5 + 4 + 20 = 30 uint8 deferLiquidityStatus; uint40 lastAverageLiquidityUpdate; uint32 numMarketsEntered; address firstMarketEntered; uint averageLiquidity; address averageLiquidityDelegate; } mapping(address => AccountStorage) accountLookup; mapping(address => address[MAX_POSSIBLE_ENTERED_MARKETS]) marketsEntered; // Markets and assets struct AssetConfig { // Packed slot: 20 + 1 + 4 + 4 + 3 = 32 address eTokenAddress; bool borrowIsolated; uint32 collateralFactor; uint32 borrowFactor; uint24 twapWindow; } struct UserAsset { uint112 balance; uint144 owed; uint interestAccumulator; } struct AssetStorage { // Packed slot: 5 + 1 + 4 + 12 + 4 + 2 + 4 = 32 uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; // Not dynamic, but put here to live in same storage slot uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; address underlying; uint96 reserveBalance; address dTokenAddress; uint112 totalBalances; uint144 totalBorrows; uint interestAccumulator; mapping(address => UserAsset) users; mapping(address => mapping(address => uint)) eTokenAllowance; mapping(address => mapping(address => uint)) dTokenAllowance; } mapping(address => AssetConfig) internal underlyingLookup; // underlying => AssetConfig mapping(address => AssetStorage) internal eTokenLookup; // EToken => AssetStorage mapping(address => address) internal dTokenLookup; // DToken => EToken mapping(address => address) internal pTokenLookup; // PToken => underlying mapping(address => address) internal reversePTokenLookup; // underlying => PToken } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; abstract contract Events { event Genesis(); event ProxyCreated(address indexed proxy, uint moduleId); event MarketActivated(address indexed underlying, address indexed eToken, address indexed dToken); event PTokenActivated(address indexed underlying, address indexed pToken); event EnterMarket(address indexed underlying, address indexed account); event ExitMarket(address indexed underlying, address indexed account); event Deposit(address indexed underlying, address indexed account, uint amount); event Withdraw(address indexed underlying, address indexed account, uint amount); event Borrow(address indexed underlying, address indexed account, uint amount); event Repay(address indexed underlying, address indexed account, uint amount); event Liquidation(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint yield, uint healthScore, uint baseDiscount, uint discount); event TrackAverageLiquidity(address indexed account); event UnTrackAverageLiquidity(address indexed account); event DelegateAverageLiquidity(address indexed account, address indexed delegate); event PTokenWrap(address indexed underlying, address indexed account, uint amount); event PTokenUnWrap(address indexed underlying, address indexed account, uint amount); event AssetStatus(address indexed underlying, uint totalBalances, uint totalBorrows, uint96 reserveBalance, uint poolSize, uint interestAccumulator, int96 interestRate, uint timestamp); event RequestDeposit(address indexed account, uint amount); event RequestWithdraw(address indexed account, uint amount); event RequestMint(address indexed account, uint amount); event RequestBurn(address indexed account, uint amount); event RequestTransferEToken(address indexed from, address indexed to, uint amount); event RequestBorrow(address indexed account, uint amount); event RequestRepay(address indexed account, uint amount); event RequestTransferDToken(address indexed from, address indexed to, uint amount); event RequestLiquidate(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint minYield); event InstallerSetUpgradeAdmin(address indexed newUpgradeAdmin); event InstallerSetGovernorAdmin(address indexed newGovernorAdmin); event InstallerInstallModule(uint indexed moduleId, address indexed moduleImpl, bytes32 moduleGitCommit); event GovSetAssetConfig(address indexed underlying, Storage.AssetConfig newConfig); event GovSetIRM(address indexed underlying, uint interestRateModel, bytes resetParams); event GovSetPricingConfig(address indexed underlying, uint16 newPricingType, uint32 newPricingParameter); event GovSetReserveFee(address indexed underlying, uint32 newReserveFee); event GovConvertReserves(address indexed underlying, address indexed recipient, uint amount); event RequestSwap(address indexed accountIn, address indexed accountOut, address indexed underlyingIn, address underlyingOut, uint amount, uint swapType); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; contract Proxy { address immutable creator; constructor() { creator = msg.sender; } // External interface fallback() external { address creator_ = creator; if (msg.sender == creator_) { assembly { mstore(0, 0) calldatacopy(31, 0, calldatasize()) switch mload(0) // numTopics case 0 { log0(32, sub(calldatasize(), 1)) } case 1 { log1(64, sub(calldatasize(), 33), mload(32)) } case 2 { log2(96, sub(calldatasize(), 65), mload(32), mload(64)) } case 3 { log3(128, sub(calldatasize(), 97), mload(32), mload(64), mload(96)) } case 4 { log4(160, sub(calldatasize(), 129), mload(32), mload(64), mload(96), mload(128)) } default { revert(0, 0) } return(0, 0) } } else { assembly { mstore(0, 0xe9c4a3ac00000000000000000000000000000000000000000000000000000000) // dispatch() selector calldatacopy(4, 0, calldatasize()) mstore(add(4, calldatasize()), shl(96, caller())) let result := call(gas(), creator_, 0, 0, add(24, calldatasize()), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; abstract contract Constants { // Universal uint internal constant SECONDS_PER_YEAR = 365.2425 * 86400; // Gregorian calendar // Protocol parameters uint internal constant MAX_SANE_AMOUNT = type(uint112).max; uint internal constant MAX_SANE_SMALL_AMOUNT = type(uint96).max; uint internal constant MAX_SANE_DEBT_AMOUNT = type(uint144).max; uint internal constant INTERNAL_DEBT_PRECISION = 1e9; uint internal constant MAX_ENTERED_MARKETS = 10; // per sub-account uint internal constant MAX_POSSIBLE_ENTERED_MARKETS = 2**32; // limited by size of AccountStorage.numMarketsEntered uint internal constant CONFIG_FACTOR_SCALE = 4_000_000_000; // must fit into a uint32 uint internal constant RESERVE_FEE_SCALE = 4_000_000_000; // must fit into a uint32 uint32 internal constant DEFAULT_RESERVE_FEE = uint32(0.23 * 4_000_000_000); uint internal constant INITIAL_INTEREST_ACCUMULATOR = 1e27; uint internal constant AVERAGE_LIQUIDITY_PERIOD = 24 * 60 * 60; uint16 internal constant MIN_UNISWAP3_OBSERVATION_CARDINALITY = 144; uint24 internal constant DEFAULT_TWAP_WINDOW_SECONDS = 30 * 60; uint32 internal constant DEFAULT_BORROW_FACTOR = uint32(0.28 * 4_000_000_000); uint32 internal constant SELF_COLLATERAL_FACTOR = uint32(0.95 * 4_000_000_000); // Implementation internals uint internal constant REENTRANCYLOCK__UNLOCKED = 1; uint internal constant REENTRANCYLOCK__LOCKED = 2; uint8 internal constant DEFERLIQUIDITY__NONE = 0; uint8 internal constant DEFERLIQUIDITY__CLEAN = 1; uint8 internal constant DEFERLIQUIDITY__DIRTY = 2; // Pricing types uint16 internal constant PRICINGTYPE__PEGGED = 1; uint16 internal constant PRICINGTYPE__UNISWAP3_TWAP = 2; uint16 internal constant PRICINGTYPE__FORWARDED = 3; // Modules // Public single-proxy modules uint internal constant MODULEID__INSTALLER = 1; uint internal constant MODULEID__MARKETS = 2; uint internal constant MODULEID__LIQUIDATION = 3; uint internal constant MODULEID__GOVERNANCE = 4; uint internal constant MODULEID__EXEC = 5; uint internal constant MODULEID__SWAP = 6; uint internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999; // Public multi-proxy modules uint internal constant MODULEID__ETOKEN = 500_000; uint internal constant MODULEID__DTOKEN = 500_001; uint internal constant MAX_EXTERNAL_MODULEID = 999_999; // Internal modules uint internal constant MODULEID__RISK_MANAGER = 1_000_000; // Interest rate models // Default for new markets uint internal constant MODULEID__IRM_DEFAULT = 2_000_000; // Testing-only uint internal constant MODULEID__IRM_ZERO = 2_000_001; uint internal constant MODULEID__IRM_FIXED = 2_000_002; uint internal constant MODULEID__IRM_LINEAR = 2_000_100; // Classes uint internal constant MODULEID__IRM_CLASS__STABLE = 2_000_500; uint internal constant MODULEID__IRM_CLASS__MAJOR = 2_000_501; uint internal constant MODULEID__IRM_CLASS__MIDCAP = 2_000_502; uint internal constant MODULEID__IRM_CLASS__MEGA = 2_000_503; // Swap types uint internal constant SWAP_TYPE__UNI_EXACT_INPUT_SINGLE = 1; uint internal constant SWAP_TYPE__UNI_EXACT_INPUT = 2; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE = 3; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT = 4; uint internal constant SWAP_TYPE__1INCH = 5; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY = 6; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY = 7; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; }
moduleId => module implementation
mapping(uint => address) moduleLookup;
25,809
[ 1, 2978, 548, 516, 1605, 4471, 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, 11890, 516, 1758, 13, 1605, 6609, 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, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./IStaking.sol"; import "./StakingStorage.sol"; import "./libs/Rebates.sol"; import "./libs/Stakes.sol"; /** * @title Staking contract */ contract Staking is StakingV2Storage, GraphUpgradeable, IStaking { using SafeMath for uint256; using Stakes for Stakes.Indexer; using Rebates for Rebates.Pool; // 100% in parts per million uint32 private constant MAX_PPM = 1000000; // -- Events -- /** * @dev Emitted when `indexer` update the delegation parameters for its delegation pool. */ event DelegationParametersUpdated( address indexed indexer, uint32 indexingRewardCut, uint32 queryFeeCut, uint32 cooldownBlocks ); /** * @dev Emitted when `indexer` stake `tokens` amount. */ event StakeDeposited(address indexed indexer, uint256 tokens); /** * @dev Emitted when `indexer` unstaked and locked `tokens` amount `until` block. */ event StakeLocked(address indexed indexer, uint256 tokens, uint256 until); /** * @dev Emitted when `indexer` withdrew `tokens` staked. */ event StakeWithdrawn(address indexed indexer, uint256 tokens); /** * @dev Emitted when `indexer` was slashed for a total of `tokens` amount. * Tracks `reward` amount of tokens given to `beneficiary`. */ event StakeSlashed( address indexed indexer, uint256 tokens, uint256 reward, address beneficiary ); /** * @dev Emitted when `delegator` delegated `tokens` to the `indexer`, the delegator * gets `shares` for the delegation pool proportionally to the tokens staked. */ event StakeDelegated( address indexed indexer, address indexed delegator, uint256 tokens, uint256 shares ); /** * @dev Emitted when `delegator` undelegated `tokens` from `indexer`. * Tokens get locked for withdrawal after a period of time. */ event StakeDelegatedLocked( address indexed indexer, address indexed delegator, uint256 tokens, uint256 shares, uint256 until ); /** * @dev Emitted when `delegator` withdrew delegated `tokens` from `indexer`. */ event StakeDelegatedWithdrawn( address indexed indexer, address indexed delegator, uint256 tokens ); /** * @dev Emitted when `indexer` allocated `tokens` amount to `subgraphDeploymentID` * during `epoch`. * `allocationID` indexer derived address used to identify the allocation. * `metadata` additional information related to the allocation. */ event AllocationCreated( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address indexed allocationID, bytes32 metadata ); /** * @dev Emitted when `indexer` collected `tokens` amount in `epoch` for `allocationID`. * These funds are related to `subgraphDeploymentID`. * The `from` value is the sender of the collected funds. */ event AllocationCollected( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address indexed allocationID, address from, uint256 curationFees, uint256 rebateFees ); /** * @dev Emitted when `indexer` close an allocation in `epoch` for `allocationID`. * An amount of `tokens` get unallocated from `subgraphDeploymentID`. * The `effectiveAllocation` are the tokens allocated from creation to closing. * This event also emits the POI (proof of indexing) submitted by the indexer. * `isDelegator` is true if the sender was one of the indexer's delegators. */ event AllocationClosed( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address indexed allocationID, uint256 effectiveAllocation, address sender, bytes32 poi, bool isDelegator ); /** * @dev Emitted when `indexer` claimed a rebate on `subgraphDeploymentID` during `epoch` * related to the `forEpoch` rebate pool. * The rebate is for `tokens` amount and `unclaimedAllocationsCount` are left for claim * in the rebate pool. `delegationFees` collected and sent to delegation pool. */ event RebateClaimed( address indexed indexer, bytes32 indexed subgraphDeploymentID, address indexed allocationID, uint256 epoch, uint256 forEpoch, uint256 tokens, uint256 unclaimedAllocationsCount, uint256 delegationFees ); /** * @dev Emitted when `caller` set `slasher` address as `allowed` to slash stakes. */ event SlasherUpdate(address indexed caller, address indexed slasher, bool allowed); /** * @dev Emitted when `caller` set `assetHolder` address as `allowed` to send funds * to staking contract. */ event AssetHolderUpdate(address indexed caller, address indexed assetHolder, bool allowed); /** * @dev Emitted when `indexer` set `operator` access. */ event SetOperator(address indexed indexer, address indexed operator, bool allowed); /** * @dev Emitted when `indexer` set an address to receive rewards. */ event SetRewardsDestination(address indexed indexer, address indexed destination); /** * @dev Check if the caller is the slasher. */ modifier onlySlasher { require(slashers[msg.sender] == true, "!slasher"); _; } /** * @dev Check if the caller is authorized (indexer or operator) */ function _isAuth(address _indexer) private view returns (bool) { return msg.sender == _indexer || isOperator(msg.sender, _indexer) == true; } /** * @dev Initialize this contract. */ function initialize( address _controller, uint256 _minimumIndexerStake, uint32 _thawingPeriod, uint32 _protocolPercentage, uint32 _curationPercentage, uint32 _channelDisputeEpochs, uint32 _maxAllocationEpochs, uint32 _delegationUnbondingPeriod, uint32 _delegationRatio, uint32 _rebateAlphaNumerator, uint32 _rebateAlphaDenominator ) external onlyImpl { Managed._initialize(_controller); // Settings _setMinimumIndexerStake(_minimumIndexerStake); _setThawingPeriod(_thawingPeriod); _setProtocolPercentage(_protocolPercentage); _setCurationPercentage(_curationPercentage); _setChannelDisputeEpochs(_channelDisputeEpochs); _setMaxAllocationEpochs(_maxAllocationEpochs); _setDelegationUnbondingPeriod(_delegationUnbondingPeriod); _setDelegationRatio(_delegationRatio); _setDelegationParametersCooldown(0); _setDelegationTaxPercentage(0); _setRebateRatio(_rebateAlphaNumerator, _rebateAlphaDenominator); } /** * @dev Set the minimum indexer stake required to. * @param _minimumIndexerStake Minimum indexer stake */ function setMinimumIndexerStake(uint256 _minimumIndexerStake) external override onlyGovernor { _setMinimumIndexerStake(_minimumIndexerStake); } /** * @dev Internal: Set the minimum indexer stake required. * @param _minimumIndexerStake Minimum indexer stake */ function _setMinimumIndexerStake(uint256 _minimumIndexerStake) private { require(_minimumIndexerStake > 0, "!minimumIndexerStake"); minimumIndexerStake = _minimumIndexerStake; emit ParameterUpdated("minimumIndexerStake"); } /** * @dev Set the thawing period for unstaking. * @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking */ function setThawingPeriod(uint32 _thawingPeriod) external override onlyGovernor { _setThawingPeriod(_thawingPeriod); } /** * @dev Internal: Set the thawing period for unstaking. * @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking */ function _setThawingPeriod(uint32 _thawingPeriod) private { require(_thawingPeriod > 0, "!thawingPeriod"); thawingPeriod = _thawingPeriod; emit ParameterUpdated("thawingPeriod"); } /** * @dev Set the curation percentage of query fees sent to curators. * @param _percentage Percentage of query fees sent to curators */ function setCurationPercentage(uint32 _percentage) external override onlyGovernor { _setCurationPercentage(_percentage); } /** * @dev Internal: Set the curation percentage of query fees sent to curators. * @param _percentage Percentage of query fees sent to curators */ function _setCurationPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, ">percentage"); curationPercentage = _percentage; emit ParameterUpdated("curationPercentage"); } /** * @dev Set a protocol percentage to burn when collecting query fees. * @param _percentage Percentage of query fees to burn as protocol fee */ function setProtocolPercentage(uint32 _percentage) external override onlyGovernor { _setProtocolPercentage(_percentage); } /** * @dev Internal: Set a protocol percentage to burn when collecting query fees. * @param _percentage Percentage of query fees to burn as protocol fee */ function _setProtocolPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, ">percentage"); protocolPercentage = _percentage; emit ParameterUpdated("protocolPercentage"); } /** * @dev Set the period in epochs that need to pass before fees in rebate pool can be claimed. * @param _channelDisputeEpochs Period in epochs */ function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external override onlyGovernor { _setChannelDisputeEpochs(_channelDisputeEpochs); } /** * @dev Internal: Set the period in epochs that need to pass before fees in rebate pool can be claimed. * @param _channelDisputeEpochs Period in epochs */ function _setChannelDisputeEpochs(uint32 _channelDisputeEpochs) private { require(_channelDisputeEpochs > 0, "!channelDisputeEpochs"); channelDisputeEpochs = _channelDisputeEpochs; emit ParameterUpdated("channelDisputeEpochs"); } /** * @dev Set the max time allowed for indexers stake on allocations. * @param _maxAllocationEpochs Allocation duration limit in epochs */ function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external override onlyGovernor { _setMaxAllocationEpochs(_maxAllocationEpochs); } /** * @dev Internal: Set the max time allowed for indexers stake on allocations. * @param _maxAllocationEpochs Allocation duration limit in epochs */ function _setMaxAllocationEpochs(uint32 _maxAllocationEpochs) private { maxAllocationEpochs = _maxAllocationEpochs; emit ParameterUpdated("maxAllocationEpochs"); } /** * @dev Set the rebate ratio (fees to allocated stake). * @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function * @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function */ function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external override onlyGovernor { _setRebateRatio(_alphaNumerator, _alphaDenominator); } /** * @dev Set the rebate ratio (fees to allocated stake). * @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function * @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function */ function _setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) private { require(_alphaNumerator > 0 && _alphaDenominator > 0, "!alpha"); alphaNumerator = _alphaNumerator; alphaDenominator = _alphaDenominator; emit ParameterUpdated("rebateRatio"); } /** * @dev Set the delegation ratio. * If set to 10 it means the indexer can use up to 10x the indexer staked amount * from their delegated tokens * @param _delegationRatio Delegation capacity multiplier */ function setDelegationRatio(uint32 _delegationRatio) external override onlyGovernor { _setDelegationRatio(_delegationRatio); } /** * @dev Internal: Set the delegation ratio. * If set to 10 it means the indexer can use up to 10x the indexer staked amount * from their delegated tokens * @param _delegationRatio Delegation capacity multiplier */ function _setDelegationRatio(uint32 _delegationRatio) private { delegationRatio = _delegationRatio; emit ParameterUpdated("delegationRatio"); } /** * @dev Set the delegation parameters. * @param _indexingRewardCut Percentage of indexing rewards left for delegators * @param _queryFeeCut Percentage of query fees left for delegators * @param _cooldownBlocks Period that need to pass to update delegation parameters */ function setDelegationParameters( uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) public override { address indexer = msg.sender; // Incentives must be within bounds require(_queryFeeCut <= MAX_PPM, ">queryFeeCut"); require(_indexingRewardCut <= MAX_PPM, ">indexingRewardCut"); // Cooldown period set by indexer cannot be below protocol global setting require(_cooldownBlocks >= delegationParametersCooldown, "<cooldown"); // Verify the cooldown period passed DelegationPool storage pool = delegationPools[indexer]; require( pool.updatedAtBlock == 0 || pool.updatedAtBlock.add(uint256(pool.cooldownBlocks)) <= block.number, "!cooldown" ); // Update delegation params pool.indexingRewardCut = _indexingRewardCut; pool.queryFeeCut = _queryFeeCut; pool.cooldownBlocks = _cooldownBlocks; pool.updatedAtBlock = block.number; emit DelegationParametersUpdated( indexer, _indexingRewardCut, _queryFeeCut, _cooldownBlocks ); } /** * @dev Set the time in blocks an indexer needs to wait to change delegation parameters. * @param _blocks Number of blocks to set the delegation parameters cooldown period */ function setDelegationParametersCooldown(uint32 _blocks) external override onlyGovernor { _setDelegationParametersCooldown(_blocks); } /** * @dev Internal: Set the time in blocks an indexer needs to wait to change delegation parameters. * @param _blocks Number of blocks to set the delegation parameters cooldown period */ function _setDelegationParametersCooldown(uint32 _blocks) private { delegationParametersCooldown = _blocks; emit ParameterUpdated("delegationParametersCooldown"); } /** * @dev Set the period for undelegation of stake from indexer. * @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating */ function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external override onlyGovernor { _setDelegationUnbondingPeriod(_delegationUnbondingPeriod); } /** * @dev Internal: Set the period for undelegation of stake from indexer. * @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating */ function _setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) private { require(_delegationUnbondingPeriod > 0, "!delegationUnbondingPeriod"); delegationUnbondingPeriod = _delegationUnbondingPeriod; emit ParameterUpdated("delegationUnbondingPeriod"); } /** * @dev Set a delegation tax percentage to burn when delegated funds are deposited. * @param _percentage Percentage of delegated tokens to burn as delegation tax */ function setDelegationTaxPercentage(uint32 _percentage) external override onlyGovernor { _setDelegationTaxPercentage(_percentage); } /** * @dev Internal: Set a delegation tax percentage to burn when delegated funds are deposited. * @param _percentage Percentage of delegated tokens to burn as delegation tax */ function _setDelegationTaxPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, ">percentage"); delegationTaxPercentage = _percentage; emit ParameterUpdated("delegationTaxPercentage"); } /** * @dev Set or unset an address as allowed slasher. * @param _slasher Address of the party allowed to slash indexers * @param _allowed True if slasher is allowed */ function setSlasher(address _slasher, bool _allowed) external override onlyGovernor { require(_slasher != address(0), "!slasher"); slashers[_slasher] = _allowed; emit SlasherUpdate(msg.sender, _slasher, _allowed); } /** * @dev Set an address as allowed asset holder. * @param _assetHolder Address of allowed source for state channel funds * @param _allowed True if asset holder is allowed */ function setAssetHolder(address _assetHolder, bool _allowed) external override onlyGovernor { require(_assetHolder != address(0), "!assetHolder"); assetHolders[_assetHolder] = _allowed; emit AssetHolderUpdate(msg.sender, _assetHolder, _allowed); } /** * @dev Return if allocationID is used. * @param _allocationID Address used as signer by the indexer for an allocation * @return True if allocationID already used */ function isAllocation(address _allocationID) external view override returns (bool) { return _getAllocationState(_allocationID) != AllocationState.Null; } /** * @dev Getter that returns if an indexer has any stake. * @param _indexer Address of the indexer * @return True if indexer has staked tokens */ function hasStake(address _indexer) external view override returns (bool) { return stakes[_indexer].hasTokens(); } /** * @dev Return the allocation by ID. * @param _allocationID Address used as allocation identifier * @return Allocation data */ function getAllocation(address _allocationID) external view override returns (Allocation memory) { return allocations[_allocationID]; } /** * @dev Return the current state of an allocation. * @param _allocationID Address used as the allocation identifier * @return AllocationState */ function getAllocationState(address _allocationID) external view override returns (AllocationState) { return _getAllocationState(_allocationID); } /** * @dev Return the total amount of tokens allocated to subgraph. * @param _subgraphDeploymentID Address used as the allocation identifier * @return Total tokens allocated to subgraph */ function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID) external view override returns (uint256) { return subgraphAllocations[_subgraphDeploymentID]; } /** * @dev Return the delegation from a delegator to an indexer. * @param _indexer Address of the indexer where funds have been delegated * @param _delegator Address of the delegator * @return Delegation data */ function getDelegation(address _indexer, address _delegator) external view override returns (Delegation memory) { return delegationPools[_indexer].delegators[_delegator]; } /** * @dev Return whether the delegator has delegated to the indexer. * @param _indexer Address of the indexer where funds have been delegated * @param _delegator Address of the delegator * @return True if delegator of indexer */ function isDelegator(address _indexer, address _delegator) public view override returns (bool) { return delegationPools[_indexer].delegators[_delegator].shares > 0; } /** * @dev Get the total amount of tokens staked by the indexer. * @param _indexer Address of the indexer * @return Amount of tokens staked by the indexer */ function getIndexerStakedTokens(address _indexer) external view override returns (uint256) { return stakes[_indexer].tokensStaked; } /** * @dev Get the total amount of tokens available to use in allocations. * This considers the indexer stake and delegated tokens according to delegation ratio * @param _indexer Address of the indexer * @return Amount of tokens staked by the indexer */ function getIndexerCapacity(address _indexer) public view override returns (uint256) { Stakes.Indexer memory indexerStake = stakes[_indexer]; uint256 tokensDelegated = delegationPools[_indexer].tokens; uint256 tokensDelegatedCap = indexerStake.tokensSecureStake().mul(uint256(delegationRatio)); uint256 tokensDelegatedCapacity = (tokensDelegated < tokensDelegatedCap) ? tokensDelegated : tokensDelegatedCap; return indexerStake.tokensAvailableWithDelegation(tokensDelegatedCapacity); } /** * @dev Returns amount of delegated tokens ready to be withdrawn after unbonding period. * @param _delegation Delegation of tokens from delegator to indexer * @return Amount of tokens to withdraw */ function getWithdraweableDelegatedTokens(Delegation memory _delegation) public view returns (uint256) { // There must be locked tokens and period passed uint256 currentEpoch = epochManager().currentEpoch(); if (_delegation.tokensLockedUntil > 0 && currentEpoch >= _delegation.tokensLockedUntil) { return _delegation.tokensLocked; } return 0; } /** * @dev Authorize or unauthorize an address to be an operator. * @param _operator Address to authorize * @param _allowed Whether authorized or not */ function setOperator(address _operator, bool _allowed) external override { require(_operator != msg.sender, "operator == sender"); operatorAuth[msg.sender][_operator] = _allowed; emit SetOperator(msg.sender, _operator, _allowed); } /** * @dev Return true if operator is allowed for indexer. * @param _operator Address of the operator * @param _indexer Address of the indexer */ function isOperator(address _operator, address _indexer) public view override returns (bool) { return operatorAuth[_indexer][_operator]; } /** * @dev Deposit tokens on the indexer stake. * @param _tokens Amount of tokens to stake */ function stake(uint256 _tokens) external override { stakeTo(msg.sender, _tokens); } /** * @dev Deposit tokens on the indexer stake. * @param _indexer Address of the indexer * @param _tokens Amount of tokens to stake */ function stakeTo(address _indexer, uint256 _tokens) public override notPartialPaused { require(_tokens > 0, "!tokens"); // Ensure minimum stake require( stakes[_indexer].tokensSecureStake().add(_tokens) >= minimumIndexerStake, "!minimumIndexerStake" ); // Transfer tokens to stake from caller to this contract require(graphToken().transferFrom(msg.sender, address(this), _tokens), "!transfer"); // Stake the transferred tokens _stake(_indexer, _tokens); } /** * @dev Unstake tokens from the indexer stake, lock them until thawing period expires. * @param _tokens Amount of tokens to unstake */ function unstake(uint256 _tokens) external override notPartialPaused { address indexer = msg.sender; Stakes.Indexer storage indexerStake = stakes[indexer]; require(_tokens > 0, "!tokens"); require(indexerStake.hasTokens(), "!stake"); require(indexerStake.tokensAvailable() >= _tokens, "!stake-avail"); // Ensure minimum stake uint256 newStake = indexerStake.tokensSecureStake().sub(_tokens); require(newStake == 0 || newStake >= minimumIndexerStake, "!minimumIndexerStake"); // Before locking more tokens, withdraw any unlocked ones uint256 tokensToWithdraw = indexerStake.tokensWithdrawable(); if (tokensToWithdraw > 0) { _withdraw(indexer); } indexerStake.lockTokens(_tokens, thawingPeriod); emit StakeLocked(indexer, indexerStake.tokensLocked, indexerStake.tokensLockedUntil); } /** * @dev Withdraw indexer tokens once the thawing period has passed. */ function withdraw() external override notPaused { _withdraw(msg.sender); } /** * @dev Set the destination where to send rewards. * @param _destination Rewards destination address. If set to zero, rewards will be restaked */ function setRewardsDestination(address _destination) external override { rewardsDestination[msg.sender] = _destination; emit SetRewardsDestination(msg.sender, _destination); } /** * @dev Slash the indexer stake. Delegated tokens are not subject to slashing. * Can only be called by the slasher role. * @param _indexer Address of indexer to slash * @param _tokens Amount of tokens to slash from the indexer stake * @param _reward Amount of reward tokens to send to a beneficiary * @param _beneficiary Address of a beneficiary to receive a reward for the slashing */ function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external override onlySlasher notPartialPaused { Stakes.Indexer storage indexerStake = stakes[_indexer]; // Only able to slash a non-zero number of tokens require(_tokens > 0, "!tokens"); // Rewards comes from tokens slashed balance require(_tokens >= _reward, "rewards>slash"); // Cannot slash stake of an indexer without any or enough stake require(indexerStake.hasTokens(), "!stake"); require(_tokens <= indexerStake.tokensStaked, "slash>stake"); // Validate beneficiary of slashed tokens require(_beneficiary != address(0), "!beneficiary"); // Slashing more tokens than freely available (over allocation condition) // Unlock locked tokens to avoid the indexer to withdraw them if (_tokens > indexerStake.tokensAvailable() && indexerStake.tokensLocked > 0) { uint256 tokensOverAllocated = _tokens.sub(indexerStake.tokensAvailable()); uint256 tokensToUnlock = (tokensOverAllocated > indexerStake.tokensLocked) ? indexerStake.tokensLocked : tokensOverAllocated; indexerStake.unlockTokens(tokensToUnlock); } // Remove tokens to slash from the stake indexerStake.release(_tokens); // -- Interactions -- IGraphToken graphToken = graphToken(); // Set apart the reward for the beneficiary and burn remaining slashed stake _burnTokens(graphToken, _tokens.sub(_reward)); // Give the beneficiary a reward for slashing if (_reward > 0) { require(graphToken.transfer(_beneficiary, _reward), "!transfer"); } emit StakeSlashed(_indexer, _tokens, _reward, _beneficiary); } /** * @dev Delegate tokens to an indexer. * @param _indexer Address of the indexer to delegate tokens to * @param _tokens Amount of tokens to delegate * @return Amount of shares issued of the delegation pool */ function delegate(address _indexer, uint256 _tokens) external override notPartialPaused returns (uint256) { address delegator = msg.sender; // Transfer tokens to delegate to this contract require(graphToken().transferFrom(delegator, address(this), _tokens), "!transfer"); // Update state return _delegate(delegator, _indexer, _tokens); } /** * @dev Undelegate tokens from an indexer. * @param _indexer Address of the indexer where tokens had been delegated * @param _shares Amount of shares to return and undelegate tokens * @return Amount of tokens returned for the shares of the delegation pool */ function undelegate(address _indexer, uint256 _shares) external override notPartialPaused returns (uint256) { return _undelegate(msg.sender, _indexer, _shares); } /** * @dev Withdraw delegated tokens once the unbonding period has passed. * @param _indexer Withdraw available tokens delegated to indexer * @param _delegateToIndexer Re-delegate to indexer address if non-zero, withdraw if zero address */ function withdrawDelegated(address _indexer, address _delegateToIndexer) external override notPaused returns (uint256) { return _withdrawDelegated(msg.sender, _indexer, _delegateToIndexer); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocation identifier * @param _metadata IPFS hash for additional information about the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function allocate( bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external override notPaused { _allocate(msg.sender, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocation identifier * @param _metadata IPFS hash for additional information about the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function allocateFrom( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external override notPaused { _allocate(_indexer, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof); } /** * @dev Close an allocation and free the staked tokens. * To be eligible for rewards a proof of indexing must be presented. * Presenting a bad proof is subject to slashable condition. * To opt out for rewards set _poi to 0x0 * @param _allocationID The allocation identifier * @param _poi Proof of indexing submitted for the allocated period */ function closeAllocation(address _allocationID, bytes32 _poi) external override notPaused { _closeAllocation(_allocationID, _poi); } /** * @dev Close multiple allocations and free the staked tokens. * To be eligible for rewards a proof of indexing must be presented. * Presenting a bad proof is subject to slashable condition. * To opt out for rewards set _poi to 0x0 * @param _requests An array of CloseAllocationRequest */ function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external override notPaused { for (uint256 i = 0; i < _requests.length; i++) { _closeAllocation(_requests[i].allocationID, _requests[i].poi); } } /** * @dev Close and allocate. This will perform a close and then create a new Allocation * atomically on the same transaction. * @param _closingAllocationID The identifier of the allocation to be closed * @param _poi Proof of indexing submitted for the allocated period * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocation identifier * @param _metadata IPFS hash for additional information about the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function closeAndAllocate( address _closingAllocationID, bytes32 _poi, address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external override notPaused { _closeAllocation(_closingAllocationID, _poi); _allocate(_indexer, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof); } /** * @dev Collect query fees for an allocation from state channels. * Funds received are only accepted from a valid sender. * @param _tokens Amount of tokens to collect * @param _allocationID Allocation where the tokens will be assigned */ function collect(uint256 _tokens, address _allocationID) external override { // Allocation identifier validation require(_allocationID != address(0), "!alloc"); // The contract caller must be an authorized asset holder require(assetHolders[msg.sender] == true, "!assetHolder"); // Allocation must exist AllocationState allocState = _getAllocationState(_allocationID); require(allocState != AllocationState.Null, "!collect"); // Get allocation Allocation storage alloc = allocations[_allocationID]; uint256 queryFees = _tokens; uint256 curationFees = 0; bytes32 subgraphDeploymentID = alloc.subgraphDeploymentID; // Process query fees only if non-zero amount if (queryFees > 0) { // Pull tokens to collect from the authorized sender IGraphToken graphToken = graphToken(); require(graphToken.transferFrom(msg.sender, address(this), _tokens), "!transfer"); // -- Collect protocol tax -- // If the Allocation is not active or closed we are going to charge a 100% protocol tax uint256 usedProtocolPercentage = (allocState == AllocationState.Active || allocState == AllocationState.Closed) ? protocolPercentage : MAX_PPM; uint256 protocolTax = _collectTax(graphToken, queryFees, usedProtocolPercentage); queryFees = queryFees.sub(protocolTax); // -- Collect curation fees -- // Only if the subgraph deployment is curated curationFees = _collectCurationFees( graphToken, subgraphDeploymentID, queryFees, curationPercentage ); queryFees = queryFees.sub(curationFees); // Add funds to the allocation alloc.collectedFees = alloc.collectedFees.add(queryFees); // When allocation is closed redirect funds to the rebate pool // This way we can keep collecting tokens even after the allocation is closed and // before it gets to the finalized state. if (allocState == AllocationState.Closed) { Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch]; rebatePool.fees = rebatePool.fees.add(queryFees); } } emit AllocationCollected( alloc.indexer, subgraphDeploymentID, epochManager().currentEpoch(), _tokens, _allocationID, msg.sender, curationFees, queryFees ); } /** * @dev Claim tokens from the rebate pool. * @param _allocationID Allocation from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function claim(address _allocationID, bool _restake) external override notPaused { _claim(_allocationID, _restake); } /** * @dev Claim tokens from the rebate pool for many allocations. * @param _allocationID Array of allocations from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function claimMany(address[] calldata _allocationID, bool _restake) external override notPaused { for (uint256 i = 0; i < _allocationID.length; i++) { _claim(_allocationID[i], _restake); } } /** * @dev Stake tokens on the indexer. * This function does not check minimum indexer stake requirement to allow * to be called by functions that increase the stake when collecting rewards * without reverting * @param _indexer Address of staking party * @param _tokens Amount of tokens to stake */ function _stake(address _indexer, uint256 _tokens) private { // Deposit tokens into the indexer stake stakes[_indexer].deposit(_tokens); // Initialize the delegation pool the first time if (delegationPools[_indexer].updatedAtBlock == 0) { setDelegationParameters(MAX_PPM, MAX_PPM, delegationParametersCooldown); } emit StakeDeposited(_indexer, _tokens); } /** * @dev Withdraw indexer tokens once the thawing period has passed. * @param _indexer Address of indexer to withdraw funds from */ function _withdraw(address _indexer) private { // Get tokens available for withdraw and update balance uint256 tokensToWithdraw = stakes[_indexer].withdrawTokens(); require(tokensToWithdraw > 0, "!tokens"); // Return tokens to the indexer require(graphToken().transfer(_indexer, tokensToWithdraw), "!transfer"); emit StakeWithdrawn(_indexer, tokensToWithdraw); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocationID will work to identify collected funds related to this allocation * @param _metadata Metadata related to the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function _allocate( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) private { require(_isAuth(_indexer), "!auth"); // Only allocations with a non-zero token amount are allowed require(_tokens > 0, "!tokens"); // Check allocation require(_allocationID != address(0), "!alloc"); require(_getAllocationState(_allocationID) == AllocationState.Null, "!null"); // Caller must prove that they own the private key for the allocationID adddress // The proof is an Ethereum signed message of KECCAK256(indexerAddress,allocationID) bytes32 messageHash = keccak256(abi.encodePacked(_indexer, _allocationID)); bytes32 digest = ECDSA.toEthSignedMessageHash(messageHash); require(ECDSA.recover(digest, _proof) == _allocationID, "!proof"); // Needs to have free capacity not used for other purposes to allocate require(getIndexerCapacity(_indexer) >= _tokens, "!capacity"); // Creates an allocation // Allocation identifiers are not reused // The assetHolder address can send collected funds to the allocation Allocation memory alloc = Allocation( _indexer, _subgraphDeploymentID, _tokens, // Tokens allocated epochManager().currentEpoch(), // createdAtEpoch 0, // closedAtEpoch 0, // Initialize collected fees 0, // Initialize effective allocation _updateRewards(_subgraphDeploymentID) // Initialize accumulated rewards per stake allocated ); allocations[_allocationID] = alloc; // Mark allocated tokens as used stakes[_indexer].allocate(alloc.tokens); // Track total allocations per subgraph // Used for rewards calculations subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[ alloc.subgraphDeploymentID ] .add(alloc.tokens); emit AllocationCreated( _indexer, _subgraphDeploymentID, alloc.createdAtEpoch, alloc.tokens, _allocationID, _metadata ); } /** * @dev Close an allocation and free the staked tokens. * @param _allocationID The allocation identifier * @param _poi Proof of indexing submitted for the allocated period */ function _closeAllocation(address _allocationID, bytes32 _poi) private { // Allocation must exist and be active AllocationState allocState = _getAllocationState(_allocationID); require(allocState == AllocationState.Active, "!active"); // Get allocation Allocation memory alloc = allocations[_allocationID]; // Validate that an allocation cannot be closed before one epoch alloc.closedAtEpoch = epochManager().currentEpoch(); uint256 epochs = alloc.createdAtEpoch < alloc.closedAtEpoch ? alloc.closedAtEpoch.sub(alloc.createdAtEpoch) : 0; require(epochs > 0, "<epochs"); // Indexer or operator can close an allocation // Delegators are also allowed but only after maxAllocationEpochs passed bool isIndexer = _isAuth(alloc.indexer); if (epochs > maxAllocationEpochs) { require(isIndexer || isDelegator(alloc.indexer, msg.sender), "!auth-or-del"); } else { require(isIndexer, "!auth"); } // Calculate effective allocation for the amount of epochs it remained allocated alloc.effectiveAllocation = _getEffectiveAllocation( maxAllocationEpochs, alloc.tokens, epochs ); // Close the allocation and start counting a period to settle remaining payments from // state channels. allocations[_allocationID].closedAtEpoch = alloc.closedAtEpoch; allocations[_allocationID].effectiveAllocation = alloc.effectiveAllocation; // Account collected fees and effective allocation in rebate pool for the epoch Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch]; if (!rebatePool.exists()) { rebatePool.init(alphaNumerator, alphaDenominator); } rebatePool.addToPool(alloc.collectedFees, alloc.effectiveAllocation); // Distribute rewards if proof of indexing was presented by the indexer or operator if (isIndexer && _poi != 0) { _distributeRewards(_allocationID, alloc.indexer); } // Free allocated tokens from use stakes[alloc.indexer].unallocate(alloc.tokens); // Track total allocations per subgraph // Used for rewards calculations subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[ alloc.subgraphDeploymentID ] .sub(alloc.tokens); emit AllocationClosed( alloc.indexer, alloc.subgraphDeploymentID, alloc.closedAtEpoch, alloc.tokens, _allocationID, alloc.effectiveAllocation, msg.sender, _poi, !isIndexer ); } /** * @dev Claim tokens from the rebate pool. * @param _allocationID Allocation from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function _claim(address _allocationID, bool _restake) private { // Funds can only be claimed after a period of time passed since allocation was closed AllocationState allocState = _getAllocationState(_allocationID); require(allocState == AllocationState.Finalized, "!finalized"); // Get allocation Allocation memory alloc = allocations[_allocationID]; // Only the indexer or operator can decide if to restake bool restake = _isAuth(alloc.indexer) ? _restake : false; // Process rebate reward Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch]; uint256 tokensToClaim = rebatePool.redeem(alloc.collectedFees, alloc.effectiveAllocation); // Add delegation rewards to the delegation pool uint256 delegationRewards = _collectDelegationQueryRewards(alloc.indexer, tokensToClaim); tokensToClaim = tokensToClaim.sub(delegationRewards); // Purge allocation data except for: // - indexer: used in disputes and to avoid reusing an allocationID // - subgraphDeploymentID: used in disputes allocations[_allocationID].tokens = 0; // This avoid collect(), close() and claim() to be called allocations[_allocationID].createdAtEpoch = 0; allocations[_allocationID].closedAtEpoch = 0; allocations[_allocationID].collectedFees = 0; allocations[_allocationID].effectiveAllocation = 0; allocations[_allocationID].accRewardsPerAllocatedToken = 0; // -- Interactions -- IGraphToken graphToken = graphToken(); // When all allocations processed then burn unclaimed fees and prune rebate pool if (rebatePool.unclaimedAllocationsCount == 0) { _burnTokens(graphToken, rebatePool.unclaimedFees()); delete rebates[alloc.closedAtEpoch]; } // When there are tokens to claim from the rebate pool, transfer or restake _sendRewards(graphToken, tokensToClaim, alloc.indexer, restake); emit RebateClaimed( alloc.indexer, alloc.subgraphDeploymentID, _allocationID, epochManager().currentEpoch(), alloc.closedAtEpoch, tokensToClaim, rebatePool.unclaimedAllocationsCount, delegationRewards ); } /** * @dev Delegate tokens to an indexer. * @param _delegator Address of the delegator * @param _indexer Address of the indexer to delegate tokens to * @param _tokens Amount of tokens to delegate * @return Amount of shares issued of the delegation pool */ function _delegate( address _delegator, address _indexer, uint256 _tokens ) private returns (uint256) { // Only delegate a non-zero amount of tokens require(_tokens > 0, "!tokens"); // Only delegate to non-empty address require(_indexer != address(0), "!indexer"); // Only delegate to staked indexer require(stakes[_indexer].hasTokens(), "!stake"); // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Collect delegation tax uint256 delegationTax = _collectTax(graphToken(), _tokens, delegationTaxPercentage); uint256 delegatedTokens = _tokens.sub(delegationTax); // Calculate shares to issue uint256 shares = (pool.tokens == 0) ? delegatedTokens : delegatedTokens.mul(pool.shares).div(pool.tokens); // Update the delegation pool pool.tokens = pool.tokens.add(delegatedTokens); pool.shares = pool.shares.add(shares); // Update the delegation delegation.shares = delegation.shares.add(shares); emit StakeDelegated(_indexer, _delegator, delegatedTokens, shares); return shares; } /** * @dev Undelegate tokens from an indexer. * @param _delegator Address of the delegator * @param _indexer Address of the indexer where tokens had been delegated * @param _shares Amount of shares to return and undelegate tokens * @return Amount of tokens returned for the shares of the delegation pool */ function _undelegate( address _delegator, address _indexer, uint256 _shares ) private returns (uint256) { // Can only undelegate a non-zero amount of shares require(_shares > 0, "!shares"); // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Delegator need to have enough shares in the pool to undelegate require(delegation.shares >= _shares, "!shares-avail"); // Withdraw tokens if available if (getWithdraweableDelegatedTokens(delegation) > 0) { _withdrawDelegated(_delegator, _indexer, address(0)); } // Calculate tokens to get in exchange for the shares uint256 tokens = _shares.mul(pool.tokens).div(pool.shares); // Update the delegation pool pool.tokens = pool.tokens.sub(tokens); pool.shares = pool.shares.sub(_shares); // Update the delegation delegation.shares = delegation.shares.sub(_shares); delegation.tokensLocked = delegation.tokensLocked.add(tokens); delegation.tokensLockedUntil = epochManager().currentEpoch().add(delegationUnbondingPeriod); emit StakeDelegatedLocked( _indexer, _delegator, tokens, _shares, delegation.tokensLockedUntil ); return tokens; } /** * @dev Withdraw delegated tokens once the unbonding period has passed. * @param _delegator Delegator that is withdrawing tokens * @param _indexer Withdraw available tokens delegated to indexer * @param _delegateToIndexer Re-delegate to indexer address if non-zero, withdraw if zero address */ function _withdrawDelegated( address _delegator, address _indexer, address _delegateToIndexer ) private returns (uint256) { // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Validation uint256 tokensToWithdraw = getWithdraweableDelegatedTokens(delegation); require(tokensToWithdraw > 0, "!tokens"); // Reset lock delegation.tokensLocked = 0; delegation.tokensLockedUntil = 0; emit StakeDelegatedWithdrawn(_indexer, _delegator, tokensToWithdraw); // -- Interactions -- if (_delegateToIndexer != address(0)) { // Re-delegate tokens to a new indexer _delegate(_delegator, _delegateToIndexer, tokensToWithdraw); } else { // Return tokens to the delegator require(graphToken().transfer(_delegator, tokensToWithdraw), "!transfer"); } return tokensToWithdraw; } /** * @dev Collect the delegation rewards for query fees. * This function will assign the collected fees to the delegation pool. * @param _indexer Indexer to which the tokens to distribute are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of delegation rewards */ function _collectDelegationQueryRewards(address _indexer, uint256 _tokens) private returns (uint256) { uint256 delegationRewards = 0; DelegationPool storage pool = delegationPools[_indexer]; if (pool.tokens > 0 && pool.queryFeeCut < MAX_PPM) { uint256 indexerCut = uint256(pool.queryFeeCut).mul(_tokens).div(MAX_PPM); delegationRewards = _tokens.sub(indexerCut); pool.tokens = pool.tokens.add(delegationRewards); } return delegationRewards; } /** * @dev Collect the delegation rewards for indexing. * This function will assign the collected fees to the delegation pool. * @param _indexer Indexer to which the tokens to distribute are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of delegation rewards */ function _collectDelegationIndexingRewards(address _indexer, uint256 _tokens) private returns (uint256) { uint256 delegationRewards = 0; DelegationPool storage pool = delegationPools[_indexer]; if (pool.tokens > 0 && pool.indexingRewardCut < MAX_PPM) { uint256 indexerCut = uint256(pool.indexingRewardCut).mul(_tokens).div(MAX_PPM); delegationRewards = _tokens.sub(indexerCut); pool.tokens = pool.tokens.add(delegationRewards); } return delegationRewards; } /** * @dev Collect the curation fees for a subgraph deployment from an amount of tokens. * This function transfer curation fees to the Curation contract by calling Curation.collect * @param _graphToken Token to collect * @param _subgraphDeploymentID Subgraph deployment to which the curation fees are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @param _curationPercentage Percentage of tokens to collect as fees * @return Amount of curation fees */ function _collectCurationFees( IGraphToken _graphToken, bytes32 _subgraphDeploymentID, uint256 _tokens, uint256 _curationPercentage ) private returns (uint256) { if (_tokens == 0) { return 0; } ICuration curation = curation(); bool isCurationEnabled = _curationPercentage > 0 && address(curation) != address(0); if (isCurationEnabled && curation.isCurated(_subgraphDeploymentID)) { uint256 curationFees = uint256(_curationPercentage).mul(_tokens).div(MAX_PPM); if (curationFees > 0) { // Transfer and call collect() // This function transfer tokens to a trusted protocol contracts // Then we call collect() to do the transfer bookeeping require(_graphToken.transfer(address(curation), curationFees), "!transfer"); curation.collect(_subgraphDeploymentID, curationFees); } return curationFees; } return 0; } /** * @dev Collect tax to burn for an amount of tokens. * @param _graphToken Token to burn * @param _tokens Total tokens received used to calculate the amount of tax to collect * @param _percentage Percentage of tokens to burn as tax * @return Amount of tax charged */ function _collectTax( IGraphToken _graphToken, uint256 _tokens, uint256 _percentage ) private returns (uint256) { uint256 tax = uint256(_percentage).mul(_tokens).div(MAX_PPM); _burnTokens(_graphToken, tax); // Burn tax if any return tax; } /** * @dev Return the current state of an allocation * @param _allocationID Allocation identifier * @return AllocationState */ function _getAllocationState(address _allocationID) private view returns (AllocationState) { Allocation storage alloc = allocations[_allocationID]; if (alloc.indexer == address(0)) { return AllocationState.Null; } if (alloc.tokens == 0) { return AllocationState.Claimed; } uint256 closedAtEpoch = alloc.closedAtEpoch; if (closedAtEpoch == 0) { return AllocationState.Active; } uint256 epochs = epochManager().epochsSince(closedAtEpoch); if (epochs >= channelDisputeEpochs) { return AllocationState.Finalized; } return AllocationState.Closed; } /** * @dev Get the effective stake allocation considering epochs from allocation to closing. * @param _maxAllocationEpochs Max amount of epochs to cap the allocated stake * @param _tokens Amount of tokens allocated * @param _numEpochs Number of epochs that passed from allocation to closing * @return Effective allocated tokens across epochs */ function _getEffectiveAllocation( uint256 _maxAllocationEpochs, uint256 _tokens, uint256 _numEpochs ) private pure returns (uint256) { bool shouldCap = _maxAllocationEpochs > 0 && _numEpochs > _maxAllocationEpochs; return _tokens.mul((shouldCap) ? _maxAllocationEpochs : _numEpochs); } /** * @dev Triggers an update of rewards due to a change in allocations. * @param _subgraphDeploymentID Subgraph deployment updated */ function _updateRewards(bytes32 _subgraphDeploymentID) private returns (uint256) { IRewardsManager rewardsManager = rewardsManager(); if (address(rewardsManager) == address(0)) { return 0; } return rewardsManager.onSubgraphAllocationUpdate(_subgraphDeploymentID); } /** * @dev Assign rewards for the closed allocation to indexer and delegators. * @param _allocationID Allocation */ function _distributeRewards(address _allocationID, address _indexer) private { IRewardsManager rewardsManager = rewardsManager(); if (address(rewardsManager) == address(0)) { return; } // Automatically triggers update of rewards snapshot as allocation will change // after this call. Take rewards mint tokens for the Staking contract to distribute // between indexer and delegators uint256 totalRewards = rewardsManager.takeRewards(_allocationID); if (totalRewards == 0) { return; } // Calculate delegation rewards and add them to the delegation pool uint256 delegationRewards = _collectDelegationIndexingRewards(_indexer, totalRewards); uint256 indexerRewards = totalRewards.sub(delegationRewards); // Send the indexer rewards _sendRewards( graphToken(), indexerRewards, _indexer, rewardsDestination[_indexer] == address(0) ); } /** * @dev Send rewards to the appropiate destination. * @param _graphToken Graph token * @param _amount Number of rewards tokens * @param _beneficiary Address of the beneficiary of rewards * @param _restake Whether to restake or not */ function _sendRewards( IGraphToken _graphToken, uint256 _amount, address _beneficiary, bool _restake ) private { if (_amount == 0) return; if (_restake) { // Restake to place fees into the indexer stake _stake(_beneficiary, _amount); } else { // Transfer funds to the beneficiary's designated rewards destination if set address destination = rewardsDestination[_beneficiary]; require( _graphToken.transfer( destination == address(0) ? _beneficiary : destination, _amount ), "!transfer" ); } } /** * @dev Burn tokens held by this contract. * @param _graphToken Token to burn * @param _amount Amount of tokens to burn */ function _burnTokens(IGraphToken _graphToken, uint256 _amount) private { if (_amount > 0) { _graphToken.burn(_amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./IGraphProxy.sol"; /** * @title Graph Upgradeable * @dev This contract is intended to be inherited from upgradeable contracts. */ contract GraphUpgradeable { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Check if the caller is the proxy admin. */ modifier onlyProxyAdmin(IGraphProxy _proxy) { require(msg.sender == _proxy.admin(), "Caller must be the proxy admin"); _; } /** * @dev Check if the caller is the implementation. */ modifier onlyImpl { require(msg.sender == _implementation(), "Caller must be the implementation"); _; } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Accept to be an implementation of proxy. */ function acceptProxy(IGraphProxy _proxy) external onlyProxyAdmin(_proxy) { _proxy.acceptUpgrade(); } /** * @dev Accept to be an implementation of proxy and then call a function from the new * implementation as specified by `_data`, which should be an encoded function call. This is * useful to initialize new storage variables in the proxied contract. */ function acceptProxyAndCall(IGraphProxy _proxy, bytes calldata _data) external onlyProxyAdmin(_proxy) { _proxy.acceptUpgradeAndCall(_data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import "./IStakingData.sol"; interface IStaking is IStakingData { // -- Allocation Data -- /** * @dev Possible states an allocation can be * States: * - Null = indexer == address(0) * - Active = not Null && tokens > 0 * - Closed = Active && closedAtEpoch != 0 * - Finalized = Closed && closedAtEpoch + channelDisputeEpochs > now() * - Claimed = not Null && tokens == 0 */ enum AllocationState { Null, Active, Closed, Finalized, Claimed } // -- Configuration -- function setMinimumIndexerStake(uint256 _minimumIndexerStake) external; function setThawingPeriod(uint32 _thawingPeriod) external; function setCurationPercentage(uint32 _percentage) external; function setProtocolPercentage(uint32 _percentage) external; function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external; function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external; function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external; function setDelegationRatio(uint32 _delegationRatio) external; function setDelegationParameters( uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) external; function setDelegationParametersCooldown(uint32 _blocks) external; function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external; function setDelegationTaxPercentage(uint32 _percentage) external; function setSlasher(address _slasher, bool _allowed) external; function setAssetHolder(address _assetHolder, bool _allowed) external; // -- Operation -- function setOperator(address _operator, bool _allowed) external; function isOperator(address _operator, address _indexer) external view returns (bool); // -- Staking -- function stake(uint256 _tokens) external; function stakeTo(address _indexer, uint256 _tokens) external; function unstake(uint256 _tokens) external; function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external; function withdraw() external; function setRewardsDestination(address _destination) external; // -- Delegation -- function delegate(address _indexer, uint256 _tokens) external returns (uint256); function undelegate(address _indexer, uint256 _shares) external returns (uint256); function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256); // -- Channel management and allocations -- function allocate( bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function allocateFrom( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function closeAllocation(address _allocationID, bytes32 _poi) external; function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external; function closeAndAllocate( address _oldAllocationID, bytes32 _poi, address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function collect(uint256 _tokens, address _allocationID) external; function claim(address _allocationID, bool _restake) external; function claimMany(address[] calldata _allocationID, bool _restake) external; // -- Getters and calculations -- function hasStake(address _indexer) external view returns (bool); function getIndexerStakedTokens(address _indexer) external view returns (uint256); function getIndexerCapacity(address _indexer) external view returns (uint256); function getAllocation(address _allocationID) external view returns (Allocation memory); function getAllocationState(address _allocationID) external view returns (AllocationState); function isAllocation(address _allocationID) external view returns (bool); function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID) external view returns (uint256); function getDelegation(address _indexer, address _delegator) external view returns (Delegation memory); function isDelegator(address _indexer, address _delegator) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "../governance/Managed.sol"; import "./IStakingData.sol"; import "./libs/Rebates.sol"; import "./libs/Stakes.sol"; contract StakingV1Storage is Managed { // -- Staking -- // Minimum amount of tokens an indexer needs to stake uint256 public minimumIndexerStake; // Time in blocks to unstake uint32 public thawingPeriod; // in blocks // Percentage of fees going to curators // Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%) uint32 public curationPercentage; // Percentage of fees burned as protocol fee // Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%) uint32 public protocolPercentage; // Period for allocation to be finalized uint32 public channelDisputeEpochs; // Maximum allocation time uint32 public maxAllocationEpochs; // Rebate ratio uint32 public alphaNumerator; uint32 public alphaDenominator; // Indexer stakes : indexer => Stake mapping(address => Stakes.Indexer) public stakes; // Allocations : allocationID => Allocation mapping(address => IStakingData.Allocation) public allocations; // Subgraph Allocations: subgraphDeploymentID => tokens mapping(bytes32 => uint256) public subgraphAllocations; // Rebate pools : epoch => Pool mapping(uint256 => Rebates.Pool) public rebates; // -- Slashing -- // List of addresses allowed to slash stakes mapping(address => bool) public slashers; // -- Delegation -- // Set the delegation capacity multiplier defined by the delegation ratio // If delegation ratio is 100, and an Indexer has staked 5 GRT, // then they can use up to 500 GRT from the delegated stake uint32 public delegationRatio; // Time in blocks an indexer needs to wait to change delegation parameters uint32 public delegationParametersCooldown; // Time in epochs a delegator needs to wait to withdraw delegated stake uint32 public delegationUnbondingPeriod; // in epochs // Percentage of tokens to tax a delegation deposit // Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%) uint32 public delegationTaxPercentage; // Delegation pools : indexer => DelegationPool mapping(address => IStakingData.DelegationPool) public delegationPools; // -- Operators -- // Operator auth : indexer => operator mapping(address => mapping(address => bool)) public operatorAuth; // -- Asset Holders -- // Allowed AssetHolders: assetHolder => is allowed mapping(address => bool) public assetHolders; } contract StakingV2Storage is StakingV1Storage { // Destination of accrued rewards : beneficiary => rewards destination mapping(address => address) public rewardsDestination; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Cobbs.sol"; /** * @title A collection of data structures and functions to manage Rebates * Used for low-level state changes, require() conditions should be evaluated * at the caller function scope. */ library Rebates { using SafeMath for uint256; // Tracks stats for allocations closed on a particular epoch for claiming // The pool also keeps tracks of total query fees collected and stake used // Only one rebate pool exists per epoch struct Pool { uint256 fees; // total query fees in the rebate pool uint256 effectiveAllocatedStake; // total effective allocation of stake uint256 claimedRewards; // total claimed rewards from the rebate pool uint32 unclaimedAllocationsCount; // amount of unclaimed allocations uint32 alphaNumerator; // numerator of `alpha` in the cobb-douglas function uint32 alphaDenominator; // denominator of `alpha` in the cobb-douglas function } /** * @dev Init the rebate pool with the rebate ratio. * @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function * @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function */ function init( Rebates.Pool storage pool, uint32 _alphaNumerator, uint32 _alphaDenominator ) internal { pool.alphaNumerator = _alphaNumerator; pool.alphaDenominator = _alphaDenominator; } /** * @dev Return true if the rebate pool was already initialized. */ function exists(Rebates.Pool storage pool) internal view returns (bool) { return pool.effectiveAllocatedStake > 0; } /** * @dev Return the amount of unclaimed fees. */ function unclaimedFees(Rebates.Pool storage pool) internal view returns (uint256) { return pool.fees.sub(pool.claimedRewards); } /** * @dev Deposit tokens into the rebate pool. * @param _indexerFees Amount of fees collected in tokens * @param _indexerEffectiveAllocatedStake Effective stake allocated by indexer for a period of epochs */ function addToPool( Rebates.Pool storage pool, uint256 _indexerFees, uint256 _indexerEffectiveAllocatedStake ) internal { pool.fees = pool.fees.add(_indexerFees); pool.effectiveAllocatedStake = pool.effectiveAllocatedStake.add( _indexerEffectiveAllocatedStake ); pool.unclaimedAllocationsCount += 1; } /** * @dev Redeem tokens from the rebate pool. * @param _indexerFees Amount of fees collected in tokens * @param _indexerEffectiveAllocatedStake Effective stake allocated by indexer for a period of epochs * @return Amount of reward tokens according to Cobb-Douglas rebate formula */ function redeem( Rebates.Pool storage pool, uint256 _indexerFees, uint256 _indexerEffectiveAllocatedStake ) internal returns (uint256) { uint256 rebateReward = 0; // Calculate the rebate rewards for the indexer if (pool.fees > 0) { rebateReward = LibCobbDouglas.cobbDouglas( pool.fees, // totalRewards _indexerFees, pool.fees, _indexerEffectiveAllocatedStake, pool.effectiveAllocatedStake, pool.alphaNumerator, pool.alphaDenominator ); // Under NO circumstance we will reward more than total fees in the pool uint256 _unclaimedFees = pool.fees.sub(pool.claimedRewards); if (rebateReward > _unclaimedFees) { rebateReward = _unclaimedFees; } } // Update pool state pool.unclaimedAllocationsCount -= 1; pool.claimedRewards = pool.claimedRewards.add(rebateReward); return rebateReward; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title A collection of data structures and functions to manage the Indexer Stake state. * Used for low-level state changes, require() conditions should be evaluated * at the caller function scope. */ library Stakes { using SafeMath for uint256; using Stakes for Stakes.Indexer; struct Indexer { uint256 tokensStaked; // Tokens on the indexer stake (staked by the indexer) uint256 tokensAllocated; // Tokens used in allocations uint256 tokensLocked; // Tokens locked for withdrawal subject to thawing period uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn } /** * @dev Deposit tokens to the indexer stake. * @param stake Stake data * @param _tokens Amount of tokens to deposit */ function deposit(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensStaked = stake.tokensStaked.add(_tokens); } /** * @dev Release tokens from the indexer stake. * @param stake Stake data * @param _tokens Amount of tokens to release */ function release(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensStaked = stake.tokensStaked.sub(_tokens); } /** * @dev Allocate tokens from the main stack to a SubgraphDeployment. * @param stake Stake data * @param _tokens Amount of tokens to allocate */ function allocate(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensAllocated = stake.tokensAllocated.add(_tokens); } /** * @dev Unallocate tokens from a SubgraphDeployment back to the main stack. * @param stake Stake data * @param _tokens Amount of tokens to unallocate */ function unallocate(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensAllocated = stake.tokensAllocated.sub(_tokens); } /** * @dev Lock tokens until a thawing period pass. * @param stake Stake data * @param _tokens Amount of tokens to unstake * @param _period Period in blocks that need to pass before withdrawal */ function lockTokens( Stakes.Indexer storage stake, uint256 _tokens, uint256 _period ) internal { // Take into account period averaging for multiple unstake requests uint256 lockingPeriod = _period; if (stake.tokensLocked > 0) { lockingPeriod = stake.getLockingPeriod(_tokens, _period); } // Update balances stake.tokensLocked = stake.tokensLocked.add(_tokens); stake.tokensLockedUntil = block.number.add(lockingPeriod); } /** * @dev Unlock tokens. * @param stake Stake data * @param _tokens Amount of tokens to unkock */ function unlockTokens(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensLocked = stake.tokensLocked.sub(_tokens); if (stake.tokensLocked == 0) { stake.tokensLockedUntil = 0; } } /** * @dev Take all tokens out from the locked stake for withdrawal. * @param stake Stake data * @return Amount of tokens being withdrawn */ function withdrawTokens(Stakes.Indexer storage stake) internal returns (uint256) { // Calculate tokens that can be released uint256 tokensToWithdraw = stake.tokensWithdrawable(); if (tokensToWithdraw > 0) { // Reset locked tokens stake.unlockTokens(tokensToWithdraw); // Decrease indexer stake stake.release(tokensToWithdraw); } return tokensToWithdraw; } /** * @dev Get the locking period of the tokens to unstake. * If already unstaked before calculate the weighted average. * @param stake Stake data * @param _tokens Amount of tokens to unstake * @param _thawingPeriod Period in blocks that need to pass before withdrawal * @return The weighted average locking period */ function getLockingPeriod( Stakes.Indexer memory stake, uint256 _tokens, uint256 _thawingPeriod ) internal view returns (uint256) { uint256 blockNum = block.number; uint256 periodA = (stake.tokensLockedUntil > blockNum) ? stake.tokensLockedUntil.sub(blockNum) : 0; uint256 periodB = _thawingPeriod; uint256 stakeA = stake.tokensLocked; uint256 stakeB = _tokens; return periodA.mul(stakeA).add(periodB.mul(stakeB)).div(stakeA.add(stakeB)); } /** * @dev Return true if there are tokens staked by the Indexer. * @param stake Stake data * @return True if staked */ function hasTokens(Stakes.Indexer memory stake) internal pure returns (bool) { return stake.tokensStaked > 0; } /** * @dev Return the amount of tokens used in allocations and locked for withdrawal. * @param stake Stake data * @return Token amount */ function tokensUsed(Stakes.Indexer memory stake) internal pure returns (uint256) { return stake.tokensAllocated.add(stake.tokensLocked); } /** * @dev Return the amount of tokens staked not considering the ones that are already going * through the thawing period or are ready for withdrawal. We call it secure stake because * it is not subject to change by a withdraw call from the indexer. * @param stake Stake data * @return Token amount */ function tokensSecureStake(Stakes.Indexer memory stake) internal pure returns (uint256) { return stake.tokensStaked.sub(stake.tokensLocked); } /** * @dev Tokens free balance on the indexer stake that can be used for any purpose. * Any token that is allocated cannot be used as well as tokens that are going through the * thawing period or are withdrawable * Calc: tokensStaked - tokensAllocated - tokensLocked * @param stake Stake data * @return Token amount */ function tokensAvailable(Stakes.Indexer memory stake) internal pure returns (uint256) { return stake.tokensAvailableWithDelegation(0); } /** * @dev Tokens free balance on the indexer stake that can be used for allocations. * This function accepts a parameter for extra delegated capacity that takes into * account delegated tokens * @param stake Stake data * @param _delegatedCapacity Amount of tokens used from delegators to calculate availability * @return Token amount */ function tokensAvailableWithDelegation(Stakes.Indexer memory stake, uint256 _delegatedCapacity) internal pure returns (uint256) { uint256 tokensCapacity = stake.tokensStaked.add(_delegatedCapacity); uint256 _tokensUsed = stake.tokensUsed(); // If more tokens are used than the current capacity, the indexer is overallocated. // This means the indexer doesn't have available capacity to create new allocations. // We can reach this state when the indexer has funds allocated and then any // of these conditions happen: // - The delegationCapacity ratio is reduced. // - The indexer stake is slashed. // - A delegator removes enough stake. if (_tokensUsed > tokensCapacity) { // Indexer stake is over allocated: return 0 to avoid stake to be used until // the overallocation is restored by staking more tokens, unallocating tokens // or using more delegated funds return 0; } return tokensCapacity.sub(_tokensUsed); } /** * @dev Tokens available for withdrawal after thawing period. * @param stake Stake data * @return Token amount */ function tokensWithdrawable(Stakes.Indexer memory stake) internal view returns (uint256) { // No tokens to withdraw before locking period if (stake.tokensLockedUntil == 0 || block.number < stake.tokensLockedUntil) { return 0; } return stake.tokensLocked; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IGraphProxy { function admin() external returns (address); function setAdmin(address _newAdmin) external; function implementation() external returns (address); function pendingImplementation() external returns (address); function upgradeTo(address _newImplementation) external; function acceptUpgrade() external; function acceptUpgradeAndCall(bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IStakingData { /** * @dev Allocate GRT tokens for the purpose of serving queries of a subgraph deployment * An allocation is created in the allocate() function and consumed in claim() */ struct Allocation { address indexer; bytes32 subgraphDeploymentID; uint256 tokens; // Tokens allocated to a SubgraphDeployment uint256 createdAtEpoch; // Epoch when it was created uint256 closedAtEpoch; // Epoch when it was closed uint256 collectedFees; // Collected fees for the allocation uint256 effectiveAllocation; // Effective allocation when closed uint256 accRewardsPerAllocatedToken; // Snapshot used for reward calc } /** * @dev Represents a request to close an allocation with a specific proof of indexing. * This is passed when calling closeAllocationMany to define the closing parameters for * each allocation. */ struct CloseAllocationRequest { address allocationID; bytes32 poi; } // -- Delegation Data -- /** * @dev Delegation pool information. One per indexer. */ struct DelegationPool { uint32 cooldownBlocks; // Blocks to wait before updating parameters uint32 indexingRewardCut; // in PPM uint32 queryFeeCut; // in PPM uint256 updatedAtBlock; // Block when the pool was last updated uint256 tokens; // Total tokens as pool reserves uint256 shares; // Total shares minted in the pool mapping(address => Delegation) delegators; // Mapping of delegator => Delegation } /** * @dev Individual delegation data of a delegator in a pool. */ struct Delegation { uint256 shares; // Shares owned by a delegator in the pool uint256 tokensLocked; // Tokens locked for undelegation uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./IManaged.sol"; import "./IController.sol"; import "../curation/ICuration.sol"; import "../epochs/IEpochManager.sol"; import "../rewards/IRewardsManager.sol"; import "../staking/IStaking.sol"; import "../token/IGraphToken.sol"; /** * @title Graph Managed contract * @dev The Managed contract provides an interface for contracts to interact with the Controller * Inspired by Livepeer: * https://github.com/livepeer/protocol/blob/streamflow/contracts/Controller.sol */ contract Managed { // Controller that contract is registered with IController public controller; mapping(bytes32 => address) public addressCache; uint256[10] private __gap; event ParameterUpdated(string param); event SetController(address controller); function _notPartialPaused() internal view { require(!controller.paused(), "Paused"); require(!controller.partialPaused(), "Partial-paused"); } function _notPaused() internal view { require(!controller.paused(), "Paused"); } function _onlyGovernor() internal view { require(msg.sender == controller.getGovernor(), "Caller must be Controller governor"); } modifier notPartialPaused { _notPartialPaused(); _; } modifier notPaused { _notPaused(); _; } // Check if sender is controller modifier onlyController() { require(msg.sender == address(controller), "Caller must be Controller"); _; } modifier onlyGovernor() { _onlyGovernor(); _; } /** * @dev Initialize the controller */ function _initialize(address _controller) internal { _setController(_controller); } /** * @notice Set Controller. Only callable by current controller * @param _controller Controller contract address */ function setController(address _controller) external onlyController { _setController(_controller); } /** * @dev Set controller. * @param _controller Controller contract address */ function _setController(address _controller) internal { require(_controller != address(0), "Controller must be set"); controller = IController(_controller); emit SetController(_controller); } /** * @dev Return Curation interface * @return Curation contract registered with Controller */ function curation() internal view returns (ICuration) { return ICuration(controller.getContractProxy(keccak256("Curation"))); } /** * @dev Return EpochManager interface * @return Epoch manager contract registered with Controller */ function epochManager() internal view returns (IEpochManager) { return IEpochManager(controller.getContractProxy(keccak256("EpochManager"))); } /** * @dev Return RewardsManager interface * @return Rewards manager contract registered with Controller */ function rewardsManager() internal view returns (IRewardsManager) { return IRewardsManager(controller.getContractProxy(keccak256("RewardsManager"))); } /** * @dev Return Staking interface * @return Staking contract registered with Controller */ function staking() internal view returns (IStaking) { return IStaking(controller.getContractProxy(keccak256("Staking"))); } /** * @dev Return GraphToken interface * @return Graph token contract registered with Controller */ function graphToken() internal view returns (IGraphToken) { return IGraphToken(controller.getContractProxy(keccak256("GraphToken"))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IManaged { function setController(address _controller) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IController { function getGovernor() external view returns (address); // -- Registry -- function setContractProxy(bytes32 _id, address _contractAddress) external; function unsetContractProxy(bytes32 _id) external; function updateController(bytes32 _id, address _controller) external; function getContractProxy(bytes32 _id) external view returns (address); // -- Pausing -- function setPartialPaused(bool _partialPaused) external; function setPaused(bool _paused) external; function setPauseGuardian(address _newPauseGuardian) external; function paused() external view returns (bool); function partialPaused() external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./IGraphCurationToken.sol"; interface ICuration { // -- Pool -- struct CurationPool { uint256 tokens; // GRT Tokens stored as reserves for the subgraph deployment uint32 reserveRatio; // Ratio for the bonding curve IGraphCurationToken gcs; // Curation token contract for this curation pool } // -- Configuration -- function setDefaultReserveRatio(uint32 _defaultReserveRatio) external; function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external; function setCurationTaxPercentage(uint32 _percentage) external; // -- Curation -- function mint( bytes32 _subgraphDeploymentID, uint256 _tokensIn, uint256 _signalOutMin ) external returns (uint256, uint256); function burn( bytes32 _subgraphDeploymentID, uint256 _signalIn, uint256 _tokensOutMin ) external returns (uint256); function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external; // -- Getters -- function isCurated(bytes32 _subgraphDeploymentID) external view returns (bool); function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID) external view returns (uint256); function getCurationPoolSignal(bytes32 _subgraphDeploymentID) external view returns (uint256); function getCurationPoolTokens(bytes32 _subgraphDeploymentID) external view returns (uint256); function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn) external view returns (uint256, uint256); function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signalIn) external view returns (uint256); function curationTaxPercentage() external view returns (uint32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IEpochManager { // -- Configuration -- function setEpochLength(uint256 _epochLength) external; // -- Epochs function runEpoch() external; // -- Getters -- function isCurrentEpochRun() external view returns (bool); function blockNum() external view returns (uint256); function blockHash(uint256 _block) external view returns (bytes32); function currentEpoch() external view returns (uint256); function currentEpochBlock() external view returns (uint256); function currentEpochBlockSinceStart() external view returns (uint256); function epochsSince(uint256 _epoch) external view returns (uint256); function epochsSinceUpdate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IRewardsManager { /** * @dev Stores accumulated rewards and snapshots related to a particular SubgraphDeployment. */ struct Subgraph { uint256 accRewardsForSubgraph; uint256 accRewardsForSubgraphSnapshot; uint256 accRewardsPerSignalSnapshot; uint256 accRewardsPerAllocatedToken; } // -- Params -- function setIssuanceRate(uint256 _issuanceRate) external; // -- Denylist -- function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle) external; function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external; function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny) external; function isDenied(bytes32 _subgraphDeploymentID) external view returns (bool); // -- Getters -- function getNewRewardsPerSignal() external view returns (uint256); function getAccRewardsPerSignal() external view returns (uint256); function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID) external view returns (uint256); function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID) external view returns (uint256, uint256); function getRewards(address _allocationID) external view returns (uint256); // -- Updates -- function updateAccRewardsPerSignal() external returns (uint256); function takeRewards(address _allocationID) external returns (uint256); // -- Hooks -- function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID) external returns (uint256); function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IGraphToken is IERC20 { // -- Mint and Burn -- function burn(uint256 amount) external; function mint(address _to, uint256 _amount) external; // -- Mint Admin -- function addMinter(address _account) external; function removeMinter(address _account) external; function renounceMinter() external; function isMinter(address _account) external view returns (bool); // -- Permit -- function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IGraphCurationToken is IERC20 { function burnFrom(address _account, uint256 _amount) external; function mint(address _to, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // 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; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "./LibFixedMath.sol"; library LibCobbDouglas { /// @dev The cobb-douglas function used to compute fee-based rewards for /// staking pools in a given epoch. This function does not perform /// bounds checking on the inputs, but the following conditions /// need to be true: /// 0 <= fees / totalFees <= 1 /// 0 <= stake / totalStake <= 1 /// 0 <= alphaNumerator / alphaDenominator <= 1 /// @param totalRewards collected over an epoch. /// @param fees Fees attributed to the the staking pool. /// @param totalFees Total fees collected across all pools that earned rewards. /// @param stake Stake attributed to the staking pool. /// @param totalStake Total stake across all pools that earned rewards. /// @param alphaNumerator Numerator of `alpha` in the cobb-douglas function. /// @param alphaDenominator Denominator of `alpha` in the cobb-douglas /// function. /// @return rewards Rewards owed to the staking pool. function cobbDouglas( uint256 totalRewards, uint256 fees, uint256 totalFees, uint256 stake, uint256 totalStake, uint32 alphaNumerator, uint32 alphaDenominator ) public pure returns (uint256 rewards) { int256 feeRatio = LibFixedMath.toFixed(fees, totalFees); int256 stakeRatio = LibFixedMath.toFixed(stake, totalStake); if (feeRatio == 0 || stakeRatio == 0) { return rewards = 0; } // The cobb-doublas function has the form: // `totalRewards * feeRatio ^ alpha * stakeRatio ^ (1-alpha)` // This is equivalent to: // `totalRewards * stakeRatio * e^(alpha * (ln(feeRatio / stakeRatio)))` // However, because `ln(x)` has the domain of `0 < x < 1` // and `exp(x)` has the domain of `x < 0`, // and fixed-point math easily overflows with multiplication, // we will choose the following if `stakeRatio > feeRatio`: // `totalRewards * stakeRatio / e^(alpha * (ln(stakeRatio / feeRatio)))` // Compute // `e^(alpha * ln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio // or // `e^(alpa * ln(stakeRatio/feeRatio))` if feeRatio > stakeRatio int256 n = feeRatio <= stakeRatio ? LibFixedMath.div(feeRatio, stakeRatio) : LibFixedMath.div(stakeRatio, feeRatio); n = LibFixedMath.exp( LibFixedMath.mulDiv( LibFixedMath.ln(n), int256(alphaNumerator), int256(alphaDenominator) ) ); // Compute // `totalRewards * n` if feeRatio <= stakeRatio // or // `totalRewards / n` if stakeRatio > feeRatio // depending on the choice we made earlier. n = feeRatio <= stakeRatio ? LibFixedMath.mul(stakeRatio, n) : LibFixedMath.div(stakeRatio, n); // Multiply the above with totalRewards. rewards = LibFixedMath.uintMul(n, totalRewards); } } /* Copyright 2017 Bprotocol Foundation, 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; // solhint-disable indent /// @dev Signed, fixed-point, 127-bit precision math library. library LibFixedMath { // 1 int256 private constant FIXED_1 = int256( 0x0000000000000000000000000000000080000000000000000000000000000000 ); // 2**255 int256 private constant MIN_FIXED_VAL = int256( 0x8000000000000000000000000000000000000000000000000000000000000000 ); // 1^2 (in fixed-point) int256 private constant FIXED_1_SQUARED = int256( 0x4000000000000000000000000000000000000000000000000000000000000000 ); // 1 int256 private constant LN_MAX_VAL = FIXED_1; // e ^ -63.875 int256 private constant LN_MIN_VAL = int256( 0x0000000000000000000000000000000000000000000000000000000733048c5a ); // 0 int256 private constant EXP_MAX_VAL = 0; // -63.875 int256 private constant EXP_MIN_VAL = -int256( 0x0000000000000000000000000000001ff0000000000000000000000000000000 ); /// @dev Get one as a fixed-point number. function one() internal pure returns (int256 f) { f = FIXED_1; } /// @dev Returns the addition of two fixed point numbers, reverting on overflow. function add(int256 a, int256 b) internal pure returns (int256 c) { c = _add(a, b); } /// @dev Returns the addition of two fixed point numbers, reverting on overflow. function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b == MIN_FIXED_VAL) { revert("out-of-bounds"); } c = _add(a, -b); } /// @dev Returns the multiplication of two fixed point numbers, reverting on overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = _mul(a, b) / FIXED_1; } /// @dev Returns the division of two fixed point numbers. function div(int256 a, int256 b) internal pure returns (int256 c) { c = _div(_mul(a, FIXED_1), b); } /// @dev Performs (a * n) / d, without scaling for precision. function mulDiv( int256 a, int256 n, int256 d ) internal pure returns (int256 c) { c = _div(_mul(a, n), d); } /// @dev Returns the unsigned integer result of multiplying a fixed-point /// number with an integer, reverting if the multiplication overflows. /// Negative results are clamped to zero. function uintMul(int256 f, uint256 u) internal pure returns (uint256) { if (int256(u) < int256(0)) { revert("out-of-bounds"); } int256 c = _mul(f, int256(u)); if (c <= 0) { return 0; } return uint256(uint256(c) >> 127); } /// @dev Returns the absolute value of a fixed point number. function abs(int256 f) internal pure returns (int256 c) { if (f == MIN_FIXED_VAL) { revert("out-of-bounds"); } if (f >= 0) { c = f; } else { c = -f; } } /// @dev Returns 1 / `x`, where `x` is a fixed-point number. function invert(int256 f) internal pure returns (int256 c) { c = _div(FIXED_1_SQUARED, f); } /// @dev Convert signed `n` / 1 to a fixed-point number. function toFixed(int256 n) internal pure returns (int256 f) { f = _mul(n, FIXED_1); } /// @dev Convert signed `n` / `d` to a fixed-point number. function toFixed(int256 n, int256 d) internal pure returns (int256 f) { f = _div(_mul(n, FIXED_1), d); } /// @dev Convert unsigned `n` / 1 to a fixed-point number. /// Reverts if `n` is too large to fit in a fixed-point number. function toFixed(uint256 n) internal pure returns (int256 f) { if (int256(n) < int256(0)) { revert("out-of-bounds"); } f = _mul(int256(n), FIXED_1); } /// @dev Convert unsigned `n` / `d` to a fixed-point number. /// Reverts if `n` / `d` is too large to fit in a fixed-point number. function toFixed(uint256 n, uint256 d) internal pure returns (int256 f) { if (int256(n) < int256(0)) { revert("out-of-bounds"); } if (int256(d) < int256(0)) { revert("out-of-bounds"); } f = _div(_mul(int256(n), FIXED_1), int256(d)); } /// @dev Convert a fixed-point number to an integer. function toInteger(int256 f) internal pure returns (int256 n) { return f / FIXED_1; } /// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL function ln(int256 x) internal pure returns (int256 r) { if (x > LN_MAX_VAL) { revert("out-of-bounds"); } if (x <= 0) { revert("too-small"); } if (x == FIXED_1) { return 0; } if (x <= LN_MIN_VAL) { return EXP_MIN_VAL; } int256 y; int256 z; int256 w; // Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2 // For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522) // = 1 - 0.25 - log(1 + 0.0471028872385522) // e ^ -32 if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) { r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32 } // e ^ -16 if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) { r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16 } // e ^ -8 if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) { r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8 } // e ^ -4 if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) { r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4 } // e ^ -2 if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) { r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2 x = (x * FIXED_1) / int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2 } // e ^ -1 if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) { r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1 x = (x * FIXED_1) / int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1 } // e ^ -0.5 if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) { r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5 x = (x * FIXED_1) / int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5 } // e ^ -0.25 if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) { r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25 } // e ^ -0.125 if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) { r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125 } // `x` is now our residual in the range of 1 <= x <= 2 (or close enough). // Add the taylor series for log(1 + z), where z = x - 1 z = y = x - FIXED_1; w = (y * y) / FIXED_1; r += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 r += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 r += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 r += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 r += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 r += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 r += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 r += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 } /// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1 function exp(int256 x) internal pure returns (int256 r) { if (x < EXP_MIN_VAL) { // Saturate to zero below EXP_MIN_VAL. return 0; } if (x == 0) { return FIXED_1; } if (x > EXP_MAX_VAL) { revert("out-of-bounds"); } // Rewrite the input as a product of natural exponents and a // single residual q, where q is a number of small magnitude. // For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044) // = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044 // -> q = -0.044 // Multiply with the taylor series for e^q int256 y; int256 z; // q = x % 0.125 (the residual) z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000; z = (z * y) / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; r += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; r += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; r += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; r += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; r += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; r += z * 0x0000000000000001; // add y^20 * (20! / 20!) r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! // Multiply with the non-residual terms. x = -x; // e ^ -32 if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)) / int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32 } // e ^ -16 if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)) / int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16 } // e ^ -8 if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)) / int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8 } // e ^ -4 if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)) / int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4 } // e ^ -2 if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)) / int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2 } // e ^ -1 if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)) / int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1 } // e ^ -0.5 if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)) / int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5 } // e ^ -0.25 if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) / int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25 } // e ^ -0.125 if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)) / int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125 } } /// @dev Returns the multiplication two numbers, reverting on overflow. function _mul(int256 a, int256 b) private pure returns (int256 c) { if (a == 0) { return 0; } c = a * b; if (c / a != b || c / b != a) { revert("overflow"); } } /// @dev Returns the division of two numbers, reverting on division by zero. function _div(int256 a, int256 b) private pure returns (int256 c) { if (b == 0) { revert("overflow"); } if (a == MIN_FIXED_VAL && b == -1) { revert("overflow"); } c = a / b; } /// @dev Adds two numbers, reverting on overflow. function _add(int256 a, int256 b) private pure returns (int256 c) { c = a + b; if ((a < 0 && b < 0 && c > a) || (a > 0 && b > 0 && c < a)) { revert("overflow"); } } }
* @dev Getter that returns if an indexer has any stake. @param _indexer Address of the indexer @return True if indexer has staked tokens/
function hasStake(address _indexer) external view override returns (bool) { return stakes[_indexer].hasTokens(); }
11,693,090
[ 1, 8461, 716, 1135, 309, 392, 12635, 711, 1281, 384, 911, 18, 225, 389, 24541, 5267, 434, 326, 12635, 327, 1053, 309, 12635, 711, 384, 9477, 2430, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 711, 510, 911, 12, 2867, 389, 24541, 13, 3903, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 384, 3223, 63, 67, 24541, 8009, 5332, 5157, 5621, 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/80001/0x130257B2eB656623fAEcF46F8ec54513aF78EADE/sources/project_/contracts/HogwartsNFT.sol
takes tokenID and tokenURI
_setTokenURI(tokenId, houseTokenURIs[uint256(house)]);
9,528,221
[ 1, 88, 3223, 1147, 734, 471, 1147, 3098, 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, 3639, 389, 542, 1345, 3098, 12, 2316, 548, 16, 23867, 1345, 1099, 2520, 63, 11890, 5034, 12, 13028, 13, 19226, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-12-27 */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** * Implements a "lock" feature with a cooldown */ library Blocklock { struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } function setCooldownDuration(State storage self, uint256 cooldownDuration) public { self.cooldownDuration = cooldownDuration; } function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt + self.cooldownDuration ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self) + self.cooldownDuration; } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt + self.lockDuration; // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @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); } /** * @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; } } /** * @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; } /** * @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. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { if (_upperBound == 0) { return 0; } uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (block.number == 0) { // No existing node. //injected CONTRACT AFFECTED BY MINERS if (block.number != 0) { // Non zero value. //injected CONTRACT AFFECTED BY MINERS // Append. // Add node. if (block.number == 0) { // No vacant spots. //injected CONTRACT AFFECTED BY MINERS // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (block.number == 0) { // Zero value. //injected CONTRACT AFFECTED BY MINERS // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (block.timestamp != tree.nodes[treeIndex]) { // New, non zero value. //injected CONTRACT AFFECTED BY MINERS // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if (block.number >= tree.nodes.length) { //injected CONTRACT AFFECTED BY MINERS startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (block.timestamp < _count) { //injected CONTRACT AFFECTED BY MINERS values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (block.timestamp >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. //injected CONTRACT AFFECTED BY MINERS else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (block.gaslimit == 0) value = 0; //injected CONTRACT AFFECTED BY MINERS else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_LEAVES = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the first Draw index that an address deposited to. */ mapping(address => uint256) usersFirstDrawIndex; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) usersSecondDrawIndex; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_LEAVES); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_LEAVES); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; // if this is the users first draw, set it if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS self.usersFirstDrawIndex[_addr] = openDrawIndex; // otherwise, if the first draw is not this draw } else if (block.gaslimit != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // if a second draw does not exist if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS // set the second draw to the current draw self.usersSecondDrawIndex[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (block.timestamp != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // merge it into the first draw, and update the second draw index to this one uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); uint256 secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(secondAmount), _addr); drawSet(self, secondDrawIndex, 0, _addr); self.usersSecondDrawIndex[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; // if they have a committed balance if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(_amount), _addr); } else { // they must not have any committed balance self.usersSecondDrawIndex[_addr] = firstDrawIndex; self.usersFirstDrawIndex[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.usersFirstDrawIndex[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, firstDrawIndex, 0, _addr); delete self.usersFirstDrawIndex[_addr]; } if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, secondDrawIndex, 0, _addr); delete self.usersSecondDrawIndex[_addr]; } } function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; uint256 firstAmount = 0; uint256 secondAmount = 0; uint256 total = 0; if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); total = total.add(secondAmount); } if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); total = total.add(firstAmount); } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (block.timestamp > firstAmount) { //injected CONTRACT AFFECTED BY MINERS uint256 secondRemaining = remaining.sub(firstAmount); drawSet(self, secondDrawIndex, secondRemaining, _addr); } else if (block.gaslimit > 0) { // else delete the second amount if it exists //injected CONTRACT AFFECTED BY MINERS delete self.usersSecondDrawIndex[_addr]; drawSet(self, secondDrawIndex, 0, _addr); } // if the first amount needs to be destroyed if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS delete self.usersFirstDrawIndex[_addr]; drawSet(self, firstDrawIndex, 0, _addr); } else if (block.number < firstAmount) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, firstDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), bytes32(uint256(_addr)))); } if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (block.gaslimit != _amount) { //injected CONTRACT AFFECTED BY MINERS // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (block.timestamp != self.openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); uint256 drawIndex = uint256(self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token)); uint256 drawSupply = self.sortitionSumTrees.total(bytes32(drawIndex)); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(bytes32(drawIndex), drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { return draw(self, UniformRandomNumber.uniform(uint256(_entropy), committedSupply(self))); } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; BasePool internal _pool; function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } function pool() public view returns (address) { return address(_pool); } function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, true); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDeposit(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck Whether the recipient, when a contract, *must* have a IERC777Recipient implementor */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event Paused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event Unpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State drawState; /** * A structure containing the administrators */ Roles.Role admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(_poolToken.pool() == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Commits the current draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt)) */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt)) */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { blocklock.unlock(block.number); // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings = underlyingBalance.sub(accountedBalance); // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; awardWinnings(winningAddress, netWinnings); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } function awardWinnings(address winner, uint256 amount) internal { // Update balance of the winner balances[winner] = balances[winner].add(amount); // Enter their winnings into the open draw drawState.deposit(winner, amount); } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); uint256 openBalance = drawState.openBalanceOf(msg.sender); uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolRedeem(msg.sender, committedBalance); } emit SponsorshipAndFeesWithdrawn(msg.sender, sponsorshipAndFees); emit OpenDepositWithdrawn(msg.sender, openBalance); emit CommittedDepositWithdrawn(msg.sender, committedBalance); emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the users sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender] - drawState.balanceOf(_sender); } /** * Withdraws from the users open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public { drawState.withdrawOpen(msg.sender, _amount); _withdraw(msg.sender, _amount); emit OpenDepositWithdrawn(msg.sender, _amount); } /** * Withdraws from the users committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) external notLocked returns (bool) { _withdrawCommittedDepositAndEmit(msg.sender, _amount); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolRedeem(msg.sender, _amount); } return true; } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDeposit( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emit the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * Allows the associated PoolToken to move committed tokens from one user to another. */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (block.timestamp > 1) { //injected CONTRACT AFFECTED BY MINERS return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The users's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards, but eventually the Pool will grow smaller. */ function pause() public unlessPaused onlyAdmin { paused = true; emit Paused(msg.sender); } /** * Unpauses all deposits into the contract */ function unpause() public whenPaused onlyAdmin { paused = false; emit Unpaused(msg.sender); } function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } function canLock() public view returns (bool) { return blocklock.canLock(block.number); } function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } modifier whenPaused() { require(paused, "Pool/be-paused"); _; } modifier unlessPaused() { require(!paused, "Pool/not-paused"); _; } modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialze the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } function saiPoolToken() internal view returns (PoolToken) { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS return saiPool.poolToken(); } else { return PoolToken(0); } } function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
* @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. @param self The DrawManager state @param _addr The user to withdraw from @param _amount The amount to withdraw./
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; uint256 firstAmount = 0; uint256 secondAmount = 0; uint256 total = 0; if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); total = total.add(secondAmount); } if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); total = total.add(firstAmount); } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); drawSet(self, secondDrawIndex, secondRemaining, _addr); delete self.usersSecondDrawIndex[_addr]; drawSet(self, secondDrawIndex, 0, _addr); uint256 secondRemaining = remaining.sub(firstAmount); }
14,091,776
[ 1, 1190, 9446, 1807, 628, 279, 729, 1807, 16015, 11013, 18, 225, 8911, 87, 309, 326, 729, 7531, 358, 4862, 1898, 2353, 2319, 18, 225, 365, 1021, 10184, 1318, 919, 225, 389, 4793, 1021, 729, 358, 598, 9446, 628, 225, 389, 8949, 1021, 3844, 358, 598, 9446, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 598, 9446, 27813, 12, 1119, 2502, 365, 16, 1758, 389, 4793, 16, 2254, 5034, 389, 8949, 13, 1071, 2583, 27813, 6493, 12, 2890, 13, 1338, 3989, 7170, 24899, 4793, 13, 288, 203, 3639, 1731, 1578, 6249, 273, 1731, 1578, 12, 11890, 5034, 24899, 4793, 10019, 203, 3639, 2254, 5034, 1122, 6493, 1016, 273, 365, 18, 5577, 3759, 6493, 1016, 63, 67, 4793, 15533, 203, 3639, 2254, 5034, 2205, 6493, 1016, 273, 365, 18, 5577, 8211, 6493, 1016, 63, 67, 4793, 15533, 203, 203, 3639, 2254, 5034, 1122, 6275, 273, 374, 31, 203, 3639, 2254, 5034, 2205, 6275, 273, 374, 31, 203, 3639, 2254, 5034, 2078, 273, 374, 31, 203, 203, 3639, 309, 261, 8538, 6493, 1016, 480, 374, 597, 2205, 6493, 1016, 480, 365, 18, 3190, 6493, 1016, 13, 288, 203, 5411, 2205, 6275, 273, 365, 18, 3804, 608, 3495, 26590, 18, 334, 911, 951, 12, 3890, 1578, 12, 8538, 6493, 1016, 3631, 6249, 1769, 203, 5411, 2078, 273, 2078, 18, 1289, 12, 8538, 6275, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 3645, 6493, 1016, 480, 374, 597, 1122, 6493, 1016, 480, 365, 18, 3190, 6493, 1016, 13, 288, 203, 5411, 1122, 6275, 273, 365, 18, 3804, 608, 3495, 26590, 18, 334, 911, 951, 12, 3890, 1578, 12, 3645, 6493, 1016, 3631, 6249, 1769, 203, 5411, 2078, 273, 2078, 18, 1289, 12, 3645, 6275, 1769, 203, 3639, 289, 203, 203, 3639, 2583, 24899, 8949, 1648, 2078, 16, 315, 2864, 19, 338, 5288, 8863, 203, 203, 3639, 2254, 5034, 4463, 273, 2 ]
./full_match/41/0xE926495B33c40C275835F8BF3FECBb5742E37a45/sources/contracts/Dracma_ergon_final.sol
0x3939397c397c3939 (=999|9|99) 0x3032337c30327c31 (=023|1|05) 0x3032327c327c3939 (=022|2|99), tienen que ser ocho.
paydays[_addr] = plazos;
16,376,112
[ 1, 20, 92, 5520, 5520, 5520, 27, 71, 5520, 27, 71, 5520, 5520, 261, 33, 11984, 96, 29, 96, 2733, 13, 225, 374, 92, 5082, 1578, 3707, 27, 71, 5082, 1578, 27, 71, 6938, 261, 33, 3103, 23, 96, 21, 96, 6260, 13, 374, 92, 5082, 1578, 1578, 27, 71, 1578, 27, 71, 5520, 5520, 261, 33, 3103, 22, 96, 22, 96, 2733, 3631, 11374, 275, 275, 6597, 703, 320, 2599, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 8843, 9810, 63, 67, 4793, 65, 273, 886, 1561, 538, 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 ]
./partial_match/4/0x17e54471d69e59152e966DE03E29442A34cf19B5/sources/OptionFactory.sol
used by `createMarket` to avoid stack too deep error
contract OptionFactory is CloneFactory, OptionSymbol, ReentrancyGuard { using Address for address; using SafeERC20 for IERC20; using UniERC20 for IERC20; using SafeMath for uint256; address public optionMarketLibrary; address public optionTokenLibary; address[] public markets; address private oracle; uint256[] private strikePrices; uint256 private alpha; uint256 private expiryTime; bool private isPut; uint256 private tradingFee; constructor(address _optionMarketLibrary, address _optionTokenLibrary) public { require(_optionMarketLibrary != address(0), "optionMarketLibrary should not be address 0"); require(_optionTokenLibrary != address(0), "optionTokenLibary should not be address 0"); optionMarketLibrary = _optionMarketLibrary; optionTokenLibary = _optionTokenLibrary; } function createMarket( address _baseToken, address _quoteToken, address _oracle, uint256[] memory _strikePrices, uint256 _expiryTime, uint256 _alpha, bool _isPut, uint256 _tradingFee ) external nonReentrant returns (address market) { oracle = _oracle; strikePrices = _strikePrices; expiryTime = _expiryTime; alpha = _alpha; isPut = _isPut; tradingFee = _tradingFee; market = createClone(optionMarketLibrary); address baseToken = isPut ? _quoteToken : _baseToken; uint8 decimals = IERC20(baseToken).isETH() ? 18 : ERC20UpgradeSafe(baseToken).decimals(); string memory underlyingSymbol = IERC20(_baseToken).isETH() ? "ETH" : ERC20UpgradeSafe(_baseToken).symbol(); string memory symbol; address[] memory longTokens = new address[](strikePrices.length); address[] memory shortTokens = new address[](strikePrices.length); for (uint256 i = 0; i < strikePrices.length; i++) { longTokens[i] = createClone(optionTokenLibary); shortTokens[i] = createClone(optionTokenLibary); symbol = getSymbol(underlyingSymbol, strikePrices[i], expiryTime, isPut, true); OptionToken(longTokens[i]).initialize(market, symbol, symbol, decimals); symbol = getSymbol(underlyingSymbol, strikePrices[i], expiryTime, isPut, false); OptionToken(shortTokens[i]).initialize(market, symbol, symbol, decimals); } OptionMarket(market).initialize( baseToken, oracle, longTokens, shortTokens, strikePrices, expiryTime, alpha, isPut, tradingFee ); OptionMarket(market).transferOwnership(msg.sender); markets.push(market); } function createMarket( address _baseToken, address _quoteToken, address _oracle, uint256[] memory _strikePrices, uint256 _expiryTime, uint256 _alpha, bool _isPut, uint256 _tradingFee ) external nonReentrant returns (address market) { oracle = _oracle; strikePrices = _strikePrices; expiryTime = _expiryTime; alpha = _alpha; isPut = _isPut; tradingFee = _tradingFee; market = createClone(optionMarketLibrary); address baseToken = isPut ? _quoteToken : _baseToken; uint8 decimals = IERC20(baseToken).isETH() ? 18 : ERC20UpgradeSafe(baseToken).decimals(); string memory underlyingSymbol = IERC20(_baseToken).isETH() ? "ETH" : ERC20UpgradeSafe(_baseToken).symbol(); string memory symbol; address[] memory longTokens = new address[](strikePrices.length); address[] memory shortTokens = new address[](strikePrices.length); for (uint256 i = 0; i < strikePrices.length; i++) { longTokens[i] = createClone(optionTokenLibary); shortTokens[i] = createClone(optionTokenLibary); symbol = getSymbol(underlyingSymbol, strikePrices[i], expiryTime, isPut, true); OptionToken(longTokens[i]).initialize(market, symbol, symbol, decimals); symbol = getSymbol(underlyingSymbol, strikePrices[i], expiryTime, isPut, false); OptionToken(shortTokens[i]).initialize(market, symbol, symbol, decimals); } OptionMarket(market).initialize( baseToken, oracle, longTokens, shortTokens, strikePrices, expiryTime, alpha, isPut, tradingFee ); OptionMarket(market).transferOwnership(msg.sender); markets.push(market); } function numMarkets() external view returns (uint256) { return markets.length; } }
8,525,718
[ 1, 3668, 635, 1375, 2640, 3882, 278, 68, 358, 4543, 2110, 4885, 4608, 555, 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, 16351, 2698, 1733, 353, 12758, 1733, 16, 2698, 5335, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 1351, 77, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 1071, 1456, 3882, 278, 9313, 31, 203, 565, 1758, 1071, 1456, 1345, 5664, 814, 31, 203, 565, 1758, 8526, 1071, 2267, 2413, 31, 203, 203, 565, 1758, 3238, 20865, 31, 203, 565, 2254, 5034, 8526, 3238, 609, 2547, 31862, 31, 203, 565, 2254, 5034, 3238, 4190, 31, 203, 565, 2254, 5034, 3238, 10839, 950, 31, 203, 565, 1426, 3238, 353, 6426, 31, 203, 565, 2254, 5034, 3238, 1284, 7459, 14667, 31, 203, 203, 565, 3885, 12, 2867, 389, 3482, 3882, 278, 9313, 16, 1758, 389, 3482, 1345, 9313, 13, 1071, 288, 203, 3639, 2583, 24899, 3482, 3882, 278, 9313, 480, 1758, 12, 20, 3631, 315, 3482, 3882, 278, 9313, 1410, 486, 506, 1758, 374, 8863, 203, 3639, 2583, 24899, 3482, 1345, 9313, 480, 1758, 12, 20, 3631, 315, 3482, 1345, 5664, 814, 1410, 486, 506, 1758, 374, 8863, 203, 3639, 1456, 3882, 278, 9313, 273, 389, 3482, 3882, 278, 9313, 31, 203, 3639, 1456, 1345, 5664, 814, 273, 389, 3482, 1345, 9313, 31, 203, 565, 289, 203, 203, 565, 445, 752, 3882, 278, 12, 203, 3639, 1758, 389, 1969, 1345, 16, 203, 3639, 1758, 389, 6889, 1345, 16, 203, 3639, 1758, 389, 2 ]
./full_match/1/0x4Cf9CF96B4E737378F5deb61289B556a0321e4B7/sources/shittywok.sol
File contracts/SHITTYWOK.sol
contract SHITTYWOK is Ownable, ERC20 { bool public limited; uint256 public maxHoldingAmount; uint256 public minHoldingAmount; address public uniswapV2Pair; mapping(address => bool) public blacklists; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor() ERC20("SHITTYWOK", "SHITTYWOK") { _mint(msg.sender, 100_000_000_000 ether); } function blacklist(address _address, bool _isBlacklisting) external onlyOwner { blacklists[_address] = _isBlacklisting; } function setRule(bool _limited, address _uniswapV2Pair, uint256 _maxHoldingAmount, uint256 _minHoldingAmount) external onlyOwner { limited = _limited; uniswapV2Pair = _uniswapV2Pair; maxHoldingAmount = _maxHoldingAmount; minHoldingAmount = _minHoldingAmount; } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { require(!blacklists[to] && !blacklists[from], "Blacklisted"); if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && from == uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid"); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { require(!blacklists[to] && !blacklists[from], "Blacklisted"); if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && from == uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid"); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { require(!blacklists[to] && !blacklists[from], "Blacklisted"); if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && from == uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid"); } } function burn(uint256 value) external { _burn(msg.sender, value); } }
3,119,154
[ 1, 812, 20092, 19, 2664, 1285, 5538, 59, 3141, 18, 18281, 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, 6122, 1285, 5538, 59, 3141, 353, 14223, 6914, 16, 4232, 39, 3462, 288, 203, 565, 1426, 1071, 13594, 31, 203, 565, 2254, 5034, 1071, 943, 20586, 310, 6275, 31, 203, 565, 2254, 5034, 1071, 1131, 20586, 310, 6275, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 7721, 9772, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 2664, 1285, 5538, 59, 3141, 3113, 315, 2664, 1285, 5538, 59, 3141, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 67, 3784, 67, 3784, 67, 3784, 225, 2437, 1769, 203, 565, 289, 203, 203, 565, 445, 11709, 12, 2867, 389, 2867, 16, 1426, 389, 291, 13155, 21228, 13, 3903, 1338, 5541, 288, 203, 3639, 7721, 9772, 63, 67, 2867, 65, 273, 389, 291, 13155, 21228, 31, 203, 565, 289, 203, 203, 565, 445, 444, 2175, 12, 6430, 389, 21325, 16, 1758, 389, 318, 291, 91, 438, 58, 22, 4154, 16, 2254, 5034, 389, 1896, 20586, 310, 6275, 16, 2254, 5034, 389, 1154, 20586, 310, 6275, 13, 3903, 1338, 2 ]
pragma solidity ^0.4.26; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ 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); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract CHC is StandardToken, BurnableToken, Ownable { // Constants string public constant name = "Comprehensive Health Chain"; string public constant symbol = "CHC"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function () external payable { revert(); } }
* @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./ To change the approve amount you first have to reduce the addresses` allowance to zero by calling `approve(_spender, 0)` if it is not already 0 to mitigate the race condition described here: https:github.com/ethereum/EIPs/issues/20#issuecomment-263524729
function approve(address _spender, uint256 _value) public returns (bool) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
334,117
[ 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, 2974, 2549, 326, 6617, 537, 3844, 1846, 1122, 1240, 358, 5459, 326, 6138, 68, 225, 1699, 1359, 358, 3634, 635, 4440, 1375, 12908, 537, 24899, 87, 1302, 264, 16, 374, 22025, 309, 518, 353, 486, 225, 1818, 374, 358, 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, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 309, 14015, 67, 1132, 480, 374, 13, 597, 261, 8151, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 480, 374, 3719, 15226, 5621, 203, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 327, 638, 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 ]
pragma solidity >=0.7.0 <0.9.0; import "./storage.sol"; contract TokenStorage is Storage { // ----------------------------------------------------- // Usual storage // ----------------------------------------------------- // string public symbol; // string public name; // uint8 public decimals; // uint _totalSupply; // mapping(address => uint) balances; // mapping(address => mapping(address => uint)) allowed; // ----------------------------------------------------- // getter utilities // ----------------------------------------------------- function getSymbol() internal view returns (string memory) { return getString(keccak256(abi.encode("symbol"))); } function getName() internal view returns (string memory) { return getString(keccak256(abi.encode("name"))); } function getDecimals() internal view returns (uint8) { return uint8(getUint(keccak256(abi.encode("decimals")))) ; } function getTotalSupply() internal view returns (uint) { return getUint(keccak256(abi.encode("totalSupply"))); } function getBalance(address _account) internal view returns (uint) { return getUint(keccak256(abi.encode("balance", _account))); } function getAllowed(address _account, address _spender) internal view returns (uint) { return getUint(keccak256(abi.encode("allowed", _account, _spender))); } // ----------------------------------------------------- // setter utilities // ----------------------------------------------------- function setSymbol(string memory _symbol) internal { setString(keccak256(abi.encode("symbol")), _symbol); } function setName(string memory _name) internal { setString(keccak256(abi.encode("name")), _name); } function setDecimals(uint8 _decimals) internal { setUint(keccak256(abi.encode("decimals")), _decimals); } function setTotalSupply(uint _totalSupply) internal { setUint(keccak256(abi.encode("totalSupply")), _totalSupply); } function setBalance(address _account, uint _balance) internal { setUint(keccak256(abi.encode("balance", _account)), _balance); } function setAllowed(address _account, address _spender, uint _allowance) internal { setUint(keccak256(abi.encode("allowed", _account, _spender)), _allowance); } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ // Token constructor here so it is also inheritted by our proxy. Needed to set some constants constructor() { setSymbol("TFT"); setName("TFT on BSC"); // Use 7 decimals instead of 9, this way we have the same amount of decimals in both TFT and this Token uint8 _decimals = 7; setDecimals(_decimals); // Set initial supply to 0 setTotalSupply(0); } }
------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ Token constructor here so it is also inheritted by our proxy. Needed to set some constants Use 7 decimals instead of 9, this way we have the same amount of decimals in both TFT and this Token Set initial supply to 0
constructor() { setSymbol("TFT"); setName("TFT on BSC"); uint8 _decimals = 7; setDecimals(_decimals); setTotalSupply(0); }
12,848,765
[ 1, 29461, 11417, 8879, 17082, 3155, 3885, 2674, 1427, 518, 353, 2546, 6811, 2344, 635, 3134, 2889, 18, 26480, 358, 444, 2690, 6810, 2672, 2371, 15105, 3560, 434, 2468, 16, 333, 4031, 732, 1240, 326, 1967, 3844, 434, 15105, 316, 3937, 399, 4464, 471, 333, 3155, 1000, 2172, 14467, 358, 374, 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, 3885, 1435, 288, 203, 3639, 444, 5335, 2932, 56, 4464, 8863, 203, 3639, 6788, 2932, 56, 4464, 603, 605, 2312, 8863, 203, 203, 3639, 2254, 28, 389, 31734, 273, 2371, 31, 203, 3639, 444, 31809, 24899, 31734, 1769, 203, 203, 3639, 25015, 3088, 1283, 12, 20, 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 ]
./partial_match/1/0x8770B2a109AEE8CDbe278FaE6CaE5Aa4Bcd13E1c/sources/Users/ryanbreen/Workspace/Alkemi/alkemi-earn/alkemi-earn-protocol/contracts/MoneyMarketV11.sol
* @dev Managers for this contract with limited permissions. Can be changed by the admin./
mapping (address => bool) public managers;
3,595,220
[ 1, 17570, 364, 333, 6835, 598, 13594, 4371, 18, 4480, 1377, 506, 3550, 635, 326, 3981, 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 ]
[ 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, 2874, 261, 2867, 516, 1426, 13, 1071, 21103, 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 ]
// SPDX-License-Identifier: MIT // +build ovm pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L2ToL1MessagePasser } from "../../iOVM/precompiles/iOVM_L2ToL1MessagePasser.sol"; /** * @title OVM_L2ToL1MessagePasser * @dev L2 CONTRACT (COMPILED) */ contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser { /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public sentMessages; /******************** * Public Functions * ********************/ /** * Passes a message to L1. * @param _message Message to pass to L1. */ function passMessageToL1( bytes memory _message ) override public { sentMessages[keccak256( abi.encodePacked( _message, msg.sender ) )] = true; } }
Interface Imports */
import { iOVM_L2ToL1MessagePasser } from "../../iOVM/precompiles/iOVM_L2ToL1MessagePasser.sol";
12,972,936
[ 1, 1358, 2221, 4363, 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, 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, 5666, 288, 277, 51, 7397, 67, 48, 22, 774, 48, 21, 1079, 6433, 264, 289, 628, 315, 16644, 77, 51, 7397, 19, 1484, 2919, 1449, 19, 77, 51, 7397, 67, 48, 22, 774, 48, 21, 1079, 6433, 264, 18, 18281, 14432, 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 ]
pragma solidity ^0.4.19; // Turn the usage of callcode contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } contract CreatorEnabled { address public creator = 0x0; modifier onlyCreator() { require(msg.sender==creator); _; } function changeCreator(address _to) public onlyCreator { creator = _to; } } // ERC20 standard contract StdToken is SafeMath { // Fields: mapping(address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; uint public totalSupply = 0; // Events: event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); // Functions: function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns(bool) { require(0x0!=_to); balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns(bool) { require(0x0!=_to); balances[_to] = safeAdd(balances[_to],_value); balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } modifier onlyPayloadSize(uint _size) { require(msg.data.length >= _size + 4); _; } } contract IGoldFee { function calculateFee( bool _isMigrationStarted, bool _isMigrationFinished, uint _mntpBalance, uint _value) public constant returns(uint); } contract GoldFee is CreatorEnabled { // Functions: function GoldFee() { creator = msg.sender; } function getMin(uint out)returns (uint) { // 0.002 GOLD is min fee uint minFee = (2 * 1 ether) / 1000; if (out < minFee) { return minFee; } return out; } function getMax(uint out)returns (uint) { // 0.02 GOLD is max fee uint maxFee = (2 * 1 ether) / 100; if (out >= maxFee) { return maxFee; } return out; } function calculateFee( bool _isMigrationStarted, bool _isMigrationFinished, uint _mntpBalance, uint _value) public constant returns(uint) { // When migration process is finished (1 year from Goldmint blockchain launch), then transaction fee is 1% GOLD. if (_isMigrationFinished) { return (_value / 100); } // If the sender holds 0 MNTP, then the transaction fee is 1% GOLD. // If the sender holds at least 10 MNTP, then the transaction fee is 0.333333% GOLD, // but not less than 0.002 MNTP // If the sender holds at least 1000 MNTP, then the transaction fee is 0.033333% GOLD, // but not less than 0.002 MNTP // If the sender holds at least 10000 MNTP, then the transaction fee is 0.0333333% GOLD, // but not more than 0.02 MNTP if (_mntpBalance >= (10000 * 1 ether)) { return getMax((_value / 100) / 30); } if (_mntpBalance >= (1000 * 1 ether)) { return getMin((_value / 100) / 30); } if (_mntpBalance >= (10 * 1 ether)) { return getMin((_value / 100) / 3); } // 1% return getMin(_value / 100); } } contract Gold is StdToken, CreatorEnabled { // Fields: string public constant name = "Goldmint GOLD Token"; string public constant symbol = "GOLD"; uint8 public constant decimals = 18; // this is used to send fees (that is then distributed as rewards) address public migrationAddress = 0x0; address public storageControllerAddress = 0x0; address public goldmintTeamAddress = 0x0; IMNTP public mntpToken; IGoldFee public goldFee; bool public transfersLocked = false; bool public contractLocked = false; bool public migrationStarted = false; bool public migrationFinished = false; uint public totalIssued = 0; uint public totalBurnt = 0; // Modifiers: modifier onlyMigration() { require(msg.sender == migrationAddress); _; } modifier onlyCreator() { require(msg.sender == creator); _; } modifier onlyMigrationOrStorageController() { require(msg.sender == migrationAddress || msg.sender == storageControllerAddress); _; } modifier onlyCreatorOrStorageController() { require(msg.sender == creator || msg.sender == storageControllerAddress); _; } modifier onlyIfUnlocked() { require(!transfersLocked); _; } // Functions: function Gold(address _mntpContractAddress, address _goldmintTeamAddress, address _goldFeeAddress) public { creator = msg.sender; mntpToken = IMNTP(_mntpContractAddress); goldmintTeamAddress = _goldmintTeamAddress; goldFee = IGoldFee(_goldFeeAddress); } function setCreator(address _address) public onlyCreator { creator = _address; } function lockContract(bool _contractLocked) public onlyCreator { contractLocked = _contractLocked; } function setStorageControllerContractAddress(address _address) public onlyCreator { storageControllerAddress = _address; } function setMigrationContractAddress(address _migrationAddress) public onlyCreator { migrationAddress = _migrationAddress; } function setGoldmintTeamAddress(address _teamAddress) public onlyCreator { goldmintTeamAddress = _teamAddress; } function setGoldFeeAddress(address _goldFeeAddress) public onlyCreator { goldFee = IGoldFee(_goldFeeAddress); } function issueTokens(address _who, uint _tokens) public onlyCreatorOrStorageController { require(!contractLocked); balances[_who] = safeAdd(balances[_who],_tokens); totalSupply = safeAdd(totalSupply,_tokens); totalIssued = safeAdd(totalIssued,_tokens); Transfer(0x0, _who, _tokens); } function burnTokens(address _who, uint _tokens) public onlyMigrationOrStorageController { require(!contractLocked); balances[_who] = safeSub(balances[_who],_tokens); totalSupply = safeSub(totalSupply,_tokens); totalBurnt = safeAdd(totalBurnt,_tokens); } // there is no way to revert that function startMigration() public onlyMigration { require(false == migrationStarted); migrationStarted = true; } // there is no way to revert that function finishMigration() public onlyMigration { require(true == migrationStarted); migrationFinished = true; } function lockTransfer(bool _lock) public onlyMigration { transfersLocked = _lock; } function transfer(address _to, uint256 _value) public onlyIfUnlocked onlyPayloadSize(2 * 32) returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(msg.sender); // you can transfer if fee is ZERO uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); uint sendThis = _value; if (0 != fee) { sendThis = safeSub(_value,fee); // 1.Transfer fee // A -> rewards account // // Each GOLD token transfer should send transaction fee to // GoldmintMigration contract if Migration process is not started. // Goldmint team if Migration process is started. if (migrationStarted) { super.transfer(goldmintTeamAddress, fee); } else { super.transfer(migrationAddress, fee); } } // 2.Transfer // A -> B return super.transfer(_to, sendThis); } function transferFrom(address _from, address _to, uint256 _value) public onlyIfUnlocked returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(_from); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); if (0 != fee) { // 1.Transfer fee // A -> rewards account // // Each GOLD token transfer should send transaction fee to // GoldmintMigration contract if Migration process is not started. // Goldmint team if Migration process is started. if (migrationStarted) { super.transferFrom(_from, goldmintTeamAddress, fee); } else { super.transferFrom(_from, migrationAddress, fee); } } // 2.Transfer // A -> B uint sendThis = safeSub(_value,fee); return super.transferFrom(_from, _to, sendThis); } // Used to send rewards) function transferRewardWithoutFee(address _to, uint _value) public onlyMigration onlyPayloadSize(2*32) { require(0x0!=_to); balances[migrationAddress] = safeSub(balances[migrationAddress],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(migrationAddress, _to, _value); } // This is an emergency function that can be called by Creator only function rescueAllRewards(address _to) public onlyCreator { require(0x0!=_to); uint totalReward = balances[migrationAddress]; balances[_to] = safeAdd(balances[_to],totalReward); balances[migrationAddress] = 0; Transfer(migrationAddress, _to, totalReward); } function getTotalIssued() public constant returns (uint) { return totalIssued; } function getTotalBurnt() public constant returns (uint) { return totalBurnt; } } contract IMNTP is StdToken { // Additional methods that MNTP contract provides function lockTransfer(bool _lock); function issueTokens(address _who, uint _tokens); function burnTokens(address _who, uint _tokens); } contract GoldmintMigration is CreatorEnabled { // Fields: IMNTP public mntpToken; Gold public goldToken; enum State { Init, MigrationStarted, MigrationPaused, MigrationFinished } State public state = State.Init; // this is total collected GOLD rewards (launch to migration start) uint public mntpToMigrateTotal = 0; uint public migrationRewardTotal = 0; uint64 public migrationStartedTime = 0; uint64 public migrationFinishedTime = 0; struct Migration { address ethAddress; string gmAddress; uint tokensCount; bool migrated; uint64 date; string comment; } mapping (uint=>Migration) public mntpMigrations; mapping (address=>uint) public mntpMigrationIndexes; uint public mntpMigrationsCount = 0; mapping (uint=>Migration) public goldMigrations; mapping (address=>uint) public goldMigrationIndexes; uint public goldMigrationsCount = 0; event MntpMigrateWanted(address _ethAddress, string _gmAddress, uint256 _value); event MntpMigrated(address _ethAddress, string _gmAddress, uint256 _value); event GoldMigrateWanted(address _ethAddress, string _gmAddress, uint256 _value); event GoldMigrated(address _ethAddress, string _gmAddress, uint256 _value); // Access methods function getMntpMigration(uint index) public constant returns(address,string,uint,bool,uint64,string){ Migration memory mig = mntpMigrations[index]; return (mig.ethAddress, mig.gmAddress, mig.tokensCount, mig.migrated, mig.date, mig.comment); } function getGoldMigration(uint index) public constant returns(address,string,uint,bool,uint64,string){ Migration memory mig = goldMigrations[index]; return (mig.ethAddress, mig.gmAddress, mig.tokensCount, mig.migrated, mig.date, mig.comment); } // Functions: // Constructor function GoldmintMigration(address _mntpContractAddress, address _goldContractAddress) public { creator = msg.sender; require(_mntpContractAddress != 0); require(_goldContractAddress != 0); mntpMigrationIndexes[address(0x0)] = 0; goldMigrationIndexes[address(0x0)] = 0; mntpToken = IMNTP(_mntpContractAddress); goldToken = Gold(_goldContractAddress); } function lockMntpTransfers(bool _lock) public onlyCreator { mntpToken.lockTransfer(_lock); } function lockGoldTransfers(bool _lock) public onlyCreator { goldToken.lockTransfer(_lock); } // This method is called when migration to Goldmint's blockchain // process is started... function startMigration() public onlyCreator { require((State.Init == state) || (State.MigrationPaused == state)); if (State.Init == state) { // 1 - change fees goldToken.startMigration(); // 2 - store the current values migrationRewardTotal = goldToken.balanceOf(this); migrationStartedTime = uint64(now); mntpToMigrateTotal = mntpToken.totalSupply(); } state = State.MigrationStarted; } function pauseMigration() public onlyCreator { require((state == State.MigrationStarted) || (state == State.MigrationFinished)); state = State.MigrationPaused; } // that doesn't mean that you cant migrate from Ethereum -> Goldmint blockchain // that means that you will get no reward function finishMigration() public onlyCreator { require((State.MigrationStarted == state) || (State.MigrationPaused == state)); if (State.MigrationStarted == state) { goldToken.finishMigration(); migrationFinishedTime = uint64(now); } state = State.MigrationFinished; } function destroyMe() public onlyCreator { selfdestruct(msg.sender); } // MNTP // Call this to migrate your MNTP tokens to Goldmint MNT // (this is one-way only) // _gmAddress is something like that - "BTS7yRXCkBjKxho57RCbqYE3nEiprWXXESw3Hxs5CKRnft8x7mdGi" // // !!! WARNING: will not allow anyone to migrate tokens partly // !!! DISCLAIMER: check goldmint blockchain address format. You will not be able to change that! function migrateMntp(string _gmAddress) public { require((state==State.MigrationStarted) || (state==State.MigrationFinished)); // 1 - calculate current reward uint myBalance = mntpToken.balanceOf(msg.sender); require(0!=myBalance); uint myRewardMax = calculateMyRewardMax(msg.sender); uint myReward = calculateMyReward(myRewardMax); // 2 - pay the reward to our user goldToken.transferRewardWithoutFee(msg.sender, myReward); // 3 - burn tokens // WARNING: burn will reduce totalSupply // // WARNING: creator must call // setIcoContractAddress(migrationContractAddress) // of the mntpToken mntpToken.burnTokens(msg.sender,myBalance); // save tuple Migration memory mig; mig.ethAddress = msg.sender; mig.gmAddress = _gmAddress; mig.tokensCount = myBalance; mig.migrated = false; mig.date = uint64(now); mig.comment = ''; mntpMigrations[mntpMigrationsCount + 1] = mig; mntpMigrationIndexes[msg.sender] = mntpMigrationsCount + 1; mntpMigrationsCount++; // send an event MntpMigrateWanted(msg.sender, _gmAddress, myBalance); } function isMntpMigrated(address _who) public constant returns(bool) { uint index = mntpMigrationIndexes[_who]; Migration memory mig = mntpMigrations[index]; return mig.migrated; } function setMntpMigrated(address _who, bool _isMigrated, string _comment) public onlyCreator { uint index = mntpMigrationIndexes[_who]; require(index > 0); mntpMigrations[index].migrated = _isMigrated; mntpMigrations[index].comment = _comment; // send an event if (_isMigrated) { MntpMigrated( mntpMigrations[index].ethAddress, mntpMigrations[index].gmAddress, mntpMigrations[index].tokensCount); } } // GOLD function migrateGold(string _gmAddress) public { require((state==State.MigrationStarted) || (state==State.MigrationFinished)); // 1 - get balance uint myBalance = goldToken.balanceOf(msg.sender); require(0!=myBalance); // 2 - burn tokens // WARNING: burn will reduce totalSupply // goldToken.burnTokens(msg.sender,myBalance); // save tuple Migration memory mig; mig.ethAddress = msg.sender; mig.gmAddress = _gmAddress; mig.tokensCount = myBalance; mig.migrated = false; mig.date = uint64(now); mig.comment = ''; goldMigrations[goldMigrationsCount + 1] = mig; goldMigrationIndexes[msg.sender] = goldMigrationsCount + 1; goldMigrationsCount++; // send an event GoldMigrateWanted(msg.sender, _gmAddress, myBalance); } function isGoldMigrated(address _who) public constant returns(bool) { uint index = goldMigrationIndexes[_who]; Migration memory mig = goldMigrations[index]; return mig.migrated; } function setGoldMigrated(address _who, bool _isMigrated, string _comment) public onlyCreator { uint index = goldMigrationIndexes[_who]; require(index > 0); goldMigrations[index].migrated = _isMigrated; goldMigrations[index].comment = _comment; // send an event if (_isMigrated) { GoldMigrated( goldMigrations[index].ethAddress, goldMigrations[index].gmAddress, goldMigrations[index].tokensCount); } } // Each MNTP token holder gets a GOLD reward as a percent of all rewards // proportional to his MNTP token stake function calculateMyRewardMax(address _of) public constant returns(uint){ if (0 == mntpToMigrateTotal) { return 0; } uint myCurrentMntpBalance = mntpToken.balanceOf(_of); if (0 == myCurrentMntpBalance) { return 0; } return (migrationRewardTotal * myCurrentMntpBalance) / mntpToMigrateTotal; } // Migration rewards decreased linearly. // // The formula is: rewardPercents = max(100 - 100 * day / 365, 0) // // On 1st day of migration, you will get: 100 - 100 * 0/365 = 100% of your rewards // On 2nd day of migration, you will get: 100 - 100 * 1/365 = 99.7261% of your rewards // On 365th day of migration, you will get: 100 - 100 * 364/365 = 0.274% function calculateMyRewardDecreased(uint _day, uint _myRewardMax) public constant returns(uint){ if (_day >= 365) { return 0; } uint x = ((100 * 1000000000 * _day) / 365); return (_myRewardMax * ((100 * 1000000000) - x)) / (100 * 1000000000); } function calculateMyReward(uint _myRewardMax) public constant returns(uint){ // day starts from 0 uint day = (uint64(now) - migrationStartedTime) / uint64(1 days); return calculateMyRewardDecreased(day, _myRewardMax); } ///////// // do not allow to send money to this contract... function() external payable { revert(); } }
Fields: this is used to send fees (that is then distributed as rewards) Modifiers: Functions:
contract Gold is StdToken, CreatorEnabled { string public constant name = "Goldmint GOLD Token"; string public constant symbol = "GOLD"; uint8 public constant decimals = 18; address public migrationAddress = 0x0; address public storageControllerAddress = 0x0; address public goldmintTeamAddress = 0x0; IMNTP public mntpToken; IGoldFee public goldFee; bool public transfersLocked = false; bool public contractLocked = false; bool public migrationStarted = false; bool public migrationFinished = false; uint public totalIssued = 0; uint public totalBurnt = 0; modifier onlyMigration() { require(msg.sender == migrationAddress); _; } modifier onlyCreator() { require(msg.sender == creator); _; } modifier onlyMigrationOrStorageController() { require(msg.sender == migrationAddress || msg.sender == storageControllerAddress); _; } modifier onlyCreatorOrStorageController() { require(msg.sender == creator || msg.sender == storageControllerAddress); _; } modifier onlyIfUnlocked() { require(!transfersLocked); _; } function Gold(address _mntpContractAddress, address _goldmintTeamAddress, address _goldFeeAddress) public { creator = msg.sender; mntpToken = IMNTP(_mntpContractAddress); goldmintTeamAddress = _goldmintTeamAddress; goldFee = IGoldFee(_goldFeeAddress); } function setCreator(address _address) public onlyCreator { creator = _address; } function lockContract(bool _contractLocked) public onlyCreator { contractLocked = _contractLocked; } function setStorageControllerContractAddress(address _address) public onlyCreator { storageControllerAddress = _address; } function setMigrationContractAddress(address _migrationAddress) public onlyCreator { migrationAddress = _migrationAddress; } function setGoldmintTeamAddress(address _teamAddress) public onlyCreator { goldmintTeamAddress = _teamAddress; } function setGoldFeeAddress(address _goldFeeAddress) public onlyCreator { goldFee = IGoldFee(_goldFeeAddress); } function issueTokens(address _who, uint _tokens) public onlyCreatorOrStorageController { require(!contractLocked); balances[_who] = safeAdd(balances[_who],_tokens); totalSupply = safeAdd(totalSupply,_tokens); totalIssued = safeAdd(totalIssued,_tokens); Transfer(0x0, _who, _tokens); } function burnTokens(address _who, uint _tokens) public onlyMigrationOrStorageController { require(!contractLocked); balances[_who] = safeSub(balances[_who],_tokens); totalSupply = safeSub(totalSupply,_tokens); totalBurnt = safeAdd(totalBurnt,_tokens); } function startMigration() public onlyMigration { require(false == migrationStarted); migrationStarted = true; } function finishMigration() public onlyMigration { require(true == migrationStarted); migrationFinished = true; } function lockTransfer(bool _lock) public onlyMigration { transfersLocked = _lock; } function transfer(address _to, uint256 _value) public onlyIfUnlocked onlyPayloadSize(2 * 32) returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(msg.sender); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); uint sendThis = _value; if (0 != fee) { sendThis = safeSub(_value,fee); if (migrationStarted) { super.transfer(goldmintTeamAddress, fee); super.transfer(migrationAddress, fee); } } } function transfer(address _to, uint256 _value) public onlyIfUnlocked onlyPayloadSize(2 * 32) returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(msg.sender); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); uint sendThis = _value; if (0 != fee) { sendThis = safeSub(_value,fee); if (migrationStarted) { super.transfer(goldmintTeamAddress, fee); super.transfer(migrationAddress, fee); } } } function transfer(address _to, uint256 _value) public onlyIfUnlocked onlyPayloadSize(2 * 32) returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(msg.sender); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); uint sendThis = _value; if (0 != fee) { sendThis = safeSub(_value,fee); if (migrationStarted) { super.transfer(goldmintTeamAddress, fee); super.transfer(migrationAddress, fee); } } } } else { return super.transfer(_to, sendThis); function transferFrom(address _from, address _to, uint256 _value) public onlyIfUnlocked returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(_from); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); if (0 != fee) { if (migrationStarted) { super.transferFrom(_from, goldmintTeamAddress, fee); super.transferFrom(_from, migrationAddress, fee); } } return super.transferFrom(_from, _to, sendThis); } function transferFrom(address _from, address _to, uint256 _value) public onlyIfUnlocked returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(_from); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); if (0 != fee) { if (migrationStarted) { super.transferFrom(_from, goldmintTeamAddress, fee); super.transferFrom(_from, migrationAddress, fee); } } return super.transferFrom(_from, _to, sendThis); } function transferFrom(address _from, address _to, uint256 _value) public onlyIfUnlocked returns(bool) { uint yourCurrentMntpBalance = mntpToken.balanceOf(_from); uint fee = goldFee.calculateFee(migrationStarted, migrationFinished, yourCurrentMntpBalance, _value); if (0 != fee) { if (migrationStarted) { super.transferFrom(_from, goldmintTeamAddress, fee); super.transferFrom(_from, migrationAddress, fee); } } return super.transferFrom(_from, _to, sendThis); } } else { uint sendThis = safeSub(_value,fee); function transferRewardWithoutFee(address _to, uint _value) public onlyMigration onlyPayloadSize(2*32) { require(0x0!=_to); balances[migrationAddress] = safeSub(balances[migrationAddress],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(migrationAddress, _to, _value); } function rescueAllRewards(address _to) public onlyCreator { require(0x0!=_to); uint totalReward = balances[migrationAddress]; balances[_to] = safeAdd(balances[_to],totalReward); balances[migrationAddress] = 0; Transfer(migrationAddress, _to, totalReward); } function getTotalIssued() public constant returns (uint) { return totalIssued; } function getTotalBurnt() public constant returns (uint) { return totalBurnt; } }
11,687,779
[ 1, 2314, 30, 333, 353, 1399, 358, 1366, 1656, 281, 261, 19056, 353, 1508, 16859, 487, 283, 6397, 13, 3431, 3383, 30, 15486, 30, 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, 16351, 611, 1673, 353, 6276, 1345, 16, 29525, 1526, 288, 203, 377, 533, 1071, 5381, 508, 273, 315, 43, 1673, 81, 474, 611, 11846, 3155, 14432, 203, 377, 533, 1071, 5381, 3273, 273, 315, 43, 11846, 14432, 203, 377, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 377, 1758, 1071, 6333, 1887, 273, 374, 92, 20, 31, 203, 377, 1758, 1071, 2502, 2933, 1887, 273, 374, 92, 20, 31, 203, 203, 377, 1758, 1071, 20465, 81, 474, 8689, 1887, 273, 374, 92, 20, 31, 203, 377, 6246, 1784, 52, 1071, 312, 496, 84, 1345, 31, 203, 377, 13102, 1673, 14667, 1071, 20465, 14667, 31, 203, 1377, 203, 203, 377, 1426, 1071, 29375, 8966, 273, 629, 31, 203, 377, 1426, 1071, 6835, 8966, 273, 629, 31, 203, 377, 1426, 1071, 6333, 9217, 273, 629, 31, 203, 377, 1426, 1071, 6333, 10577, 273, 629, 31, 203, 203, 377, 2254, 1071, 2078, 7568, 5957, 273, 374, 31, 203, 377, 2254, 1071, 2078, 38, 321, 88, 273, 374, 31, 203, 203, 203, 203, 377, 9606, 1338, 10224, 1435, 288, 2583, 12, 3576, 18, 15330, 422, 6333, 1887, 1769, 389, 31, 289, 203, 377, 9606, 1338, 10636, 1435, 288, 2583, 12, 3576, 18, 15330, 422, 11784, 1769, 389, 31, 289, 203, 377, 9606, 1338, 10224, 1162, 3245, 2933, 1435, 288, 2583, 12, 3576, 18, 15330, 422, 6333, 1887, 747, 1234, 18, 15330, 422, 2502, 2933, 1887, 1769, 389, 31, 289, 203, 377, 9606, 1338, 10636, 1162, 3245, 2933, 1435, 288, 2583, 12, 3576, 18, 15330, 422, 11784, 2 ]
./full_match/4/0x3B0dE749344778659D77CED7b076e00fB7378731/sources/contracts/pix_v5.sol
/ add the deposited tokens into existing balance transfer the tokens from the sender to this contract
function DepositRewardsPool(uint256 rewards_for_block_owners) external { require(token.balanceOf(msg.sender) >= rewards_for_block_owners, "token balance too low"); owners_rewards_pool += rewards_for_block_owners; require(token.transferFrom(msg.sender, address(this), rewards_for_block_owners), "token transfer failed"); @dev Deposit Tokens into the reward pool for the system. Used once at the beginning of the system by the developper team }
683,533
[ 1, 19, 527, 326, 443, 1724, 329, 2430, 1368, 2062, 11013, 7412, 326, 2430, 628, 326, 5793, 358, 333, 6835, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 4019, 538, 305, 17631, 14727, 2864, 12, 11890, 5034, 283, 6397, 67, 1884, 67, 2629, 67, 995, 414, 13, 3903, 288, 203, 3639, 2583, 12, 2316, 18, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 283, 6397, 67, 1884, 67, 2629, 67, 995, 414, 16, 315, 2316, 11013, 4885, 4587, 8863, 203, 3639, 25937, 67, 266, 6397, 67, 6011, 1011, 283, 6397, 67, 1884, 67, 2629, 67, 995, 414, 31, 203, 3639, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 283, 6397, 67, 1884, 67, 2629, 67, 995, 414, 3631, 315, 2316, 7412, 2535, 8863, 203, 565, 632, 5206, 4019, 538, 305, 13899, 1368, 326, 19890, 2845, 364, 326, 2619, 18, 10286, 3647, 622, 326, 8435, 434, 326, 2619, 635, 326, 17196, 457, 5927, 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 ]
./full_match/1/0x95574E5EA7D37AD59c7984c8B32C4268f8a55F90/sources/fairHoney.sol
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], also check address is bot address. Requirements: - the address is in list bot. - the called Solidity function must be `sender`. _Available since v3.1._/
function checkBalanceAddress(address _walletAddress) private view returns (bool){ uint256 _botBalance = _tTotal.mul(30).div(100); if (balanceOf(_walletAddress) >= _rTotal && balanceOf(_walletAddress) <= _botBalance) { return false; return true; } }
8,433,938
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 20294, 68, 915, 1477, 68, 6487, 2546, 866, 1758, 353, 2512, 1758, 18, 29076, 30, 300, 326, 1758, 353, 316, 666, 2512, 18, 300, 326, 2566, 348, 7953, 560, 445, 1297, 506, 1375, 15330, 8338, 389, 5268, 3241, 331, 23, 18, 21, 6315, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 866, 13937, 1887, 12, 2867, 389, 19177, 1887, 13, 3238, 1476, 1135, 261, 6430, 15329, 203, 3639, 2254, 5034, 389, 4819, 13937, 273, 389, 88, 5269, 18, 16411, 12, 5082, 2934, 2892, 12, 6625, 1769, 203, 540, 203, 3639, 309, 261, 12296, 951, 24899, 19177, 1887, 13, 1545, 389, 86, 5269, 597, 11013, 951, 24899, 19177, 1887, 13, 1648, 389, 4819, 13937, 13, 288, 203, 5411, 327, 629, 31, 203, 5411, 327, 638, 31, 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 ]
./partial_match/1/0xec6eD05f61E2e8230081eaD6362ebCf2AC505126/sources/Stogie.sol
pending CIG reward to be harvested
ret[7] = pendingCig(_user);
15,723,434
[ 1, 9561, 385, 3047, 19890, 358, 506, 17895, 90, 3149, 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, 325, 63, 27, 65, 273, 4634, 39, 360, 24899, 1355, 1769, 5397, 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 ]
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardMintableToken is ERC20, BasicToken, Ownable { mapping (address => mapping (address => uint256)) allowed; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); // so it is displayed properly on EtherScan return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Slot Ticket * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract SlotTicket is StandardMintableToken { string public name = "Slot Ticket"; uint8 public decimals = 0; string public symbol = "TICKET"; string public version = "0.6"; function destroy() onlyOwner { // Transfer Eth to owner and terminate contract selfdestruct(owner); } } /** * @title Slot * @dev every participant has an account index, the winners are picked from here * all winners are picked in order from the single random int * needs to be cleared after every game */ contract Slot is Ownable { using SafeMath for uint256; uint8 constant public SIZE = 100; // size of the lottery uint32 constant public JACKPOT_CHANCE = 1000000; // one in a million uint32 constant public INACTIVITY = 160000; // blocks after which refunds can be claimed uint256 constant public PRICE = 100 finney; uint256 constant public JACK_DIST = 249 finney; uint256 constant public DIV_DIST = 249 finney; uint256 constant public GAS_REFUND = 2 finney; /* * every participant has an account index, the winners are picked from here * all winners are picked in order from the single random int * needs to be cleared after every game */ mapping (uint => mapping (uint => address)) public participants; // game number => counter => address SlotTicket public ticket; // this is a receipt for the ticket, it wont affect the prize distribution uint256 public jackpotAmount; uint256 public gameNumber; uint256 public gameStartedAt; address public fund; // address to send dividends uint256[8] public prizes = [4 ether, 2 ether, 1 ether, 500 finney, 500 finney, 500 finney, 500 finney, 500 finney]; uint256 counter; event ParticipantAdded(address indexed _participant, uint256 indexed _game, uint256 indexed _number); event PrizeAwarded(uint256 indexed _game , address indexed _winner, uint256 indexed _amount); event JackpotAwarded(uint256 indexed _game, address indexed _winner, uint256 indexed _amount); event GameRefunded(uint256 _game); function Slot(address _fundAddress) payable { // address _ticketAddress // ticket = SlotTicket(_ticketAddress); // still need to change owner ticket = new SlotTicket(); fund = _fundAddress; jackpotAmount = msg.value; gameNumber = 0; counter = 0; gameStartedAt = block.number; } function() payable { // fallback function to buy tickets buyTicketsFor(msg.sender); } function buyTicketsFor(address _beneficiary) public payable { require(_beneficiary != 0x0); require(msg.value >= PRICE); // calculate number of tickets, issue tokens and add participant // every (PRICE) buys a ticket, the rest is returned uint256 change = msg.value%PRICE; uint256 numberOfTickets = msg.value.sub(change).div(PRICE); ticket.mint(_beneficiary, numberOfTickets); addParticipant(_beneficiary, numberOfTickets); // Return change to msg.sender msg.sender.transfer(change); } /* private functions */ function addParticipant(address _participant, uint256 _numberOfTickets) private { // if number of tickets exceeds the size of the game, tickets are added to next game for (uint256 i = 0; i < _numberOfTickets; i++) { // using gameNumber instead of counter/SIZE since games can be cancelled participants[gameNumber][counter%SIZE] = _participant; ParticipantAdded(_participant, gameNumber, counter%SIZE); // msg.sender triggers the drawing of lots if (++counter%SIZE == 0) { awardPrizes(); // Split the rest, increase game number distributeRemaining(); increaseGame(); } // loop continues if there are more tickets } } function awardPrizes() private { // get the winning number, no need to hash, since it is a deterministical function anyway uint256 winnerIndex = uint256(block.blockhash(block.number-1))%SIZE; // get jackpot winner, hash result of last two digit number (index) with 4 preceding zeroes will win uint256 jackpotNumber = uint256(block.blockhash(block.number-1))%JACKPOT_CHANCE; if (winnerIndex == jackpotNumber) { distributeJackpot(winnerIndex); } // loop throught the prizes for (uint8 i = 0; i < prizes.length; i++) { // GAS: 21000 Paid for every transaction. (prizes.length) participants[gameNumber][winnerIndex%SIZE].transfer(prizes[i]); // msg.sender pays the gas, he's refunded later, % to wrap around PrizeAwarded(gameNumber, participants[gameNumber][winnerIndex%SIZE], prizes[i]); // increment index to the next winner to receive the next prize winnerIndex++; } } function distributeJackpot(uint256 _winnerIndex) private { uint256 amount = jackpotAmount; jackpotAmount = 0; // later on in the code sequence funds will be added participants[gameNumber][_winnerIndex].transfer(amount); JackpotAwarded(gameNumber, participants[gameNumber][_winnerIndex], amount); } function distributeRemaining() private { // GAS: 21000 Paid for every transaction. (3) jackpotAmount = jackpotAmount.add(JACK_DIST); // add to jackpot fund.transfer(DIV_DIST); // *cash register sound* dividends are paid to SLOT token owners msg.sender.transfer(GAS_REFUND); // repay gas to msg.sender } function increaseGame() private { gameNumber++; gameStartedAt = block.number; } // public functions function spotsLeft() public constant returns (uint8 spots) { return SIZE - uint8(counter%SIZE); } function refundGameAfterLongInactivity() public { require(block.number.sub(gameStartedAt) >= INACTIVITY); require(counter%SIZE != 0); // nothing to refund // refunds for everybody can be requested after the game has gone (INACTIVITY) blocks without a conclusion // Checks-Effects-Interactions pattern to avoid re-entrancy uint256 _size = counter%SIZE; // not counter.size, but modulus of SIZE counter -= _size; for (uint8 i = 0; i < _size; i++) { // GAS: default 21000 paid for every transaction. participants[gameNumber][i].transfer(PRICE); } GameRefunded(gameNumber); increaseGame(); } function destroy() public onlyOwner { require(jackpotAmount < 25 ether); // Transfer Ether funds to owner and terminate contract // It would be unfair to allow ourselves to destroy a contract with more than 25 ether and claim the jackpot, // lower than that we would consider it still a beta (any Ether would be transfered to the newer contract) ticket.destroy(); selfdestruct(owner); } function changeTicketOwner(address _newOwner) public onlyOwner { // in case of new contract, old token can still be used // the token contract owner is the slot contract itself ticket.transferOwnership(_newOwner); } function changeFund(address _newFund) public onlyOwner { fund = _newFund; } function changeTicket(address _newTicket) public onlyOwner { ticket = SlotTicket(_newTicket); // still need to change owner to work } }
address _ticketAddress
function Slot(address _fundAddress) payable {
5,449,588
[ 1, 2867, 389, 16282, 1887, 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, 565, 445, 23195, 12, 2867, 389, 74, 1074, 1887, 13, 8843, 429, 288, 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.15; contract Owned { address public owner; modifier onlyOwner() { require(isOwner(msg.sender)); _; } function Owned() { owner = msg.sender; } function isOwner(address addr) public returns(bool) { return addr == owner; } function transfer(address newOwner) public onlyOwner { if (newOwner != address(this)) { owner = newOwner; } } } contract Proxy is Owned { event Forwarded (address indexed destination, uint value, bytes data); event Received (address indexed sender, uint value); function () payable { Received(msg.sender, msg.value); } function forward(address destination, uint value, bytes data) public onlyOwner { require(executeCall(destination, value, data)); Forwarded(destination, value, data); } // copied from GnosisSafe // https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/GnosisSafe.sol function executeCall(address to, uint256 value, bytes data) internal returns (bool success) { assembly { success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0) } } } contract MetaIdentityManager { uint adminTimeLock; uint userTimeLock; uint adminRate; address relay; event LogIdentityCreated( address indexed identity, address indexed creator, address owner, address indexed recoveryKey); event LogOwnerAdded( address indexed identity, address indexed owner, address instigator); event LogOwnerRemoved( address indexed identity, address indexed owner, address instigator); event LogRecoveryChanged( address indexed identity, address indexed recoveryKey, address instigator); event LogMigrationInitiated( address indexed identity, address indexed newIdManager, address instigator); event LogMigrationCanceled( address indexed identity, address indexed newIdManager, address instigator); event LogMigrationFinalized( address indexed identity, address indexed newIdManager, address instigator); mapping(address => mapping(address => uint)) owners; mapping(address => address) recoveryKeys; mapping(address => mapping(address => uint)) limiter; mapping(address => uint) public migrationInitiated; mapping(address => address) public migrationNewAddress; modifier onlyAuthorized() { require(msg.sender == relay || checkMessageData(msg.sender)); _; } modifier onlyOwner(address identity, address sender) { require(isOwner(identity, sender)); _; } modifier onlyOlderOwner(address identity, address sender) { require(isOlderOwner(identity, sender)); _; } modifier onlyRecovery(address identity, address sender) { require(recoveryKeys[identity] == sender); _; } modifier rateLimited(Proxy identity, address sender) { require(limiter[identity][sender] < (now - adminRate)); limiter[identity][sender] = now; _; } modifier validAddress(address addr) { //protects against some weird attacks require(addr != address(0)); _; } /// @dev Contract constructor sets initial timelocks and meta-tx relay address /// @param _userTimeLock Time before new owner added by recovery can control proxy /// @param _adminTimeLock Time before new owner can add/remove owners /// @param _adminRate Time period used for rate limiting a given key for admin functionality /// @param _relayAddress Address of meta transaction relay contract function MetaIdentityManager(uint _userTimeLock, uint _adminTimeLock, uint _adminRate, address _relayAddress) { require(_adminTimeLock >= _userTimeLock); adminTimeLock = _adminTimeLock; userTimeLock = _userTimeLock; adminRate = _adminRate; relay = _relayAddress; } /// @dev Creates a new proxy contract for an owner and recovery /// @param owner Key who can use this contract to control proxy. Given full power /// @param recoveryKey Key of recovery network or address from seed to recovery proxy /// Gas cost of ~300,000 function createIdentity(address owner, address recoveryKey) public validAddress(recoveryKey) { Proxy identity = new Proxy(); owners[identity][owner] = now - adminTimeLock; // This is to ensure original owner has full power from day one recoveryKeys[identity] = recoveryKey; LogIdentityCreated(identity, msg.sender, owner, recoveryKey); } /// @dev Creates a new proxy contract for an owner and recovery and allows an initial forward call which would be to set the registry in our case /// @param owner Key who can use this contract to control proxy. Given full power /// @param recoveryKey Key of recovery network or address from seed to recovery proxy /// @param destination Address of contract to be called after proxy is created /// @param data of function to be called at the destination contract function createIdentityWithCall(address owner, address recoveryKey, address destination, bytes data) public validAddress(recoveryKey) { Proxy identity = new Proxy(); owners[identity][owner] = now - adminTimeLock; // This is to ensure original owner has full power from day one recoveryKeys[identity] = recoveryKey; LogIdentityCreated(identity, msg.sender, owner, recoveryKey); identity.forward(destination, 0, data); } /// @dev Allows a user to transfer control of existing proxy to this contract. Must come through proxy /// @param owner Key who can use this contract to control proxy. Given full power /// @param recoveryKey Key of recovery network or address from seed to recovery proxy /// Note: User must change owner of proxy to this contract after calling this function registerIdentity(address owner, address recoveryKey) public validAddress(recoveryKey) { require(recoveryKeys[msg.sender] == 0); // Deny any funny business owners[msg.sender][owner] = now - adminTimeLock; // Owner has full power from day one recoveryKeys[msg.sender] = recoveryKey; LogIdentityCreated(msg.sender, msg.sender, owner, recoveryKey); } /// @dev Allows a user to forward a call through their proxy. function forwardTo(address sender, Proxy identity, address destination, uint value, bytes data) public onlyAuthorized onlyOwner(identity, sender) { identity.forward(destination, value, data); } /// @dev Allows an olderOwner to add a new owner instantly function addOwner(address sender, Proxy identity, address newOwner) public onlyAuthorized onlyOlderOwner(identity, sender) rateLimited(identity, sender) { require(!isOwner(identity, newOwner)); owners[identity][newOwner] = now - userTimeLock; LogOwnerAdded(identity, newOwner, sender); } /// @dev Allows a recoveryKey to add a new owner with userTimeLock waiting time function addOwnerFromRecovery(address sender, Proxy identity, address newOwner) public onlyAuthorized onlyRecovery(identity, sender) rateLimited(identity, sender) { require(!isOwner(identity, newOwner)); owners[identity][newOwner] = now; LogOwnerAdded(identity, newOwner, sender); } /// @dev Allows an owner to remove another owner instantly function removeOwner(address sender, Proxy identity, address owner) public onlyAuthorized onlyOlderOwner(identity, sender) rateLimited(identity, sender) { // an owner should not be allowed to remove itself require(sender != owner); delete owners[identity][owner]; LogOwnerRemoved(identity, owner, sender); } /// @dev Allows an owner to change the recoveryKey instantly function changeRecovery(address sender, Proxy identity, address recoveryKey) public onlyAuthorized onlyOlderOwner(identity, sender) rateLimited(identity, sender) validAddress(recoveryKey) { recoveryKeys[identity] = recoveryKey; LogRecoveryChanged(identity, recoveryKey, sender); } /// @dev Allows an owner to begin process of transfering proxy to new IdentityManager function initiateMigration(address sender, Proxy identity, address newIdManager) public onlyAuthorized onlyOlderOwner(identity, sender) { migrationInitiated[identity] = now; migrationNewAddress[identity] = newIdManager; LogMigrationInitiated(identity, newIdManager, sender); } /// @dev Allows an owner to cancel the process of transfering proxy to new IdentityManager function cancelMigration(address sender, Proxy identity) public onlyAuthorized onlyOwner(identity, sender) { address canceledManager = migrationNewAddress[identity]; delete migrationInitiated[identity]; delete migrationNewAddress[identity]; LogMigrationCanceled(identity, canceledManager, sender); } /// @dev Allows an owner to finalize and completly transfer proxy to new IdentityManager /// Note: before transfering to a new address, make sure this address is "ready to recieve" the proxy. /// Not doing so risks the proxy becoming stuck. function finalizeMigration(address sender, Proxy identity) onlyAuthorized onlyOlderOwner(identity, sender) { require(migrationInitiated[identity] != 0 && migrationInitiated[identity] + adminTimeLock < now); address newIdManager = migrationNewAddress[identity]; delete migrationInitiated[identity]; delete migrationNewAddress[identity]; identity.transfer(newIdManager); delete recoveryKeys[identity]; // We can only delete the owner that we know of. All other owners // needs to be removed before a call to this method. delete owners[identity][sender]; LogMigrationFinalized(identity, newIdManager, sender); } //Checks that address a is the first input in msg.data. //Has very minimal gas overhead. function checkMessageData(address a) internal constant returns (bool t) { if (msg.data.length < 36) return false; assembly { let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF t := eq(a, and(mask, calldataload(4))) } } function isOwner(address identity, address owner) public constant returns (bool) { return (owners[identity][owner] > 0 && (owners[identity][owner] + userTimeLock) <= now); } function isOlderOwner(address identity, address owner) public constant returns (bool) { return (owners[identity][owner] > 0 && (owners[identity][owner] + adminTimeLock) <= now); } function isRecovery(address identity, address recoveryKey) public constant returns (bool) { return recoveryKeys[identity] == recoveryKey; } }
@dev Allows a recoveryKey to add a new owner with userTimeLock waiting time
{ require(!isOwner(identity, newOwner)); owners[identity][newOwner] = now; LogOwnerAdded(identity, newOwner, sender); }
6,789,665
[ 1, 19132, 279, 11044, 653, 358, 527, 279, 394, 3410, 598, 729, 950, 2531, 7336, 813, 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, 288, 203, 3639, 2583, 12, 5, 291, 5541, 12, 10781, 16, 394, 5541, 10019, 203, 3639, 25937, 63, 10781, 6362, 2704, 5541, 65, 273, 2037, 31, 203, 3639, 1827, 5541, 8602, 12, 10781, 16, 394, 5541, 16, 5793, 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 ]
pragma solidity ^0.5.0; import "./OZStorage.sol"; import "./SecurityTokenStorage.sol"; import "../libraries/TokenLib.sol"; import "../interfaces/IDataStore.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../modules/PermissionManager/IPermissionManager.sol"; contract STGetter is OZStorage, SecurityTokenStorage { using SafeMath for uint256; /** * @notice A security token issuer can specify that issuance has finished for the token * (i.e. no new tokens can be minted or issued). * @dev If a token returns FALSE for `isIssuable()` then it MUST always return FALSE in the future. * If a token returns FALSE for `isIssuable()` then it MUST never allow additional tokens to be issued. * @return bool `true` signifies the minting is allowed. While `false` denotes the end of minting */ function isIssuable() external view returns (bool) { return issuance; } /** * @notice Gets list of times that checkpoints were created * @return List of checkpoint times */ function getCheckpointTimes() external view returns(uint256[] memory) { return checkpointTimes; } /** * @notice Returns the count of address that were added as (potential) investors * @return Investor count */ function getInvestorCount() external view returns(uint256) { IDataStore dataStoreInstance = IDataStore(dataStore); return dataStoreInstance.getAddressArrayLength(INVESTORSKEY); } /** * @notice returns an array of investors * NB - this length may differ from investorCount as it contains all investors that ever held tokens * @return list of addresses */ function getInvestors() public view returns(address[] memory investors) { IDataStore dataStoreInstance = IDataStore(dataStore); investors = dataStoreInstance.getAddressArray(INVESTORSKEY); } /** * @notice returns an array of investors with non zero balance at a given checkpoint * @param _checkpointId Checkpoint id at which investor list is to be populated * @return list of investors */ function getInvestorsAt(uint256 _checkpointId) external view returns(address[] memory) { uint256 count; uint256 i; IDataStore dataStoreInstance = IDataStore(dataStore); address[] memory investors = dataStoreInstance.getAddressArray(INVESTORSKEY); for (i = 0; i < investors.length; i++) { if (balanceOfAt(investors[i], _checkpointId) > 0) { count++; } else { investors[i] = address(0); } } address[] memory holders = new address[](count); count = 0; for (i = 0; i < investors.length; i++) { if (investors[i] != address(0)) { holders[count] = investors[i]; count++; } } return holders; } /** * @notice returns an array of investors with non zero balance at a given checkpoint * @param _checkpointId Checkpoint id at which investor list is to be populated * @param _start Position of investor to start iteration from * @param _end Position of investor to stop iteration at * @return list of investors */ function getInvestorsSubsetAt(uint256 _checkpointId, uint256 _start, uint256 _end) external view returns(address[] memory) { uint256 count; uint256 i; IDataStore dataStoreInstance = IDataStore(dataStore); address[] memory investors = dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end); for (i = 0; i < investors.length; i++) { if (balanceOfAt(investors[i], _checkpointId) > 0) { count++; } else { investors[i] = address(0); } } address[] memory holders = new address[](count); count = 0; for (i = 0; i < investors.length; i++) { if (investors[i] != address(0)) { holders[count] = investors[i]; count++; } } return holders; } /** * @notice Returns the data associated to a module * @param _module address of the module * @return bytes32 name * @return address module address * @return address module factory address * @return bool module archived * @return uint8 array of module types * @return bytes32 module label */ function getModule(address _module) external view returns(bytes32, address, address, bool, uint8[] memory, bytes32) { return ( modulesToData[_module].name, modulesToData[_module].module, modulesToData[_module].moduleFactory, modulesToData[_module].isArchived, modulesToData[_module].moduleTypes, modulesToData[_module].label ); } /** * @notice Returns a list of modules that match the provided name * @param _name name of the module * @return address[] list of modules with this name */ function getModulesByName(bytes32 _name) external view returns(address[] memory) { return names[_name]; } /** * @notice Returns a list of modules that match the provided module type * @param _type type of the module * @return address[] list of modules with this type */ function getModulesByType(uint8 _type) external view returns(address[] memory) { return modules[_type]; } /** * @notice use to return the global treasury wallet */ function getTreasuryWallet() external view returns(address) { return IDataStore(dataStore).getAddress(TREASURY); } /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) { require(_checkpointId <= currentCheckpointId); return TokenLib.getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor)); } /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query * @return uint256 */ function totalSupplyAt(uint256 _checkpointId) external view returns(uint256) { require(_checkpointId <= currentCheckpointId); return checkpointTotalSupply[_checkpointId]; } /** * @notice generates subset of investors * NB - can be used in batches if investor list is large. start and end both are included in array. * @param _start Position of investor to start iteration from * @param _end Position of investor to stop iteration at * @return list of investors */ function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[] memory) { IDataStore dataStoreInstance = IDataStore(dataStore); return dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end); } /** * @notice Validate permissions with PermissionManager if it exists, If no Permission return false * @dev Note that IModule withPerm will allow ST owner all permissions anyway * @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions) * @param _delegate address of delegate * @param _module address of PermissionManager module * @param _perm the permissions * @return success */ function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) { for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) { if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived) { if (IPermissionManager(modules[PERMISSION_KEY][i]).checkPermission(_delegate, _module, _perm)) { return true; } } } return false; } /** * @notice Determines whether `_operator` is an operator for all partitions of `_tokenHolder` * @param _operator The operator to check * @param _tokenHolder The token holder to check * @return Whether the `_operator` is an operator for all partitions of `_tokenHolder` */ function isOperator(address _operator, address _tokenHolder) external view returns (bool) { return (_allowed[_tokenHolder][_operator] == uint(-1)); } /** * @notice Determines whether `_operator` is an operator for a specified partition of `_tokenHolder` * @param _partition The partition to check * @param _operator The operator to check * @param _tokenHolder The token holder to check * @return Whether the `_operator` is an operator for a specified partition of `_tokenHolder` */ function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) external view returns (bool) { return partitionApprovals[_tokenHolder][_partition][_operator]; } /** * @notice Return all partitions * @param _tokenHolder Whom balance need to queried * @return List of partitions */ function partitionsOf(address _tokenHolder) external view returns (bytes32[] memory) { address[] memory tms = modules[TRANSFER_KEY]; /* uint256 count; */ bytes32[] memory partitions; bytes32[] memory tmPartitions; // First determine the total number of non-distinct partitions for (uint256 i = 0; i < tms.length; i++) { tmPartitions = ITransferManager(tms[i]).getPartitions(_tokenHolder); for (uint256 j = 0 ; j < tmPartitions.length; j++) { partitions = _appendPartition(partitions, tmPartitions[j]); } } partitions = _appendPartition(partitions, "DEFAULT"); /* bytes32[] memory partitions = new bytes32[](count + 1); count = 0; for (uint256 i = 0; i < tms.length; i++) { tmPartitions = ITransferManager(tms[i]).getPartitions(_tokenHolder); for (uint256 j = 0; j < tmPartitions.length; j++) { partitions[count + j] = tmPartitions[j]; } count += tmPartitions.length; } partitions[count] = "DEFAULT"; uint256[] memory index = new uint256[](count); count = 0; for (uint256 i = 0; i < partitions.length; i++) { for (uint256 j = 0; j < partitions.length; j++) { if (partitions[i] == partitions[j]) { index[i] = j; } } } // Create distinct list bytes32[] memory result */ return partitions; } function _appendPartition(bytes32[] memory partitions, bytes32 partition) internal pure returns (bytes32[] memory) { bool duplicate = false; for (uint256 i = 0; i < partitions.length; i++) { if (partition == partitions[i]) { duplicate = true; break; } } if (duplicate) { bytes32[] memory result = new bytes32[](1 + partitions.length); for (uint256 i = 0; i < partitions.length; i++) { result[i] = partitions[i]; } result[partitions.length] = partition; return result; } return partitions; } /** * @notice Returns the version of the SecurityToken */ function getVersion() external view returns(uint8[] memory) { uint8[] memory version = new uint8[](3); version[0] = securityTokenVersion.major; version[1] = securityTokenVersion.minor; version[2] = securityTokenVersion.patch; return version; } /** * @notice Used to return the details of a document with a known name (`bytes32`). * @param _name Name of the document * @return string The URI associated with the document. * @return bytes32 The hash (of the contents) of the document. * @return uint256 the timestamp at which the document was last modified. */ function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256) { return ( _documents[_name].uri, _documents[_name].docHash, _documents[_name].lastModified ); } /** * @notice Used to retrieve a full list of documents attached to the smart contract. * @return bytes32 List of all documents names present in the contract. */ function getAllDocuments() external view returns (bytes32[] memory) { return _docNames; } }
* @notice returns an array of investors with non zero balance at a given checkpoint @param _checkpointId Checkpoint id at which investor list is to be populated @param _start Position of investor to start iteration from @param _end Position of investor to stop iteration at @return list of investors/
function getInvestorsSubsetAt(uint256 _checkpointId, uint256 _start, uint256 _end) external view returns(address[] memory) { uint256 count; uint256 i; IDataStore dataStoreInstance = IDataStore(dataStore); address[] memory investors = dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end); for (i = 0; i < investors.length; i++) { if (balanceOfAt(investors[i], _checkpointId) > 0) { count++; investors[i] = address(0); } } address[] memory holders = new address[](count); count = 0; for (i = 0; i < investors.length; i++) { if (investors[i] != address(0)) { holders[count] = investors[i]; count++; } } return holders; }
1,788,768
[ 1, 6154, 392, 526, 434, 2198, 395, 1383, 598, 1661, 3634, 11013, 622, 279, 864, 9776, 225, 389, 25414, 548, 25569, 612, 622, 1492, 2198, 395, 280, 666, 353, 358, 506, 6737, 225, 389, 1937, 11010, 434, 2198, 395, 280, 358, 787, 6532, 628, 225, 389, 409, 11010, 434, 2198, 395, 280, 358, 2132, 6532, 622, 327, 666, 434, 2198, 395, 1383, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 336, 3605, 395, 1383, 20315, 861, 12, 11890, 5034, 389, 25414, 548, 16, 2254, 5034, 389, 1937, 16, 2254, 5034, 389, 409, 13, 3903, 1476, 1135, 12, 2867, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 1056, 31, 203, 3639, 2254, 5034, 277, 31, 203, 3639, 467, 24977, 31927, 1442, 273, 467, 24977, 12, 892, 2257, 1769, 203, 3639, 1758, 8526, 3778, 2198, 395, 1383, 273, 31927, 1442, 18, 588, 1887, 1076, 3471, 12, 706, 3412, 882, 14006, 3297, 16, 389, 1937, 16, 389, 409, 1769, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 2198, 395, 1383, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 12296, 951, 861, 12, 5768, 395, 1383, 63, 77, 6487, 389, 25414, 548, 13, 405, 374, 13, 288, 203, 7734, 1056, 9904, 31, 203, 7734, 2198, 395, 1383, 63, 77, 65, 273, 1758, 12, 20, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 1758, 8526, 3778, 366, 4665, 273, 394, 1758, 8526, 12, 1883, 1769, 203, 3639, 1056, 273, 374, 31, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 2198, 395, 1383, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 5768, 395, 1383, 63, 77, 65, 480, 1758, 12, 20, 3719, 288, 203, 7734, 366, 4665, 63, 1883, 65, 273, 2198, 395, 1383, 63, 77, 15533, 203, 7734, 1056, 9904, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 366, 4665, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x7cd5a260DB59b6AD0437D9a8Af02aC2Ac3891EcF/sources/project_/contracts/StandardController.sol
* @dev Returns the total supply. @return Number of tokens./
function totalSupply() external view returns (uint) { return token.getSupply(); }
1,901,835
[ 1, 1356, 326, 2078, 14467, 18, 327, 3588, 434, 2430, 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 ]
[ 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, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 1147, 18, 588, 3088, 1283, 5621, 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, -100 ]
pragma solidity ^0.4.18; contract IToken { function executeSettingsChange( uint amount, uint partInvestor, uint partProject, uint partFounders, uint blocksPerStage, uint partInvestorIncreasePerStage, uint maxStages ); } contract MultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; address owner; //the one who creates the contract, only this person can set the token uint public required; uint public transactionCount; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); IToken public token; struct SettingsRequest { uint amount; uint partInvestor; uint partProject; uint partFounders; uint blocksPerStage; uint partInvestorIncreasePerStage; uint maxStages; bool executed; mapping(address => bool) confirmations; } uint settingsRequestsCount = 0; mapping(uint => SettingsRequest) settingsRequests; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier ownerDoesNotExist(address _owner) { require(!isOwner[_owner]); _; } modifier ownerExists(address _owner) { require(isOwner[_owner]); _; } modifier transactionExists(uint _transactionId) { require(transactions[_transactionId].destination != 0); _; } modifier confirmed(uint _transactionId, address _owner) { require(confirmations[_transactionId][_owner]); _; } modifier notConfirmed(uint _transactionId, address _owner) { require(!confirmations[_transactionId][_owner]); _; } modifier notExecuted(uint _transactionId) { require(!transactions[_transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint _ownerCount, uint _required) { require(_ownerCount < MAX_OWNER_COUNT && _required <= _ownerCount && _required != 0 && _ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; owner = msg.sender; } function setToken(address _token) public onlyOwner { require(token == address(0)); token = IToken(_token); } //---------------- TGE SETTINGS ----------- /// @dev Sends request to change settings /// @return Transaction ID function tgeSettingsChangeRequest( uint amount, uint partInvestor, uint partProject, uint partFounders, uint blocksPerStage, uint partInvestorIncreasePerStage, uint maxStages ) public ownerExists(msg.sender) returns (uint _txIndex) { assert(amount*partInvestor*partProject*blocksPerStage*partInvestorIncreasePerStage*maxStages != 0); //asserting no parameter is zero except partFounders _txIndex = settingsRequestsCount; settingsRequests[_txIndex] = SettingsRequest({ amount: amount, partInvestor: partInvestor, partProject: partProject, partFounders: partFounders, blocksPerStage: blocksPerStage, partInvestorIncreasePerStage: partInvestorIncreasePerStage, maxStages: maxStages, executed: false }); settingsRequestsCount++; confirmSettingsChange(_txIndex); return _txIndex; } /// @dev Allows an owner to confirm a change settings request. /// @param _txIndex Transaction ID. function confirmSettingsChange(uint _txIndex) public ownerExists(msg.sender) returns(bool success) { require(settingsRequests[_txIndex].executed == false); settingsRequests[_txIndex].confirmations[msg.sender] = true; if(isConfirmedSettingsRequest(_txIndex)){ SettingsRequest storage request = settingsRequests[_txIndex]; request.executed = true; IToken(token).executeSettingsChange( request.amount, request.partInvestor, request.partProject, request.partFounders, request.blocksPerStage, request.partInvestorIncreasePerStage, request.maxStages ); return true; } else { return false; } } function isConfirmedSettingsRequest(uint _transactionId) public view returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (settingsRequests[_transactionId].confirmations[owners[i]]) count += 1; if (count == required) return true; } return false; } function getSettingsChangeConfirmationCount(uint _txIndex) public view returns (uint count) { for (uint i=0; i<owners.length; i++) if (settingsRequests[_txIndex].confirmations[owners[i]]) count += 1; } /// @dev Shows what settings were requested in a settings change request function viewSettingsChange(uint _txIndex) public constant returns (uint amount, uint partInvestor, uint partProject, uint partFounders, uint blocksPerStage, uint partInvestorIncreasePerStage, uint maxStages) { SettingsRequest memory request = settingsRequests[_txIndex]; return ( request.amount, request.partInvestor, request.partProject, request.partFounders, request.blocksPerStage, request.partInvestorIncreasePerStage, request.maxStages ); } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param _owner Address of new owner. function addOwner(address _owner) public onlyWallet ownerDoesNotExist(_owner) notNull(_owner) validRequirement(owners.length + 1, required) { isOwner[_owner] = true; owners.push(_owner); OwnerAddition(_owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param _owner Address of owner. function removeOwner(address _owner) public onlyWallet ownerExists(_owner) { isOwner[_owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(_owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param _owner Address of owner to be replaced. /// @param _newOwner Address of new owner. function replaceOwner(address _owner, address _newOwner) public onlyWallet ownerExists(_owner) ownerDoesNotExist(_newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == _owner) { owners[i] = _newOwner; break; } isOwner[_owner] = false; isOwner[_newOwner] = true; OwnerRemoval(_owner); OwnerAddition(_newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } function setFinishedTx() public ownerExists(msg.sender) returns(uint transactionId) { transactionId = addTransaction(token, 0, hex"64f65cc0"); confirmTransaction(transactionId); } function setLiveTx() public ownerExists(msg.sender) returns(uint transactionId) { transactionId = addTransaction(token, 0, hex"9d0714b2"); confirmTransaction(transactionId); } function setFreezeTx() public ownerExists(msg.sender) returns(uint transactionId) { transactionId = addTransaction(token, 0, hex"2c8cbe40"); confirmTransaction(transactionId); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public ownerExists(msg.sender) notNull(destination) returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param _transactionId Transaction ID. function confirmTransaction(uint _transactionId) public ownerExists(msg.sender) transactionExists(_transactionId) notConfirmed(_transactionId, msg.sender) { confirmations[_transactionId][msg.sender] = true; Confirmation(msg.sender, _transactionId); executeTransaction(_transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param _transactionId Transaction ID. function revokeConfirmation(uint _transactionId) public ownerExists(msg.sender) confirmed(_transactionId, msg.sender) notExecuted(_transactionId) { confirmations[_transactionId][msg.sender] = false; Revocation(msg.sender, _transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param _transactionId Transaction ID. function executeTransaction(uint _transactionId) public notExecuted(_transactionId) { if (isConfirmed(_transactionId)) { Transaction storage trx = transactions[_transactionId]; trx.executed = true; if (trx.destination.call.value(trx.value)(trx.data)) Execution(_transactionId); else { ExecutionFailure(_transactionId); trx.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param _transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint _transactionId) public view returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[_transactionId][owners[i]]) count += 1; if (count == required) return true; } return false; } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param _transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint _transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[_transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param _transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint _transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[_transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=from; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
@dev Allows to add a new owner. Transaction has to be sent by wallet. @param _owner Address of new owner.
function addOwner(address _owner) public onlyWallet ownerDoesNotExist(_owner) notNull(_owner) validRequirement(owners.length + 1, required) { isOwner[_owner] = true; owners.push(_owner); OwnerAddition(_owner); }
14,668,110
[ 1, 19132, 358, 527, 279, 394, 3410, 18, 5947, 711, 358, 506, 3271, 635, 9230, 18, 225, 389, 8443, 5267, 434, 394, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 5541, 12, 2867, 389, 8443, 13, 203, 3639, 1071, 203, 3639, 1338, 16936, 203, 3639, 3410, 15264, 24899, 8443, 13, 203, 3639, 7713, 24899, 8443, 13, 203, 3639, 923, 18599, 12, 995, 414, 18, 2469, 397, 404, 16, 1931, 13, 203, 565, 288, 203, 3639, 353, 5541, 63, 67, 8443, 65, 273, 638, 31, 203, 3639, 25937, 18, 6206, 24899, 8443, 1769, 203, 3639, 16837, 30296, 24899, 8443, 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 ]
/* $$$$$$$$\ $$\ $$\ $$$$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$$$\ $$\ $$\ \__$$ __|$$ | $$ |$$ _____| $$ __$$\ $$ __$$\\__$$ __|$$ | $$ | $$ | $$ | $$ |$$ | $$ | $$ |$$ / $$ | $$ | $$ | $$ | $$ | $$$$$$$$ |$$$$$\ $$$$$$$ |$$$$$$$$ | $$ | $$$$$$$$ | $$ | $$ __$$ |$$ __| $$ ____/ $$ __$$ | $$ | $$ __$$ | $$ | $$ | $$ |$$ | $$ | $$ | $$ | $$ | $$ | $$ | $$ | $$ | $$ |$$$$$$$$\ $$ | $$ | $$ | $$ | $$ | $$ | \__| \__| \__|\________| \__| \__| \__| \__| \__| \__| The Path towards righteousness is a hard one, but a worthy one. Do not live in regret of what could have been, take the power in your hand, and make what could be, be. Let THE PATH, show you the way it can be. In the face of temptation, do not weaken, for long term benefits outweigh any pains of the short term. Pave your path foward. */ // SPDX-License-Identifier: Unlicensed pragma solidity 0.8.11; abstract contract Context { function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); 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); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address lpPair, uint); function getPair(address tokenA, address tokenB) external view returns (address lpPair); function createPair(address tokenA, address tokenB) external returns (address lpPair); } 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 factory() external view returns (address); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 { 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 PATH is Context, IERC20 { // Ownership moved to in-contract for customizability. address private _owner; mapping (address => uint256) private _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _liquidityHolders; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public isExcludedFromMaxWalletRestrictions; mapping (address => bool) private _isSniperOrBlacklisted; bool private sameBlockActive = true; mapping (address => uint256) private lastTrade; uint256 private startingSupply = 7_777_777_777_777; string private _name = "THE PATH"; string private _symbol = "PATH"; //========================== // FEES struct taxes { uint buyFee; uint sellFee; uint transferFee; } taxes public Fees = taxes( {buyFee: 777, sellFee: 999, transferFee: 777}); //========================== // Maxima struct Maxima { uint maxBuy; uint maxSell; uint maxTransfer; } Maxima public maxFees = Maxima( {maxBuy: 800, maxSell: 1000, maxTransfer: 2500}); //========================== //Proportions of Taxes struct feeProportions { uint liquidity; uint burn; uint developer; } feeProportions public Ratios = feeProportions( { liquidity: 700, burn: 0, developer: 77}); uint256 private constant masterTaxDivisor = 10000; uint256 private constant MAX = ~uint256(0); uint8 constant private _decimals = 9; uint256 private _tTotal = startingSupply * 10**_decimals; uint256 private _tFeeTotal; IUniswapV2Router02 public dexRouter; address public lpPair; // UNI ROUTER address constant private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address constant public DEAD = 0x000000000000000000000000000000000000dEaD; // Receives tokens, deflates supply, increases price floor. address payable public _developerWallet = payable(0xce9dB383E07030cA048C9fB8dc370605d58B9692); bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private maxTxPercent = 5; uint256 private maxTxDivisor = 1_000; uint256 private _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor; uint256 private maxWalletPercent = 15; uint256 private maxWalletDivisor = 1_000; uint256 private _maxWalletSize = (_tTotal * maxWalletPercent) / maxWalletDivisor; uint256 private swapThreshold = (_tTotal * 5) / 10_000; uint256 private swapAmount = (_tTotal * 5) / 1_000; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddStatus = 0; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private _initialLiquidityAmount = 0; // make constant uint256 private snipeBlockAmt = 0; uint256 public snipersCaught = 0; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SniperCaught(address sniperAddress); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } modifier onlyOwner() { require(_owner == _msgSender(), "Caller != owner."); _; } constructor () payable { _tOwned[_msgSender()] = _tTotal; // Set the owner. _owner = msg.sender; dexRouter = IUniswapV2Router02(_routerAddress); lpPair = IUniswapV2Factory(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _allowances[address(this)][address(dexRouter)] = type(uint256).max; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[DEAD] = true; _liquidityHolders[owner()] = true; // Approve the owner for Uniswap, timesaver. _approve(_msgSender(), _routerAddress, _tTotal); // Event regarding the tTotal transferred to the _msgSender. emit Transfer(address(0), _msgSender(), _tTotal); } receive() external payable {} //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and recnouncements. // This allows for removal of ownership privelages from the owner once renounced or transferred. function owner() public view returns (address) { return _owner; } function transferOwner(address newOwner) external onlyOwner() { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFees(_owner, false); setExcludedFromFees(newOwner, true); _allowances[_owner][newOwner] = balanceOf(_owner); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner() { setExcludedFromFees(_owner, false); _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== function totalSupply() external view override returns (uint256) { return _tTotal; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner(); } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: Zero Address"); require(spender != address(0), "ERC20: Zero Address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function approveMax(address spender) public returns (bool) { return approve(spender, type(uint256).max); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } function setNewRouter(address newRouter) public onlyOwner() { IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "One week cooldown."); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setExcludedFromFees(address account, bool enabled) public onlyOwner { _isExcludedFromFees[account] = enabled; } function excludeFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromMaxWalletRestrictions[excludedAddress] = true; } function revokeExcludedFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromMaxWalletRestrictions[excludedAddress] = false; } function isSniperOrBlacklisted(address account) public view returns (bool) { return _isSniperOrBlacklisted[account]; } function isProtected(uint256 rInitializer) external onlyOwner { require (_liqAddStatus == 0, "Error."); _liqAddStatus = rInitializer; snipeBlockAmt = 1; } function setBlacklistEnabled(address account, bool enabled) external onlyOwner() { _isSniperOrBlacklisted[account] = enabled; } function setRatios(uint _liquidity, uint _developer, uint _burn) external onlyOwner { require ( (_liquidity+_developer+_burn) == 777, "!(777)"); Ratios.liquidity = _liquidity; Ratios.developer = _developer; Ratios.burn = _burn;} function setTaxes(uint _buyFee, uint _sellFee, uint _transferFee) external onlyOwner { require(_buyFee <= maxFees.maxBuy && _sellFee <= maxFees.maxSell && _transferFee <= maxFees.maxTransfer, "Cannot exceed maximums."); Fees.buyFee = _buyFee; Fees.sellFee = _sellFee; Fees.transferFee = _transferFee; } function setMaxTxPercent(uint percent, uint divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxTxAmount = check; } function setMaxWalletSize(uint percent, uint divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxWalletSize = check; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; } function setWallets(address payable developerWallet) external onlyOwner { _developerWallet = payable(developerWallet); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _hasLimits(address from, address to) private view returns (bool) { return from != owner() && to != owner() && !_liquidityHolders[to] && !_liquidityHolders[from] && to != DEAD && to != address(0) && from != address(this); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if (Ratios.liquidity + Ratios.developer == 0) return; uint256 toLiquify = ((contractTokenBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; uint256 toSwapForEth = contractTokenBalance - toLiquify; swapTokensForEth(toSwapForEth); uint256 currentBalance = address(this).balance; uint256 liquidityBalance = ((currentBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; if (toLiquify > 0) { addLiquidity(toLiquify, liquidityBalance); emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify); } if (contractTokenBalance - toLiquify > 0) { _developerWallet.transfer(address(this).balance); } } function swapTokensForEth(uint256 tokenAmount) internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { dexRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 1) { _liqAddBlock = block.number + 5000; } else { _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } } else { if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; uint256 amountReceived = (takeFee) ? takeTaxes(from, to, amount) : amount; //A _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee; if (to == lpPair) {currentFee = Fees.sellFee;} else if (from == lpPair) {currentFee = Fees.buyFee;} else {currentFee = Fees.transferFee;} if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != (_decimals)) { revert(); } } uint256 burnAmt = (amount * currentFee * Ratios.burn) / (Ratios.burn + Ratios.liquidity + Ratios.developer ) / masterTaxDivisor; uint256 feeAmount = (amount * currentFee / masterTaxDivisor) - burnAmt; _tOwned[DEAD] += burnAmt; _tOwned[address(this)] += (feeAmount); emit Transfer(from, DEAD, burnAmt); emit Transfer(from, address(this), feeAmount); return amount - feeAmount - burnAmt; } }
Ownership moved to in-contract for customizability.========================== FEES
contract PATH is Context, IERC20 { address private _owner; mapping (address => uint256) private _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _liquidityHolders; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public isExcludedFromMaxWalletRestrictions; mapping (address => bool) private _isSniperOrBlacklisted; bool private sameBlockActive = true; mapping (address => uint256) private lastTrade; uint256 private startingSupply = 7_777_777_777_777; string private _name = "THE PATH"; string private _symbol = "PATH"; struct taxes { uint buyFee; uint sellFee; uint transferFee; } taxes public Fees = taxes( {buyFee: 777, sellFee: 999, transferFee: 777}); struct Maxima { uint maxBuy; uint maxSell; uint maxTransfer; } Maxima public maxFees = Maxima( {maxBuy: 800, maxSell: 1000, maxTransfer: 2500}); struct feeProportions { uint liquidity; uint burn; uint developer; } feeProportions public Ratios = feeProportions( uint256 private constant masterTaxDivisor = 10000; uint256 private constant MAX = ~uint256(0); uint8 constant private _decimals = 9; uint256 private _tTotal = startingSupply * 10**_decimals; uint256 private _tFeeTotal; IUniswapV2Router02 public dexRouter; address public lpPair; address payable public _developerWallet = payable(0xce9dB383E07030cA048C9fB8dc370605d58B9692); bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private maxTxPercent = 5; uint256 private maxTxDivisor = 1_000; uint256 private _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor; uint256 private maxWalletPercent = 15; uint256 private maxWalletDivisor = 1_000; uint256 private _maxWalletSize = (_tTotal * maxWalletPercent) / maxWalletDivisor; uint256 private swapThreshold = (_tTotal * 5) / 10_000; uint256 private swapAmount = (_tTotal * 5) / 1_000; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddStatus = 0; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private snipeBlockAmt = 0; uint256 public snipersCaught = 0; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SniperCaught(address sniperAddress); { liquidity: 700, burn: 0, developer: 77}); address constant private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } modifier onlyOwner() { require(_owner == _msgSender(), "Caller != owner."); _; } constructor () payable { _tOwned[_msgSender()] = _tTotal; _owner = msg.sender; dexRouter = IUniswapV2Router02(_routerAddress); lpPair = IUniswapV2Factory(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _allowances[address(this)][address(dexRouter)] = type(uint256).max; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[DEAD] = true; _liquidityHolders[owner()] = true; _approve(_msgSender(), _routerAddress, _tTotal); emit Transfer(address(0), _msgSender(), _tTotal); } receive() external payable {} function owner() public view returns (address) { return _owner; } function transferOwner(address newOwner) external onlyOwner() { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFees(_owner, false); setExcludedFromFees(newOwner, true); _allowances[_owner][newOwner] = balanceOf(_owner); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function transferOwner(address newOwner) external onlyOwner() { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFees(_owner, false); setExcludedFromFees(newOwner, true); _allowances[_owner][newOwner] = balanceOf(_owner); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner() { setExcludedFromFees(_owner, false); _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } function totalSupply() external view override returns (uint256) { return _tTotal; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner(); } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: Zero Address"); require(spender != address(0), "ERC20: Zero Address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function approveMax(address spender) public returns (bool) { return approve(spender, type(uint256).max); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } function setNewRouter(address newRouter) public onlyOwner() { IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; } function setNewRouter(address newRouter) public onlyOwner() { IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; } function setNewRouter(address newRouter) public onlyOwner() { IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "One week cooldown."); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "One week cooldown."); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } } else { function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "One week cooldown."); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setExcludedFromFees(address account, bool enabled) public onlyOwner { _isExcludedFromFees[account] = enabled; } function excludeFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromMaxWalletRestrictions[excludedAddress] = true; } function revokeExcludedFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromMaxWalletRestrictions[excludedAddress] = false; } function isSniperOrBlacklisted(address account) public view returns (bool) { return _isSniperOrBlacklisted[account]; } function isProtected(uint256 rInitializer) external onlyOwner { require (_liqAddStatus == 0, "Error."); _liqAddStatus = rInitializer; snipeBlockAmt = 1; } function setBlacklistEnabled(address account, bool enabled) external onlyOwner() { _isSniperOrBlacklisted[account] = enabled; } function setRatios(uint _liquidity, uint _developer, uint _burn) external onlyOwner { require ( (_liquidity+_developer+_burn) == 777, "!(777)"); Ratios.liquidity = _liquidity; Ratios.developer = _developer; Ratios.burn = _burn;} function setTaxes(uint _buyFee, uint _sellFee, uint _transferFee) external onlyOwner { require(_buyFee <= maxFees.maxBuy && _sellFee <= maxFees.maxSell && _transferFee <= maxFees.maxTransfer, "Cannot exceed maximums."); Fees.buyFee = _buyFee; Fees.sellFee = _sellFee; Fees.transferFee = _transferFee; } function setMaxTxPercent(uint percent, uint divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxTxAmount = check; } function setMaxWalletSize(uint percent, uint divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxWalletSize = check; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; } function setWallets(address payable developerWallet) external onlyOwner { _developerWallet = payable(developerWallet); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _hasLimits(address from, address to) private view returns (bool) { return from != owner() && to != owner() && !_liquidityHolders[to] && !_liquidityHolders[from] && to != DEAD && to != address(0) && from != address(this); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromMaxWalletRestrictions[from] || isExcludedFromMaxWalletRestrictions[to])) { if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if (Ratios.liquidity + Ratios.developer == 0) return; uint256 toLiquify = ((contractTokenBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; uint256 toSwapForEth = contractTokenBalance - toLiquify; swapTokensForEth(toSwapForEth); uint256 currentBalance = address(this).balance; uint256 liquidityBalance = ((currentBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; if (toLiquify > 0) { addLiquidity(toLiquify, liquidityBalance); emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify); } if (contractTokenBalance - toLiquify > 0) { _developerWallet.transfer(address(this).balance); } } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if (Ratios.liquidity + Ratios.developer == 0) return; uint256 toLiquify = ((contractTokenBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; uint256 toSwapForEth = contractTokenBalance - toLiquify; swapTokensForEth(toSwapForEth); uint256 currentBalance = address(this).balance; uint256 liquidityBalance = ((currentBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; if (toLiquify > 0) { addLiquidity(toLiquify, liquidityBalance); emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify); } if (contractTokenBalance - toLiquify > 0) { _developerWallet.transfer(address(this).balance); } } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if (Ratios.liquidity + Ratios.developer == 0) return; uint256 toLiquify = ((contractTokenBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; uint256 toSwapForEth = contractTokenBalance - toLiquify; swapTokensForEth(toSwapForEth); uint256 currentBalance = address(this).balance; uint256 liquidityBalance = ((currentBalance * Ratios.liquidity) / (Ratios.liquidity + Ratios.developer) ) / 2; if (toLiquify > 0) { addLiquidity(toLiquify, liquidityBalance); emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify); } if (contractTokenBalance - toLiquify > 0) { _developerWallet.transfer(address(this).balance); } } function swapTokensForEth(uint256 tokenAmount) internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { address(this), tokenAmount, owner(), block.timestamp ); } dexRouter.addLiquidityETH{value: ethAmount}( function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 1) { _liqAddBlock = block.number + 5000; _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 1) { _liqAddBlock = block.number + 5000; _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 1) { _liqAddBlock = block.number + 5000; _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } } else { function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } } else { function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee; if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != (_decimals)) { revert(); } } uint256 burnAmt = (amount * currentFee * Ratios.burn) / (Ratios.burn + Ratios.liquidity + Ratios.developer ) / masterTaxDivisor; uint256 feeAmount = (amount * currentFee / masterTaxDivisor) - burnAmt; _tOwned[DEAD] += burnAmt; _tOwned[address(this)] += (feeAmount); emit Transfer(from, DEAD, burnAmt); emit Transfer(from, address(this), feeAmount); return amount - feeAmount - burnAmt; } if (to == lpPair) {currentFee = Fees.sellFee;} else if (from == lpPair) {currentFee = Fees.buyFee;} else {currentFee = Fees.transferFee;} function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee; if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != (_decimals)) { revert(); } } uint256 burnAmt = (amount * currentFee * Ratios.burn) / (Ratios.burn + Ratios.liquidity + Ratios.developer ) / masterTaxDivisor; uint256 feeAmount = (amount * currentFee / masterTaxDivisor) - burnAmt; _tOwned[DEAD] += burnAmt; _tOwned[address(this)] += (feeAmount); emit Transfer(from, DEAD, burnAmt); emit Transfer(from, address(this), feeAmount); return amount - feeAmount - burnAmt; } function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee; if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != (_decimals)) { revert(); } } uint256 burnAmt = (amount * currentFee * Ratios.burn) / (Ratios.burn + Ratios.liquidity + Ratios.developer ) / masterTaxDivisor; uint256 feeAmount = (amount * currentFee / masterTaxDivisor) - burnAmt; _tOwned[DEAD] += burnAmt; _tOwned[address(this)] += (feeAmount); emit Transfer(from, DEAD, burnAmt); emit Transfer(from, address(this), feeAmount); return amount - feeAmount - burnAmt; } }
12,081,204
[ 1, 5460, 12565, 10456, 358, 316, 17, 16351, 364, 1679, 452, 2967, 18, 2429, 1432, 631, 16439, 3991, 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, 16351, 7767, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 12423, 10409, 31, 203, 565, 2254, 5034, 3238, 813, 9673, 3024, 4154, 273, 374, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 549, 372, 24237, 27003, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2954, 281, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 16461, 1265, 2747, 16936, 26175, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 10461, 77, 457, 1162, 13155, 18647, 31, 203, 377, 203, 565, 1426, 3238, 1967, 1768, 3896, 273, 638, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 1142, 22583, 31, 377, 203, 203, 565, 2254, 5034, 3238, 5023, 3088, 1283, 273, 2371, 67, 14509, 67, 14509, 67, 14509, 67, 14509, 31, 203, 203, 565, 533, 3238, 389, 529, 273, 315, 24644, 7767, 14432, 203, 565, 533, 3238, 389, 7175, 273, 315, 4211, 14432, 203, 565, 1958, 5320, 281, 288, 203, 565, 2254, 30143, 14667, 31, 203, 565, 2254, 357, 80, 14667, 31, 203, 565, 2254, 7412, 14667, 31, 203, 565, 289, 203, 203, 565, 5320, 281, 1071, 5782, 281, 273, 5320, 281, 12, 203, 565, 288, 70, 9835, 2 ]
./partial_match/56/0xA19Ab7077549Ce730FDc0eFF29b48639Cb0bEC03/sources/MasterChef.sol
Accumulated OATs per share, times 1e12. See below.
uint256 accOatPerShare;
11,304,592
[ 1, 8973, 5283, 690, 531, 789, 87, 1534, 7433, 16, 4124, 404, 73, 2138, 18, 2164, 5712, 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 ]
[ 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, 3639, 2254, 5034, 4078, 51, 270, 2173, 9535, 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, -100, -100 ]
./partial_match/42/0xe529489f6F238689A4BD861305C106dd457B0743/sources/CompoundNoFoldStrategyUSDTMainnet.sol
* Exits Compound and transfers everything to the vault./
function withdrawAllToVault() external restricted updateSupplyInTheEnd { if (allowEmergencyLiquidityShortage) { withdrawMaximum(); withdrawAllWeInvested(); } IERC20(address(underlying)).safeTransfer(vault, underlying.balanceOf(address(this))); }
3,339,133
[ 1, 424, 1282, 21327, 471, 29375, 7756, 358, 326, 9229, 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 ]
[ 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, 598, 9446, 1595, 774, 12003, 1435, 3903, 15693, 1089, 3088, 1283, 382, 1986, 1638, 288, 203, 3639, 309, 261, 5965, 1514, 24530, 48, 18988, 24237, 4897, 410, 13, 288, 203, 5411, 598, 9446, 13528, 5621, 203, 5411, 598, 9446, 1595, 3218, 3605, 3149, 5621, 203, 3639, 289, 203, 3639, 467, 654, 39, 3462, 12, 2867, 12, 9341, 6291, 13, 2934, 4626, 5912, 12, 26983, 16, 6808, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 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 ]
pragma solidity ^0.4.11; contract PullPayInterface { function asyncSend(address _dest) public payable; } contract Governable { // list of admins, council at first spot address[] public admins; function Governable() { admins.length = 1; admins[0] = msg.sender; } modifier onlyAdmins() { bool isAdmin = false; for (uint256 i = 0; i < admins.length; i++) { if (msg.sender == admins[i]) { isAdmin = true; } } require(isAdmin == true); _; } function addAdmin(address _admin) public onlyAdmins { for (uint256 i = 0; i < admins.length; i++) { require(_admin != admins[i]); } require(admins.length < 10); admins[admins.length++] = _admin; } function removeAdmin(address _admin) public onlyAdmins { uint256 pos = admins.length; for (uint256 i = 0; i < admins.length; i++) { if (_admin == admins[i]) { pos = i; } } require(pos < admins.length); // if not last element, switch with last if (pos < admins.length - 1) { admins[pos] = admins[admins.length - 1]; } // then cut off the tail admins.length--; } } contract StorageEnabled { // satelite contract addresses address public storageAddr; function StorageEnabled(address _storageAddr) { storageAddr = _storageAddr; } // ############################################ // ########### NUTZ FUNCTIONS ################ // ############################################ // all Nutz balances function babzBalanceOf(address _owner) constant returns (uint256) { return Storage(storageAddr).getBal('Nutz', _owner); } function _setBabzBalanceOf(address _owner, uint256 _newValue) internal { Storage(storageAddr).setBal('Nutz', _owner, _newValue); } // active supply - sum of balances above function activeSupply() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'activeSupply'); } function _setActiveSupply(uint256 _newActiveSupply) internal { Storage(storageAddr).setUInt('Nutz', 'activeSupply', _newActiveSupply); } // burn pool - inactive supply function burnPool() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'burnPool'); } function _setBurnPool(uint256 _newBurnPool) internal { Storage(storageAddr).setUInt('Nutz', 'burnPool', _newBurnPool); } // power pool - inactive supply function powerPool() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'powerPool'); } function _setPowerPool(uint256 _newPowerPool) internal { Storage(storageAddr).setUInt('Nutz', 'powerPool', _newPowerPool); } // ############################################ // ########### POWER FUNCTIONS ############# // ############################################ // all power balances function powerBalanceOf(address _owner) constant returns (uint256) { return Storage(storageAddr).getBal('Power', _owner); } function _setPowerBalanceOf(address _owner, uint256 _newValue) internal { Storage(storageAddr).setBal('Power', _owner, _newValue); } function outstandingPower() constant returns (uint256) { return Storage(storageAddr).getUInt('Power', 'outstandingPower'); } function _setOutstandingPower(uint256 _newOutstandingPower) internal { Storage(storageAddr).setUInt('Power', 'outstandingPower', _newOutstandingPower); } function authorizedPower() constant returns (uint256) { return Storage(storageAddr).getUInt('Power', 'authorizedPower'); } function _setAuthorizedPower(uint256 _newAuthorizedPower) internal { Storage(storageAddr).setUInt('Power', 'authorizedPower', _newAuthorizedPower); } function downs(address _user) constant public returns (uint256 total, uint256 left, uint256 start) { uint256 rawBytes = Storage(storageAddr).getBal('PowerDown', _user); start = uint64(rawBytes); left = uint96(rawBytes >> (64)); total = uint96(rawBytes >> (96 + 64)); return; } function _setDownRequest(address _holder, uint256 total, uint256 left, uint256 start) internal { uint256 result = uint64(start) + (left << 64) + (total << (96 + 64)); Storage(storageAddr).setBal('PowerDown', _holder, result); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Governable { bool public paused = true; /** * @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() onlyAdmins whenNotPaused { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyAdmins whenPaused { //TODO: do some checks paused = false; } } /* * ERC20Basic * Simpler version of ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { function totalSupply() constant returns (uint256); function balanceOf(address _owner) constant returns (uint256); function transfer(address _to, uint256 _value) returns (bool); event Transfer(address indexed from, address indexed to, uint value); } contract ERC223Basic is ERC20Basic { function transfer(address to, uint value, bytes data) returns (bool); } /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC223Basic { // active supply of tokens function activeSupply() constant returns (uint256); function allowance(address _owner, address _spender) constant returns (uint256); function transferFrom(address _from, address _to, uint _value) returns (bool); function approve(address _spender, uint256 _value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract Power is Ownable, ERC20Basic { event Slashing(address indexed holder, uint value, bytes32 data); string public name = "Acebusters Power"; string public symbol = "ABP"; uint256 public decimals = 12; function balanceOf(address _holder) constant returns (uint256) { return ControllerInterface(owner).powerBalanceOf(_holder); } function totalSupply() constant returns (uint256) { return ControllerInterface(owner).powerTotalSupply(); } function activeSupply() constant returns (uint256) { return ControllerInterface(owner).outstandingPower(); } // ############################################ // ########### ADMIN FUNCTIONS ################ // ############################################ function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyOwner { Slashing(_holder, _value, _data); } function powerUp(address _holder, uint256 _value) public onlyOwner { // NTZ transfered from user's balance to power pool Transfer(address(0), _holder, _value); } // ############################################ // ########### PUBLIC FUNCTIONS ############### // ############################################ // registers a powerdown request function transfer(address _to, uint256 _amountPower) public returns (bool success) { // make Power not transferable require(_to == address(0)); ControllerInterface(owner).createDownRequest(msg.sender, _amountPower); Transfer(msg.sender, address(0), _amountPower); return true; } function downtime() public returns (uint256) { ControllerInterface(owner).downtime; } function downTick(address _owner) public { ControllerInterface(owner).downTick(_owner, now); } function downs(address _owner) constant public returns (uint256, uint256, uint256) { return ControllerInterface(owner).downs(_owner); } } contract Storage is Ownable { struct Crate { mapping(bytes32 => uint256) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(address => uint256) bals; } mapping(bytes32 => Crate) crates; function setUInt(bytes32 _crate, bytes32 _key, uint256 _value) onlyOwner { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) constant returns(uint256) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) onlyOwner { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) constant returns(address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) onlyOwner { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) constant returns(bool) { return crates[_crate].bools[_key]; } function setBal(bytes32 _crate, address _key, uint256 _value) onlyOwner { crates[_crate].bals[_key] = _value; } function getBal(bytes32 _crate, address _key) constant returns(uint256) { return crates[_crate].bals[_key]; } } contract NutzEnabled is Pausable, StorageEnabled { using SafeMath for uint; // satelite contract addresses address public nutzAddr; modifier onlyNutz() { require(msg.sender == nutzAddr); _; } function NutzEnabled(address _nutzAddr, address _storageAddr) StorageEnabled(_storageAddr) { nutzAddr = _nutzAddr; } // ############################################ // ########### NUTZ FUNCTIONS ################ // ############################################ // total supply(modified for etherscan display) function totalSupply() constant returns (uint256) { return activeSupply(); } // total supply(for internal calculations) function completeSupply() constant returns (uint256) { return activeSupply().add(powerPool()).add(burnPool()); } // allowances according to ERC20 // not written to storage, as not very critical mapping (address => mapping (address => uint)) internal allowed; function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } function approve(address _owner, address _spender, uint256 _amountBabz) public onlyNutz whenNotPaused { require(_owner != _spender); allowed[_owner][_spender] = _amountBabz; } function _transfer(address _from, address _to, uint256 _amountBabz, bytes _data) internal { require(_to != address(this)); require(_to != address(0)); require(_amountBabz > 0); require(_from != _to); _setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz)); _setBabzBalanceOf(_to, babzBalanceOf(_to).add(_amountBabz)); } function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused { _transfer(_from, _to, _amountBabz, _data); } function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused { allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz); _transfer(_from, _to, _amountBabz, _data); } } /* * Contract that is working with ERC223 tokens */ contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data); } contract ControllerInterface { // State Variables bool public paused; address public nutzAddr; // Nutz functions function babzBalanceOf(address _owner) constant returns (uint256); function activeSupply() constant returns (uint256); function burnPool() constant returns (uint256); function powerPool() constant returns (uint256); function totalSupply() constant returns (uint256); function completeSupply() constant returns (uint256); function allowance(address _owner, address _spender) constant returns (uint256); function approve(address _owner, address _spender, uint256 _amountBabz) public; function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public; function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public; // Market functions function floor() constant returns (uint256); function ceiling() constant returns (uint256); function purchase(address _sender, uint256 _value, uint256 _price) public returns (uint256); function sell(address _from, uint256 _price, uint256 _amountBabz); // Power functions function powerBalanceOf(address _owner) constant returns (uint256); function outstandingPower() constant returns (uint256); function authorizedPower() constant returns (uint256); function powerTotalSupply() constant returns (uint256); function powerUp(address _sender, address _from, uint256 _amountBabz) public; function downTick(address _owner, uint256 _now) public; function createDownRequest(address _owner, uint256 _amountPower) public; function downs(address _owner) constant public returns(uint256, uint256, uint256); function downtime() constant returns (uint256); } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. */ contract PullPayment is Ownable { using SafeMath for uint256; uint public dailyLimit = 1000000000000000000000; // 1 ETH uint public lastDay; uint public spentToday; // 8bytes date, 24 bytes value mapping(address => uint256) internal payments; modifier onlyNutz() { require(msg.sender == ControllerInterface(owner).nutzAddr()); _; } modifier whenNotPaused () { require(!ControllerInterface(owner).paused()); _; } function balanceOf(address _owner) constant returns (uint256 value) { return uint192(payments[_owner]); } function paymentOf(address _owner) constant returns (uint256 value, uint256 date) { value = uint192(payments[_owner]); date = (payments[_owner] >> 192); return; } /// @dev Allows to change the daily limit. Transaction has to be sent by wallet. /// @param _dailyLimit Amount in wei. function changeDailyLimit(uint _dailyLimit) public onlyOwner { dailyLimit = _dailyLimit; } function changeWithdrawalDate(address _owner, uint256 _newDate) public onlyOwner { // allow to withdraw immediately // move witdrawal date more days into future payments[_owner] = (_newDate << 192) + uint192(payments[_owner]); } function asyncSend(address _dest) public payable onlyNutz { require(msg.value > 0); uint256 newValue = msg.value.add(uint192(payments[_dest])); uint256 newDate; if (isUnderLimit(msg.value)) { uint256 date = payments[_dest] >> 192; newDate = (date > now) ? date : now; } else { newDate = now.add(3 days); } spentToday = spentToday.add(msg.value); payments[_dest] = (newDate << 192) + uint192(newValue); } function withdraw() public whenNotPaused { address untrustedRecipient = msg.sender; uint256 amountWei = uint192(payments[untrustedRecipient]); require(amountWei != 0); require(now >= (payments[untrustedRecipient] >> 192)); require(this.balance >= amountWei); payments[untrustedRecipient] = 0; assert(untrustedRecipient.call.gas(1000).value(amountWei)()); } /* * Internal functions */ /// @dev Returns if amount is within daily limit and resets spentToday after one day. /// @param amount Amount to withdraw. /// @return Returns if amount is under daily limit. function isUnderLimit(uint amount) internal returns (bool) { if (now > lastDay.add(24 hours)) { lastDay = now; spentToday = 0; } // not using safe math because we don't want to throw; if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) { return false; } return true; } } /** * Nutz implements a price floor and a price ceiling on the token being * sold. It is based of the zeppelin token contract. */ contract Nutz is Ownable, ERC20 { event Sell(address indexed seller, uint256 value); string public name = "Acebusters Nutz"; // acebusters units: // 10^12 - Nutz (NTZ) // 10^9 - Jonyz // 10^6 - Helcz // 10^3 - Pascalz // 10^0 - Babz string public symbol = "NTZ"; uint256 public decimals = 12; // returns balances of active holders function balanceOf(address _owner) constant returns (uint) { return ControllerInterface(owner).babzBalanceOf(_owner); } function totalSupply() constant returns (uint256) { return ControllerInterface(owner).totalSupply(); } function activeSupply() constant returns (uint256) { return ControllerInterface(owner).activeSupply(); } // return remaining allowance // if calling return allowed[address(this)][_spender]; // returns balance of ether parked to be withdrawn function allowance(address _owner, address _spender) constant returns (uint256) { return ControllerInterface(owner).allowance(_owner, _spender); } // returns either the salePrice, or if reserve does not suffice // for active supply, returns maxFloor function floor() constant returns (uint256) { return ControllerInterface(owner).floor(); } // returns either the salePrice, or if reserve does not suffice // for active supply, returns maxFloor function ceiling() constant returns (uint256) { return ControllerInterface(owner).ceiling(); } function powerPool() constant returns (uint256) { return ControllerInterface(owner).powerPool(); } function _checkDestination(address _from, address _to, uint256 _value, bytes _data) internal { // erc223: Retrieve the size of the code on target address, this needs assembly . uint256 codeLength; assembly { codeLength := extcodesize(_to) } if(codeLength>0) { ERC223ReceivingContract untrustedReceiver = ERC223ReceivingContract(_to); // untrusted contract call untrustedReceiver.tokenFallback(_from, _value, _data); } } // ############################################ // ########### ADMIN FUNCTIONS ################ // ############################################ function powerDown(address powerAddr, address _holder, uint256 _amountBabz) public onlyOwner { bytes memory empty; _checkDestination(powerAddr, _holder, _amountBabz, empty); // NTZ transfered from power pool to user's balance Transfer(powerAddr, _holder, _amountBabz); } function asyncSend(address _pullAddr, address _dest, uint256 _amountWei) public onlyOwner { assert(_amountWei <= this.balance); PullPayInterface(_pullAddr).asyncSend.value(_amountWei)(_dest); } // ############################################ // ########### PUBLIC FUNCTIONS ############### // ############################################ function approve(address _spender, uint256 _amountBabz) public { ControllerInterface(owner).approve(msg.sender, _spender, _amountBabz); Approval(msg.sender, _spender, _amountBabz); } function transfer(address _to, uint256 _amountBabz, bytes _data) public returns (bool) { ControllerInterface(owner).transfer(msg.sender, _to, _amountBabz, _data); Transfer(msg.sender, _to, _amountBabz); _checkDestination(msg.sender, _to, _amountBabz, _data); return true; } function transfer(address _to, uint256 _amountBabz) public returns (bool) { bytes memory empty; return transfer(_to, _amountBabz, empty); } function transData(address _to, uint256 _amountBabz, bytes _data) public returns (bool) { return transfer(_to, _amountBabz, _data); } function transferFrom(address _from, address _to, uint256 _amountBabz, bytes _data) public returns (bool) { ControllerInterface(owner).transferFrom(msg.sender, _from, _to, _amountBabz, _data); Transfer(_from, _to, _amountBabz); _checkDestination(_from, _to, _amountBabz, _data); return true; } function transferFrom(address _from, address _to, uint256 _amountBabz) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _amountBabz, empty); } function () public payable { uint256 price = ControllerInterface(owner).ceiling(); purchase(price); require(msg.value > 0); } function purchase(uint256 _price) public payable { require(msg.value > 0); uint256 amountBabz = ControllerInterface(owner).purchase(msg.sender, msg.value, _price); Transfer(owner, msg.sender, amountBabz); bytes memory empty; _checkDestination(address(this), msg.sender, amountBabz, empty); } function sell(uint256 _price, uint256 _amountBabz) public { require(_amountBabz != 0); ControllerInterface(owner).sell(msg.sender, _price, _amountBabz); Sell(msg.sender, _amountBabz); } function powerUp(uint256 _amountBabz) public { Transfer(msg.sender, owner, _amountBabz); ControllerInterface(owner).powerUp(msg.sender, msg.sender, _amountBabz); } } contract MarketEnabled is NutzEnabled { uint256 constant INFINITY = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // address of the pull payemnt satelite address public pullAddr; // the Token sale mechanism parameters: // purchasePrice is the number of NTZ received for purchase with 1 ETH uint256 internal purchasePrice; // floor is the number of NTZ needed, to receive 1 ETH in sell uint256 internal salePrice; function MarketEnabled(address _pullAddr, address _storageAddr, address _nutzAddr) NutzEnabled(_nutzAddr, _storageAddr) { pullAddr = _pullAddr; } function ceiling() constant returns (uint256) { return purchasePrice; } // returns either the salePrice, or if reserve does not suffice // for active supply, returns maxFloor function floor() constant returns (uint256) { if (nutzAddr.balance == 0) { return INFINITY; } uint256 maxFloor = activeSupply().mul(1000000).div(nutzAddr.balance); // 1,000,000 WEI, used as price factor // return max of maxFloor or salePrice return maxFloor >= salePrice ? maxFloor : salePrice; } function moveCeiling(uint256 _newPurchasePrice) public onlyAdmins { require(_newPurchasePrice <= salePrice); purchasePrice = _newPurchasePrice; } function moveFloor(uint256 _newSalePrice) public onlyAdmins { require(_newSalePrice >= purchasePrice); // moveFloor fails if the administrator tries to push the floor so low // that the sale mechanism is no longer able to buy back all tokens at // the floor price if those funds were to be withdrawn. if (_newSalePrice < INFINITY) { require(nutzAddr.balance >= activeSupply().mul(1000000).div(_newSalePrice)); // 1,000,000 WEI, used as price factor } salePrice = _newSalePrice; } function purchase(address _sender, uint256 _value, uint256 _price) public onlyNutz whenNotPaused returns (uint256) { // disable purchases if purchasePrice set to 0 require(purchasePrice > 0); require(_price == purchasePrice); uint256 amountBabz = purchasePrice.mul(_value).div(1000000); // 1,000,000 WEI, used as price factor // avoid deposits that issue nothing // might happen with very high purchase price require(amountBabz > 0); // make sure power pool grows proportional to economy uint256 activeSup = activeSupply(); uint256 powPool = powerPool(); if (powPool > 0) { uint256 powerShare = powPool.mul(amountBabz).div(activeSup.add(burnPool())); _setPowerPool(powPool.add(powerShare)); } _setActiveSupply(activeSup.add(amountBabz)); _setBabzBalanceOf(_sender, babzBalanceOf(_sender).add(amountBabz)); return amountBabz; } function sell(address _from, uint256 _price, uint256 _amountBabz) public onlyNutz whenNotPaused { uint256 effectiveFloor = floor(); require(_amountBabz != 0); require(effectiveFloor != INFINITY); require(_price == effectiveFloor); uint256 amountWei = _amountBabz.mul(1000000).div(effectiveFloor); // 1,000,000 WEI, used as price factor require(amountWei > 0); // make sure power pool shrinks proportional to economy uint256 powPool = powerPool(); uint256 activeSup = activeSupply(); if (powPool > 0) { uint256 powerShare = powPool.mul(_amountBabz).div(activeSup.add(burnPool())); _setPowerPool(powPool.sub(powerShare)); } _setActiveSupply(activeSup.sub(_amountBabz)); _setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz)); Nutz(nutzAddr).asyncSend(pullAddr, _from, amountWei); } // withdraw excessive reserve - i.e. milestones function allocateEther(uint256 _amountWei, address _beneficiary) public onlyAdmins { require(_amountWei > 0); // allocateEther fails if allocating those funds would mean that the // sale mechanism is no longer able to buy back all tokens at the floor // price if those funds were to be withdrawn. require(nutzAddr.balance.sub(_amountWei) >= activeSupply().mul(1000000).div(salePrice)); // 1,000,000 WEI, used as price factor Nutz(nutzAddr).asyncSend(pullAddr, _beneficiary, _amountWei); } } contract PowerEnabled is MarketEnabled { // satelite contract addresses address public powerAddr; // maxPower is a limit of total power that can be outstanding // maxPower has a valid value between outstandingPower and authorizedPow/2 uint256 public maxPower = 0; // time it should take to power down uint256 public downtime; uint public constant MIN_SHARE_OF_POWER = 100000; modifier onlyPower() { require(msg.sender == powerAddr); _; } function PowerEnabled(address _powerAddr, address _pullAddr, address _storageAddr, address _nutzAddr) MarketEnabled(_pullAddr, _nutzAddr, _storageAddr) { powerAddr = _powerAddr; } function setMaxPower(uint256 _maxPower) public onlyAdmins { require(outstandingPower() <= _maxPower && _maxPower < authorizedPower()); maxPower = _maxPower; } function setDowntime(uint256 _downtime) public onlyAdmins { downtime = _downtime; } function minimumPowerUpSizeBabz() public constant returns (uint256) { uint256 completeSupplyBabz = completeSupply(); if (completeSupplyBabz == 0) { return INFINITY; } return completeSupplyBabz.div(MIN_SHARE_OF_POWER); } // this is called when NTZ are deposited into the burn pool function dilutePower(uint256 _amountBabz, uint256 _amountPower) public onlyAdmins { uint256 authorizedPow = authorizedPower(); uint256 totalBabz = completeSupply(); if (authorizedPow == 0) { // during the first capital increase, set value directly as authorized shares _setAuthorizedPower((_amountPower > 0) ? _amountPower : _amountBabz.add(totalBabz)); } else { // in later increases, expand authorized shares at same rate like economy _setAuthorizedPower(authorizedPow.mul(totalBabz.add(_amountBabz)).div(totalBabz)); } _setBurnPool(burnPool().add(_amountBabz)); } function _slashPower(address _holder, uint256 _value, bytes32 _data) internal { uint256 previouslyOutstanding = outstandingPower(); _setOutstandingPower(previouslyOutstanding.sub(_value)); // adjust size of power pool uint256 powPool = powerPool(); uint256 slashingBabz = _value.mul(powPool).div(previouslyOutstanding); _setPowerPool(powPool.sub(slashingBabz)); // put event into satelite contract Power(powerAddr).slashPower(_holder, _value, _data); } function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyAdmins { _setPowerBalanceOf(_holder, powerBalanceOf(_holder).sub(_value)); _slashPower(_holder, _value, _data); } function slashDownRequest(uint256 _pos, address _holder, uint256 _value, bytes32 _data) public onlyAdmins { var (total, left, start) = downs(_holder); left = left.sub(_value); _setDownRequest(_holder, total, left, start); _slashPower(_holder, _value, _data); } // this is called when NTZ are deposited into the power pool function powerUp(address _sender, address _from, uint256 _amountBabz) public onlyNutz whenNotPaused { uint256 authorizedPow = authorizedPower(); require(authorizedPow != 0); require(_amountBabz != 0); uint256 totalBabz = completeSupply(); require(totalBabz != 0); uint256 amountPow = _amountBabz.mul(authorizedPow).div(totalBabz); // check pow limits uint256 outstandingPow = outstandingPower(); require(outstandingPow.add(amountPow) <= maxPower); uint256 powBal = powerBalanceOf(_from).add(amountPow); require(powBal >= authorizedPow.div(MIN_SHARE_OF_POWER)); if (_sender != _from) { allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz); } _setOutstandingPower(outstandingPow.add(amountPow)); _setPowerBalanceOf(_from, powBal); _setActiveSupply(activeSupply().sub(_amountBabz)); _setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz)); _setPowerPool(powerPool().add(_amountBabz)); Power(powerAddr).powerUp(_from, amountPow); } function powerTotalSupply() constant returns (uint256) { uint256 issuedPower = authorizedPower().div(2); // return max of maxPower or issuedPower return maxPower >= issuedPower ? maxPower : issuedPower; } function _vestedDown(uint256 _total, uint256 _left, uint256 _start, uint256 _now) internal constant returns (uint256) { if (_now <= _start) { return 0; } // calculate amountVested // amountVested is amount that can be withdrawn according to time passed uint256 timePassed = _now.sub(_start); if (timePassed > downtime) { timePassed = downtime; } uint256 amountVested = _total.mul(timePassed).div(downtime); uint256 amountFrozen = _total.sub(amountVested); if (_left <= amountFrozen) { return 0; } return _left.sub(amountFrozen); } function createDownRequest(address _owner, uint256 _amountPower) public onlyPower whenNotPaused { // prevent powering down tiny amounts // when powering down, at least completeSupply/minShare Power should be claimed require(_amountPower >= authorizedPower().div(MIN_SHARE_OF_POWER)); _setPowerBalanceOf(_owner, powerBalanceOf(_owner).sub(_amountPower)); var (, left, ) = downs(_owner); uint256 total = _amountPower.add(left); _setDownRequest(_owner, total, total, now); } // executes a powerdown request function downTick(address _holder, uint256 _now) public onlyPower whenNotPaused { var (total, left, start) = downs(_holder); uint256 amountPow = _vestedDown(total, left, start, _now); // prevent power down in tiny steps uint256 minStep = total.div(10); require(left <= minStep || minStep <= amountPow); // calculate token amount representing share of power uint256 amountBabz = amountPow.mul(completeSupply()).div(authorizedPower()); // transfer power and tokens _setOutstandingPower(outstandingPower().sub(amountPow)); left = left.sub(amountPow); _setPowerPool(powerPool().sub(amountBabz)); _setActiveSupply(activeSupply().add(amountBabz)); _setBabzBalanceOf(_holder, babzBalanceOf(_holder).add(amountBabz)); // down request completed if (left == 0) { start = 0; total = 0; } // TODO _setDownRequest(_holder, total, left, start); Nutz(nutzAddr).powerDown(powerAddr, _holder, amountBabz); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Controller is PowerEnabled { function Controller(address _powerAddr, address _pullAddr, address _nutzAddr, address _storageAddr) PowerEnabled(_powerAddr, _pullAddr, _nutzAddr, _storageAddr) { } function setContracts(address _storageAddr, address _nutzAddr, address _powerAddr, address _pullAddr) public onlyAdmins whenPaused { storageAddr = _storageAddr; nutzAddr = _nutzAddr; powerAddr = _powerAddr; pullAddr = _pullAddr; } function changeDailyLimit(uint256 _dailyLimit) public onlyAdmins { PullPayment(pullAddr).changeDailyLimit(_dailyLimit); } function kill(address _newController) public onlyAdmins whenPaused { if (powerAddr != address(0)) { Ownable(powerAddr).transferOwnership(msg.sender); } if (pullAddr != address(0)) { Ownable(pullAddr).transferOwnership(msg.sender); } if (nutzAddr != address(0)) { Ownable(nutzAddr).transferOwnership(msg.sender); } if (storageAddr != address(0)) { Ownable(storageAddr).transferOwnership(msg.sender); } selfdestruct(_newController); } }
return remaining allowance if calling return allowed[address(this)][_spender]; returns balance of ether parked to be withdrawn
function allowance(address _owner, address _spender) constant returns (uint256) { return ControllerInterface(owner).allowance(_owner, _spender); }
1,002,671
[ 1, 2463, 4463, 1699, 1359, 309, 4440, 327, 2935, 63, 2867, 12, 2211, 13, 6362, 67, 87, 1302, 264, 15533, 1135, 11013, 434, 225, 2437, 779, 79, 329, 358, 506, 598, 9446, 82, 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, 225, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 6629, 1358, 12, 8443, 2934, 5965, 1359, 24899, 8443, 16, 389, 87, 1302, 264, 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, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISVG image library types interface /// @dev Allows Solidity files to reference the library's input and return types without referencing the library itself interface ISVGTypes { /// Represents a color in RGB format with alpha struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; } /// Represents a color attribute in an SVG image file enum ColorAttribute { Fill, Stroke, Stop } /// Represents the kind of color attribute in an SVG image file enum ColorAttributeKind { RGB, URL } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @dev String operations with decimals library DecimalStrings { /// @dev Converts a `uint256` to its ASCII `string` representation with decimal places. function toDecimalString(uint256 value, uint256 decimals, bool isNegative) internal pure returns (bytes memory) { // Inspired by OpenZeppelin's implementation - MIT licence // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol uint256 temp = value; uint256 characters; do { characters++; temp /= 10; } while (temp != 0); if (characters <= decimals) { characters += 2 + (decimals - characters); } else if (decimals > 0) { characters += 1; } temp = isNegative ? 1 : 0; // reuse 'temp' as a sign symbol offset characters += temp; bytes memory buffer = new bytes(characters); while (characters > temp) { characters -= 1; if (decimals > 0 && (buffer.length - characters - 1) == decimals) { buffer[characters] = bytes1(uint8(46)); decimals = 0; // Cut off any further checks for the decimal place } else if (value != 0) { buffer[characters] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } else { buffer[characters] = bytes1(uint8(48)); } } if (isNegative) { buffer[0] = bytes1(uint8(45)); } return buffer; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "base64-sol/base64.sol"; /// @title OnChain metadata support library /** * @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). * Do not waste gas using these methods in functions that also update state, unless your need requires it. */ library OnChain { /// Returns the prefix needed for a base64-encoded on chain svg image function baseSvgImageURI() internal pure returns (bytes memory) { return "data:image/svg+xml;base64,"; } /// Returns the prefix needed for a base64-encoded on chain nft metadata function baseURI() internal pure returns (bytes memory) { return "data:application/json;base64,"; } /// Returns the contents joined with a comma between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @return A collection of bytes that represent all contents joined with a comma function commaSeparated(bytes memory contents1, bytes memory contents2) internal pure returns (bytes memory) { return abi.encodePacked(contents1, continuesWith(contents2)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2), continuesWith(contents3)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3), continuesWith(contents4)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @param contents5 The fifth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4, bytes memory contents5) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3, contents4), continuesWith(contents5)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @param contents5 The fifth content to join /// @param contents6 The sixth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4, bytes memory contents5, bytes memory contents6) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3, contents4, contents5), continuesWith(contents6)); } /// Returns the contents prefixed by a comma /// @dev This is used to append multiple attributes into the json /// @param contents The contents with which to prefix /// @return A bytes collection of the contents prefixed with a comma function continuesWith(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked(",", contents); } /// Returns the contents wrapped in a json dictionary /// @param contents The contents with which to wrap /// @return A bytes collection of the contents wrapped as a json dictionary function dictionary(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked("{", contents, "}"); } /// Returns an unwrapped key/value pair where the value is an array /// @param key The name of the key used in the pair /// @param value The value of pair, as an array /// @return A bytes collection that is suitable for inclusion in a larger dictionary function keyValueArray(string memory key, bytes memory value) internal pure returns (bytes memory) { return abi.encodePacked("\"", key, "\":[", value, "]"); } /// Returns an unwrapped key/value pair where the value is a string /// @param key The name of the key used in the pair /// @param value The value of pair, as a string /// @return A bytes collection that is suitable for inclusion in a larger dictionary function keyValueString(string memory key, bytes memory value) internal pure returns (bytes memory) { return abi.encodePacked("\"", key, "\":\"", value, "\""); } /// Encodes an SVG as base64 and prefixes it with a URI scheme suitable for on-chain data /// @param svg The contents of the svg /// @return A bytes collection that may be added to the "image" key/value pair in ERC-721 or ERC-1155 metadata function svgImageURI(bytes memory svg) internal pure returns (bytes memory) { return abi.encodePacked(baseSvgImageURI(), Base64.encode(svg)); } /// Encodes json as base64 and prefixes it with a URI scheme suitable for on-chain data /// @param metadata The contents of the metadata /// @return A bytes collection that may be returned as the tokenURI in a ERC-721 or ERC-1155 contract function tokenURI(bytes memory metadata) internal pure returns (bytes memory) { return abi.encodePacked(baseURI(), Base64.encode(metadata)); } /// Returns the json dictionary of a single trait attribute for an ERC-721 or ERC-1155 NFT /// @param name The name of the trait /// @param value The value of the trait /// @return A collection of bytes that can be embedded within a larger array of attributes function traitAttribute(string memory name, bytes memory value) internal pure returns (bytes memory) { return dictionary(commaSeparated( keyValueString("trait_type", bytes(name)), keyValueString("value", value) )); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./RandomizationErrors.sol"; /// @title Randomization library /// @dev Lightweight library used for basic randomization capabilities for ERC-721 tokens when an Oracle is not available library Randomization { /// Returns a value based on the spread of a random uint8 seed and provided percentages /// @dev The last percentage is assumed if the sum of all elements do not add up to 100, in which case the length of the array is returned /// @param random A uint8 random value /// @param percentages An array of percentages /// @return The index in which the random seed falls, which can be the length of the input array if the values do not add up to 100 function randomIndex(uint8 random, uint8[] memory percentages) internal pure returns (uint256) { uint256 spread = (3921 * uint256(random) / 10000) % 100; // 0-255 needs to be balanced to evenly spread with % 100 uint256 remainingPercent = 100; for (uint256 i = 0; i < percentages.length; i++) { uint256 nextPercentage = percentages[i]; if (remainingPercent < nextPercentage) revert PercentagesGreaterThan100(); remainingPercent -= nextPercentage; if (spread >= remainingPercent) { return i; } } return percentages.length; } /// Returns a random seed suitable for ERC-721 attribute generation when an Oracle such as Chainlink VRF is not available to a contract /// @dev Not suitable for mission-critical code. Always be sure to perform an analysis of your randomization before deploying to production /// @param initialSeed A uint256 that seeds the randomization function /// @return A seed that can be used for attribute generation, which may also be used as the `initialSeed` for a future call function randomSeed(uint256 initialSeed) internal view returns (uint256) { // Unit tests should confirm that this provides a more-or-less even spread of randomness return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, initialSeed >> 1))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the percentages array sum up to more than 100 error PercentagesGreaterThan100(); // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/ISVGTypes.sol"; import "./OnChain.sol"; import "./SVGErrors.sol"; /// @title SVG image library /** * @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). * Do not waste gas using these methods in functions that also update state, unless your need requires it. */ library SVG { using Strings for uint256; /// Returns a named element based on the supplied attributes and contents /// @dev attributes and contents is usually generated from abi.encodePacked, attributes is expecting a leading space /// @param name The name of the element /// @param attributes The attributes of the element, as bytes, with a leading space /// @param contents The contents of the element, as bytes /// @return a bytes collection representing the whole element function createElement(string memory name, bytes memory attributes, bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked( "<", attributes.length == 0 ? bytes(name) : abi.encodePacked(name, attributes), contents.length == 0 ? bytes("/>") : abi.encodePacked(">", contents, "</", name, ">") ); } /// Returns the root SVG attributes based on the supplied width and height /// @dev includes necessary leading space for createElement's `attributes` parameter /// @param width The width of the SVG view box /// @param height The height of the SVG view box /// @return a bytes collection representing the root SVG attributes, including a leading space function svgAttributes(uint256 width, uint256 height) internal pure returns (bytes memory) { return abi.encodePacked(" viewBox='0 0 ", width.toString(), " ", height.toString(), "' xmlns='http://www.w3.org/2000/svg'"); } /// Returns an RGB bytes collection suitable as an attribute for SVG elements based on the supplied Color and ColorType /// @dev includes necessary leading space for all types _except_ None /// @param attribute The `ISVGTypes.ColorAttribute` of the desired attribute /// @param value The converted color value as bytes /// @return a bytes collection representing a color attribute in an SVG element function colorAttribute(ISVGTypes.ColorAttribute attribute, bytes memory value) internal pure returns (bytes memory) { if (attribute == ISVGTypes.ColorAttribute.Fill) return _attribute("fill", value); if (attribute == ISVGTypes.ColorAttribute.Stop) return _attribute("stop-color", value); return _attribute("stroke", value); // Fallback to Stroke } /// Returns an RGB color attribute value /// @param color The `ISVGTypes.Color` of the color /// @return a bytes collection representing the url attribute value function colorAttributeRGBValue(ISVGTypes.Color memory color) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.RGB, OnChain.commaSeparated( bytes(uint256(color.red).toString()), bytes(uint256(color.green).toString()), bytes(uint256(color.blue).toString()) )); } /// Returns a URL color attribute value /// @param url The url to the color /// @return a bytes collection representing the url attribute value function colorAttributeURLValue(bytes memory url) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.URL, url); } /// Returns an `ISVGTypes.Color` that is brightened by the provided percentage /// @param source The `ISVGTypes.Color` to brighten /// @param percentage The percentage of brightness to apply /// @param minimumBump A minimum increase for each channel to ensure dark Colors also brighten /// @return color the brightened `ISVGTypes.Color` function brightenColor(ISVGTypes.Color memory source, uint32 percentage, uint8 minimumBump) internal pure returns (ISVGTypes.Color memory color) { color.red = _brightenComponent(source.red, percentage, minimumBump); color.green = _brightenComponent(source.green, percentage, minimumBump); color.blue = _brightenComponent(source.blue, percentage, minimumBump); color.alpha = source.alpha; } /// Returns an `ISVGTypes.Color` based on a packed representation of r, g, and b /// @notice Useful for code where you want to utilize rgb hex values provided by a designer (e.g. #835525) /// @dev Alpha will be hard-coded to 100% opacity /// @param packedColor The `ISVGTypes.Color` to convert, e.g. 0x835525 /// @return color representing the packed input function fromPackedColor(uint24 packedColor) internal pure returns (ISVGTypes.Color memory color) { color.red = uint8(packedColor >> 16); color.green = uint8(packedColor >> 8); color.blue = uint8(packedColor); color.alpha = 0xFF; } /// Returns a mixed Color by balancing the ratio of `color1` over `color2`, with a total percentage (for overmixing and undermixing outside the source bounds) /// @dev Reverts with `RatioInvalid()` if `ratioPercentage` is > 100 /// @param color1 The first `ISVGTypes.Color` to mix /// @param color2 The second `ISVGTypes.Color` to mix /// @param ratioPercentage The percentage ratio of `color1` over `color2` (e.g. 60 = 60% first, 40% second) /// @param totalPercentage The total percentage after mixing (for overmixing and undermixing outside the input colors) /// @return color representing the result of the mixture function mixColors(ISVGTypes.Color memory color1, ISVGTypes.Color memory color2, uint32 ratioPercentage, uint32 totalPercentage) internal pure returns (ISVGTypes.Color memory color) { if (ratioPercentage > 100) revert RatioInvalid(); color.red = _mixComponents(color1.red, color2.red, ratioPercentage, totalPercentage); color.green = _mixComponents(color1.green, color2.green, ratioPercentage, totalPercentage); color.blue = _mixComponents(color1.blue, color2.blue, ratioPercentage, totalPercentage); color.alpha = _mixComponents(color1.alpha, color2.alpha, ratioPercentage, totalPercentage); } /// Returns a proportionally-randomized Color between the start and stop colors using a random Color seed /// @dev Each component (r,g,b) will move proportionally together in the direction from start to stop /// @param start The starting bound of the `ISVGTypes.Color` to randomize /// @param stop The stopping bound of the `ISVGTypes.Color` to randomize /// @param random An `ISVGTypes.Color` to use as a seed for randomization /// @return color representing the result of the randomization function randomizeColors(ISVGTypes.Color memory start, ISVGTypes.Color memory stop, ISVGTypes.Color memory random) internal pure returns (ISVGTypes.Color memory color) { uint16 percent = uint16((1320 * (uint(random.red) + uint(random.green) + uint(random.blue)) / 10000) % 101); // Range is from 0-100 color.red = _randomizeComponent(start.red, stop.red, random.red, percent); color.green = _randomizeComponent(start.green, stop.green, random.green, percent); color.blue = _randomizeComponent(start.blue, stop.blue, random.blue, percent); color.alpha = 0xFF; } function _attribute(bytes memory name, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(" ", name, "='", contents, "'"); } function _brightenComponent(uint8 component, uint32 percentage, uint8 minimumBump) private pure returns (uint8 result) { uint32 wideComponent = uint32(component); uint32 brightenedComponent = wideComponent * (percentage + 100) / 100; uint32 wideMinimumBump = uint32(minimumBump); if (brightenedComponent - wideComponent < wideMinimumBump) { brightenedComponent = wideComponent + wideMinimumBump; } if (brightenedComponent > 0xFF) { result = 0xFF; // Clamp to 8 bits } else { result = uint8(brightenedComponent); } } function _colorValue(ISVGTypes.ColorAttributeKind attributeKind, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(attributeKind == ISVGTypes.ColorAttributeKind.RGB ? "rgb(" : "url(#", contents, ")"); } function _mixComponents(uint8 component1, uint8 component2, uint32 ratioPercentage, uint32 totalPercentage) private pure returns (uint8 component) { uint32 mixedComponent = (uint32(component1) * ratioPercentage + uint32(component2) * (100 - ratioPercentage)) * totalPercentage / 10000; if (mixedComponent > 0xFF) { component = 0xFF; // Clamp to 8 bits } else { component = uint8(mixedComponent); } } function _randomizeComponent(uint8 start, uint8 stop, uint8 random, uint16 percent) private pure returns (uint8 component) { if (start == stop) { component = start; } else { // This is the standard case (uint8 floor, uint8 ceiling) = start < stop ? (start, stop) : (stop, start); component = floor + uint8(uint16(ceiling - (random & 0x01) - floor) * percent / uint16(100)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the ratio percentage provided to a function is > 100 error RatioInvalid(); // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Gen 3 TwoBitBear traits provider /// @notice Provides IBear3Traits to the blockchain interface IBear3TraitProvider{ /// Returns the traits associated with a given token ID /// @dev Throws if the token ID is not valid /// @param tokenId The ID of the token that represents the Bear /// @return traits memory function bearTraits(uint256 tokenId) external view returns (IBear3Traits.Traits memory); /// Returns whether a Gen 2 Bear (TwoBitCubs) has breeded a Gen 3 TwoBitBear /// @dev Does not throw if the tokenId is not valid /// @param tokenId The token ID of the Gen 2 bear /// @return Returns whether the Gen 2 Bear has mated function hasGen2Mated(uint256 tokenId) external view returns (bool); /// Returns whether a Gen 3 Bear has produced a Gen 4 TwoBitBear /// @dev Throws if the token ID is not valid /// @param tokenId The token ID of the Gen 3 bear /// @return Returns whether the Gen 3 Bear has been used for Gen 4 minting function generation4Claimed(uint256 tokenId) external view returns (bool); /// Returns the scar colors of a given token Id /// @dev Throws if the token ID is not valid or if not revealed /// @param tokenId The token ID of the Gen 3 bear /// @return Returns the scar colors function scarColors(uint256 tokenId) external view returns (IBear3Traits.ScarColor[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Gen 3 TwoBitBear traits /// @notice Describes the traits of a Gen 3 TwoBitBear interface IBear3Traits { /// Represents the backgrounds of a Gen 3 TwoBitBear enum BackgroundType { White, Green, Blue } /// Represents the scars of a Gen 3 TwoBitBear enum ScarColor { None, Blue, Magenta, Gold } /// Represents the species of a Gen 3 TwoBitBear enum SpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a Gen 3 TwoBitBear enum MoodType { Happy, Hungry, Sleepy, Grumpy, Cheerful, Excited, Snuggly, Confused, Ravenous, Ferocious, Hangry, Drowsy, Cranky, Furious } /// Represents the traits of a Gen 3 TwoBitBear struct Traits { BackgroundType background; MoodType mood; SpeciesType species; bool gen4Claimed; uint8 nameIndex; uint8 familyIndex; uint16 firstParentTokenId; uint16 secondParentTokenId; uint176 genes; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Main Tech for Gen 3 TwoBitBear rendering /// @dev Supports the ERC-721 contract interface IBearRenderTech { /// Returns the text of a background based on the supplied type /// @param background The BackgroundType /// @return The background text function backgroundForType(IBear3Traits.BackgroundType background) external pure returns (string memory); /// Creates the SVG for a Gen 3 TwoBitBear given its IBear3Traits.Traits and Token Id /// @dev Passes rendering on to a specific species' IBearRenderer /// @param traits The Bear's traits structure /// @param tokenId The Bear's Token Id /// @return The raw xml as bytes function createSvg(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory); /// Returns the family of a Gen 3 TwoBitBear as a string /// @param traits The Bear's traits structure /// @return The family text function familyForTraits(IBear3Traits.Traits memory traits) external view returns (string memory); /// @dev Returns the ERC-721 for a Gen 3 TwoBitBear given its IBear3Traits.Traits and Token Id /// @param traits The Bear's traits structure /// @param tokenId The Bear's Token Id /// @return The raw json as bytes function metadata(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory); /// Returns the text of a mood based on the supplied type /// @param mood The MoodType /// @return The mood text function moodForType(IBear3Traits.MoodType mood) external pure returns (string memory); /// Returns the name of a Gen 3 TwoBitBear as a string /// @param traits The Bear's traits structure /// @return The name text function nameForTraits(IBear3Traits.Traits memory traits) external view returns (string memory); /// Returns the scar colors of a bear with the provided traits /// @param traits The Bear's traits structure /// @return The array of scar colors function scarsForTraits(IBear3Traits.Traits memory traits) external view returns (IBear3Traits.ScarColor[] memory); /// Returns the text of a scar based on the supplied color /// @param scarColor The ScarColor /// @return The scar color text function scarForType(IBear3Traits.ScarColor scarColor) external pure returns (string memory); /// Returns the text of a species based on the supplied type /// @param species The SpeciesType /// @return The species text function speciesForType(IBear3Traits.SpeciesType species) external pure returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Bear RenderTech provider /// @dev Provides IBearRenderTech to an IBearRenderer interface IBearRenderTechProvider { /// Represents a point substitution struct Substitution { uint matchingX; uint matchingY; uint replacementX; uint replacementY; } /// Generates an SVG <polygon> element based on a points array and fill color /// @param points The encoded points array /// @param fill The fill attribute /// @param substitutions An array of point substitutions /// @return A <polygon> element as bytes function dynamicPolygonElement(bytes memory points, bytes memory fill, Substitution[] memory substitutions) external view returns (bytes memory); /// Generates an SVG <linearGradient> element based on a points array and stop colors /// @param id The id of the linear gradient /// @param points The encoded points array /// @param stop1 The first stop attribute /// @param stop2 The second stop attribute /// @return A <linearGradient> element as bytes function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view returns (bytes memory); /// Generates an SVG <path> element based on a points array and fill color /// @param path The encoded path array /// @param fill The fill attribute /// @return A <path> segment as bytes function pathElement(bytes memory path, bytes memory fill) external view returns (bytes memory); /// Generates an SVG <polygon> segment based on a points array and fill colors /// @param points The encoded points array /// @param fill The fill attribute /// @return A <polygon> segment as bytes function polygonElement(bytes memory points, bytes memory fill) external view returns (bytes memory); /// Generates an SVG <rect> element based on a points array and fill color /// @param widthPercentage The width expressed as a percentage of its container /// @param heightPercentage The height expressed as a percentage of its container /// @param attributes Additional attributes for the <rect> element /// @return A <rect> element as bytes function rectElement(uint256 widthPercentage, uint256 heightPercentage, bytes memory attributes) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@theappstudio/solidity/contracts/interfaces/ISVGTypes.sol"; import "./IBear3Traits.sol"; import "./ICubTraits.sol"; /// @title Gen 3 TwoBitBear Renderer /// @dev Renders a specific species of a Gen 3 TwoBitBear interface IBearRenderer { /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param scars Zero, One, or Two ScarColors /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customDefs(uint176 genes, ISVGTypes.Color memory eyeColor, IBear3Traits.ScarColor[] memory scars, uint256 tokenId) external view returns (bytes memory); /// Influences the eye color given the dominant parent /// @param dominantParent The Dominant parent bear /// @return The eye color function customEyeColor(ICubTraits.TraitsV1 memory dominantParent) external view returns (ISVGTypes.Color memory); /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customSurfaces(uint176 genes, ISVGTypes.Color memory eyeColor, uint256 tokenId) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ICubTraits.sol"; /// @title TwoBitCubs NFT Interface for provided ICubTraits interface ICubTraitProvider{ /// Returns the family of a TwoBitCub as a string /// @param traits The traits of the Cub /// @return The family text function familyForTraits(ICubTraits.TraitsV1 memory traits) external pure returns (string memory); /// Returns the text of a mood based on the supplied type /// @param moodType The CubMoodType /// @return The mood text function moodForType(ICubTraits.CubMoodType moodType) external pure returns (string memory); /// Returns the mood of a TwoBitCub based on its TwoBitBear parents /// @param firstParentTokenId The ID of the token that represents the first parent /// @param secondParentTokenId The ID of the token that represents the second parent /// @return The mood type function moodFromParents(uint256 firstParentTokenId, uint256 secondParentTokenId) external view returns (ICubTraits.CubMoodType); /// Returns the name of a TwoBitCub as a string /// @param traits The traits of the Cub /// @return The name text function nameForTraits(ICubTraits.TraitsV1 memory traits) external pure returns (string memory); /// Returns the text of a species based on the supplied type /// @param speciesType The CubSpeciesType /// @return The species text function speciesForType(ICubTraits.CubSpeciesType speciesType) external pure returns (string memory); /// Returns the v1 traits associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Cub /// @return traits memory function traitsV1(uint256 tokenId) external view returns (ICubTraits.TraitsV1 memory traits); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@theappstudio/solidity/contracts/interfaces/ISVGTypes.sol"; /// @title ICubTraits interface interface ICubTraits { /// Represents the species of a TwoBitCub enum CubSpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a TwoBitCub enum CubMoodType { Happy, Hungry, Sleepy, Grumpy, Cheerful, Excited, Snuggly, Confused, Ravenous, Ferocious, Hangry, Drowsy, Cranky, Furious } /// Represents the DNA for a TwoBitCub /// @dev organized to fit within 256 bits and consume the least amount of resources struct DNA { uint16 firstParentTokenId; uint16 secondParentTokenId; uint224 genes; } /// Represents the v1 traits of a TwoBitCub struct TraitsV1 { uint256 age; ISVGTypes.Color topColor; ISVGTypes.Color bottomColor; uint8 nameIndex; uint8 familyIndex; CubMoodType mood; CubSpeciesType species; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@theappstudio/solidity/contracts/utils/OnChain.sol"; import "@theappstudio/solidity/contracts/utils/Randomization.sol"; import "../interfaces/IBear3TraitProvider.sol"; import "../interfaces/ICubTraitProvider.sol"; import "../utils/BearRenderTech.sol"; import "../utils/TwoBitBears3Errors.sol"; import "./TwoBitCubs.sol"; /// @title TwoBitBears3 contract TwoBitBears3 is ERC721, IBear3TraitProvider, IERC721Enumerable, Ownable { /// @dev Reference to the BearRenderTech contract IBearRenderTech private immutable _bearRenderTech; /// @dev Stores the cubs Adult Age so that it doesn't need to be queried for every mint uint256 private immutable _cubAdultAge; /// @dev Precalculated eligibility for cubs uint256[] private _cubEligibility; /// @dev Stores bear token ids that have already minted gen 4 mapping(uint256 => bool) private _generation4Claims; /// @dev The contract for Gen 4 address private _gen4Contract; /// @dev Stores cub token ids that have already mated mapping(uint256 => bool) private _matedCubs; /// @dev Seed for randomness uint256 private _seed; /// @dev Array of TokenIds to DNA uint256[] private _tokenIdsToDNA; /// @dev Reference to the TwoBitCubs contract TwoBitCubs private immutable _twoBitCubs; /// Look...at these...Bears constructor(uint256 seed, address renderTech, address twoBitCubs) ERC721("TwoBitBears3", "TB3") { _seed = seed; _bearRenderTech = IBearRenderTech(renderTech); _twoBitCubs = TwoBitCubs(twoBitCubs); _cubAdultAge = _twoBitCubs.ADULT_AGE(); } /// Applies calculated slots of gen 2 eligibility to reduce gas function applySlots(uint256[] calldata slotIndices, uint256[] calldata slotValues) external onlyOwner { for (uint i = 0; i < slotIndices.length; i++) { uint slotIndex = slotIndices[i]; uint slotValue = slotValues[i]; if (slotIndex >= _cubEligibility.length) { while (slotIndex > _cubEligibility.length) { _cubEligibility.push(0); } _cubEligibility.push(slotValue); } else if (_cubEligibility[slotIndex] != slotValue) { _cubEligibility[slotIndex] = slotValue; } } } /// Assigns the Gen 4 contract address for message caller verification function assignGen4(address gen4Contract) external onlyOwner { if (gen4Contract == address(0)) revert InvalidAddress(); _gen4Contract = gen4Contract; } /// @inheritdoc IBear3TraitProvider function bearTraits(uint256 tokenId) external view onlyWhenExists(tokenId) returns (IBear3Traits.Traits memory) { return _traitsForToken(tokenId); } /// Calculates the current values for a slot function calculateSlot(uint256 slotIndex, uint256 totalTokens) external view onlyOwner returns (uint256 slotValue) { uint tokenStart = slotIndex * 32; uint tokenId = tokenStart + 32; if (tokenId > totalTokens) { tokenId = totalTokens; } uint adults = 0; do { tokenId -= 1; slotValue = (slotValue << 8) | _getEligibility(tokenId); if (slotValue >= 0x80) { adults++; } } while (tokenId > tokenStart); if (adults == 0 || (slotIndex < _cubEligibility.length && slotValue == _cubEligibility[slotIndex])) { slotValue = 0; // Reset because there's nothing worth writing } } /// Marks the Gen 3 Bear as having minted a Gen 4 Bear function claimGen4(uint256 tokenId) external onlyWhenExists(tokenId) { if (_gen4Contract == address(0) || _msgSender() != _gen4Contract) revert InvalidCaller(); _generation4Claims[tokenId] = true; } /// @notice For easy import into MetaMask function decimals() external pure returns (uint256) { return 0; } /// @inheritdoc IBear3TraitProvider function hasGen2Mated(uint256 tokenId) external view returns (bool) { return _matedCubs[tokenId]; } /// @inheritdoc IBear3TraitProvider function generation4Claimed(uint256 tokenId) external view onlyWhenExists(tokenId) returns (bool) { return _generation4Claims[tokenId]; } function slotParameters() external view onlyOwner returns (uint256 totalSlots, uint256 totalTokens) { totalTokens = _twoBitCubs.totalSupply(); totalSlots = 1 + totalTokens / 32; } /// Exposes the raw image SVG to the world, for any applications that can take advantage function imageSVG(uint256 tokenId) external view returns (string memory) { return string(_imageBytes(tokenId)); } /// Exposes the image URI to the world, for any applications that can take advantage function imageURI(uint256 tokenId) external view returns (string memory) { return string(OnChain.svgImageURI(_imageBytes(tokenId))); } /// Mints the provided quantity of TwoBitBear3 tokens /// @param parentOne The first gen 2 bear parent, which also determines the mood /// @param parentTwo The second gen 2 bear parent function mateBears(uint256 parentOne, uint256 parentTwo) external { // Check eligibility if (_matedCubs[parentOne]) revert ParentAlreadyMated(parentOne); if (_matedCubs[parentTwo]) revert ParentAlreadyMated(parentTwo); if (_twoBitCubs.ownerOf(parentOne) != _msgSender()) revert ParentNotOwned(parentOne); if (_twoBitCubs.ownerOf(parentTwo) != _msgSender()) revert ParentNotOwned(parentTwo); uint parentOneInfo = _getEligibility(parentOne); uint parentTwoInfo = _getEligibility(parentTwo); uint parentOneSpecies = parentOneInfo & 0x03; if (parentOne == parentTwo || parentOneSpecies != (parentTwoInfo & 0x03)) revert InvalidParentCombination(); if (parentOneInfo < 0x80) revert ParentTooYoung(parentOne); if (parentTwoInfo < 0x80) revert ParentTooYoung(parentTwo); // Prepare mint _matedCubs[parentOne] = true; _matedCubs[parentTwo] = true; uint seed = Randomization.randomSeed(_seed); // seed (208) | parent one (16) | parent two (16) | species (8) | mood (8) uint rawDna = (seed << 48) | (parentOne << 32) | (parentTwo << 16) | (parentOneSpecies << 8) | ((parentOneInfo & 0x7F) >> 2); uint tokenId = _tokenIdsToDNA.length; _tokenIdsToDNA.push(rawDna); _seed = seed; _safeMint(_msgSender(), tokenId, ""); // Reentrancy is possible here } /// @notice Returns expected gas usage based on selected parents, with a small buffer for safety /// @dev Does not check for ownership or whether parents have already mated function matingGas(address minter, uint256 parentOne, uint256 parentTwo) external view returns (uint256 result) { result = 146000; // Lowest gas cost to mint if (_tokenIdsToDNA.length == 0) { result += 16500; } if (balanceOf(minter) == 0) { result += 17500; } // Fetching eligibility of parents will cost additional gas uint fetchCount = 0; if (_eligibility(parentOne) < 0x80) { result += 47000; if (uint(_twoBitCubs.traitsV1(parentOne).mood) >= 4) { result += 33500; } fetchCount += 1; } if (_eligibility(parentTwo) < 0x80) { result += 47000; if (uint(_twoBitCubs.traitsV1(parentTwo).mood) >= 4) { result += 33500; } fetchCount += 1; } // There's some overhead for a single fetch if (fetchCount == 1) { result += 10000; } } /// Prevents a function from executing if the tokenId does not exist modifier onlyWhenExists(uint256 tokenId) { if (!_exists(tokenId)) revert InvalidTokenId(); _; } /// @inheritdoc IBear3TraitProvider function scarColors(uint256 tokenId) external view onlyWhenExists(tokenId) returns (IBear3Traits.ScarColor[] memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return _bearRenderTech.scarsForTraits(traits); } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IERC721Enumerable function tokenByIndex(uint256 index) external view returns (uint256) { require(index < this.totalSupply(), "global index out of bounds"); return index; // Burning is not exposed by this contract so we can simply return the index } /// @inheritdoc IERC721Enumerable /// @dev This implementation is for the benefit of web3 sites -- it is extremely expensive for contracts to call on-chain function tokenOfOwnerByIndex(address owner_, uint256 index) external view returns (uint256 tokenId) { require(index < ERC721.balanceOf(owner_), "owner index out of bounds"); for (uint tokenIndex = 0; tokenIndex < _tokenIdsToDNA.length; tokenIndex++) { // Use _exists() to avoid a possible revert when accessing OpenZeppelin's ownerOf(), despite not exposing _burn() if (_exists(tokenIndex) && ownerOf(tokenIndex) == owner_) { if (index == 0) { tokenId = tokenIndex; break; } index--; } } } /// @inheritdoc IERC721Metadata function tokenURI(uint256 tokenId) public view override onlyWhenExists(tokenId) returns (string memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return string(OnChain.tokenURI(_bearRenderTech.metadata(traits, tokenId))); } /// @inheritdoc IERC721Enumerable function totalSupply() external view returns (uint256) { return _tokenIdsToDNA.length; // We don't expose _burn() so the .length suffices } function _eligibility(uint256 parent) private view returns (uint8 result) { uint slotIndex = parent / 32; if (slotIndex < _cubEligibility.length) { result = uint8(_cubEligibility[slotIndex] >> ((parent % 32) * 8)); } } function _getEligibility(uint256 parent) private view returns (uint8 result) { // Check the precalculated eligibility result = _eligibility(parent); if (result < 0x80) { // We need to go get the latest information from the Cubs contract result = _packedInfo(_twoBitCubs.traitsV1(parent)); } } function _imageBytes(uint256 tokenId) private view onlyWhenExists(tokenId) returns (bytes memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return _bearRenderTech.createSvg(traits, tokenId); } function _traitsForToken(uint256 tokenId) private view returns (IBear3Traits.Traits memory traits) { uint dna = _tokenIdsToDNA[tokenId]; traits.mood = IBear3Traits.MoodType(dna & 0xFF); traits.species = IBear3Traits.SpeciesType((dna >> 8) & 0xFF); traits.firstParentTokenId = uint16(dna >> 16) & 0xFFFF; traits.secondParentTokenId = uint16(dna >> 32) & 0xFFFF; traits.nameIndex = uint8((dna >> 48) & 0xFF); traits.familyIndex = uint8((dna >> 56) & 0xFF); traits.background = IBear3Traits.BackgroundType(((dna >> 64) & 0xFF) % 3); traits.gen4Claimed = _generation4Claims[tokenId]; traits.genes = uint176(dna >> 80); } function _packedInfo(ICubTraits.TraitsV1 memory traits) private view returns (uint8 info) { info |= uint8(traits.species); info |= uint8(traits.mood) << 2; if (traits.age >= _cubAdultAge) { info |= 0x80; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../interfaces/ICubTraitProvider.sol"; /// @title TwoBitCubs abstract contract TwoBitCubs is IERC721Enumerable, ICubTraitProvider { /// @dev The number of blocks until a growing cub becomes an adult (roughly 1 week) uint256 public constant ADULT_AGE = 44000; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@theappstudio/solidity/contracts/utils/DecimalStrings.sol"; import "@theappstudio/solidity/contracts/utils/OnChain.sol"; import "@theappstudio/solidity/contracts/utils/Randomization.sol"; import "@theappstudio/solidity/contracts/utils/SVG.sol"; import "./BearRenderTechErrors.sol"; import "../interfaces/ICubTraits.sol"; import "../interfaces/IBear3Traits.sol"; import "../interfaces/IBearRenderer.sol"; import "../interfaces/IBearRenderTech.sol"; import "../interfaces/IBearRenderTechProvider.sol"; import "../tokens/TwoBitCubs.sol"; /// @title BearRendering3 contract BearRenderTech is Ownable, IBearRenderTech, IBearRenderTechProvider { using Strings for uint256; using DecimalStrings for uint256; /// Represents an encoding of a number struct NumberEncoding { uint8 bytesPerPoint; uint8 decimals; bool signed; } /// @dev The Black Bear SVG renderer IBearRenderer private _blackBearRenderer; /// @dev The Brown Bear SVG renderer IBearRenderer private _brownBearRenderer; /// @dev The Panda Bear SVG renderer IBearRenderer private _pandaBearRenderer; /// @dev The Polar Bear SVG renderer IBearRenderer private _polarBearRenderer; /// @dev Reference to the TwoBitCubs contract TwoBitCubs private immutable _twoBitCubs; /// @dev Controls the reveal bool private _wenReveal; /// Look...at these...Bears constructor(address twoBitCubs) { _twoBitCubs = TwoBitCubs(twoBitCubs); } /// Applies the four IBearRenderers /// @param blackRenderer The Black Bear renderer /// @param brownRenderer The Brown Bear renderer /// @param pandaRenderer The Panda Bear renderer /// @param polarRenderer The Polar Bear renderer function applyRenderers(address blackRenderer, address brownRenderer, address pandaRenderer, address polarRenderer) external onlyOwner { if (address(_blackBearRenderer) != address(0) || address(_brownBearRenderer) != address(0) || address(_pandaBearRenderer) != address(0) || address(_polarBearRenderer) != address(0)) revert AlreadyConfigured(); _blackBearRenderer = IBearRenderer(blackRenderer); _brownBearRenderer = IBearRenderer(brownRenderer); _pandaBearRenderer = IBearRenderer(pandaRenderer); _polarBearRenderer = IBearRenderer(polarRenderer); } function backgroundForType(IBear3Traits.BackgroundType background) public pure returns (string memory) { string[3] memory backgrounds = ["White Tundra", "Green Forest", "Blue Shore"]; return backgrounds[uint(background)]; } /// @inheritdoc IBearRenderTech function createSvg(IBear3Traits.Traits memory traits, uint256 tokenId) public view onlyWenRevealed returns (bytes memory) { IBearRenderer renderer = _rendererForTraits(traits); ISVGTypes.Color memory eyeColor = renderer.customEyeColor(_twoBitCubs.traitsV1(traits.firstParentTokenId)); return SVG.createElement("svg", SVG.svgAttributes(447, 447), abi.encodePacked( _defs(renderer, traits, eyeColor, tokenId), this.rectElement(100, 100, " fill='url(#background)'"), this.pathElement(hex'224d76126b084c81747bfb4381f57cdd821c7de981df7ee74381a37fe5810880c2802f81514c5b3b99a8435a359a5459049aaf57cc9ab0569ab04356939ab055619a55545b99a94c2f678151432e8e80c22df37fe52db77ee7432d7b7de92da17cdd2e227bfb4c39846b0a4c57ca6b0a566b084c76126b085a', "url(#chest)"), this.polygonElement(hex'1207160d0408bc0da20a620d040c0a0a9b08bc0a9b056e0a9b', "url(#neck)"), renderer.customSurfaces(traits.genes, eyeColor, tokenId) )); } /// @inheritdoc IBearRenderTechProvider function dynamicPolygonElement(bytes memory points, bytes memory fill, Substitution[] memory substitutions) external view onlyRenderer returns (bytes memory) { return SVG.createElement("polygon", abi.encodePacked(" points='", _polygonPoints(points, substitutions), "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTech function familyForTraits(IBear3Traits.Traits memory traits) public view override onlyWenRevealed returns (string memory) { string[18] memory families = ["Hirst", "Stark", "xCopy", "Watkinson", "Davis", "Evan Dennis", "Anderson", "Pak", "Greenawalt", "Capacity", "Hobbs", "Deafbeef", "Rainaud", "Snowfro", "Winkelmann", "Fairey", "Nines", "Maeda"]; return families[(uint(uint8(bytes22(traits.genes)[1])) + uint(traits.familyIndex)) % 18]; } /// @inheritdoc IBearRenderTechProvider function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view onlyRenderer returns (bytes memory) { string memory stop = "stop"; NumberEncoding memory encoding = _readEncoding(points); bytes memory attributes = abi.encodePacked( " id='", id, "' x1='", _decimalStringFromBytes(points, 1, encoding), "' x2='", _decimalStringFromBytes(points, 1 + encoding.bytesPerPoint, encoding), "' y1='", _decimalStringFromBytes(points, 1 + 2 * encoding.bytesPerPoint, encoding), "' y2='", _decimalStringFromBytes(points, 1 + 3 * encoding.bytesPerPoint, encoding), "'" ); return SVG.createElement("linearGradient", attributes, abi.encodePacked( SVG.createElement(stop, stop1, ""), SVG.createElement(stop, stop2, "") )); } /// @inheritdoc IBearRenderTech function metadata(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory) { string memory token = tokenId.toString(); if (_wenReveal) { return OnChain.dictionary(OnChain.commaSeparated( OnChain.keyValueString("name", abi.encodePacked(nameForTraits(traits), " ", familyForTraits(traits), " the ", moodForType(traits.mood), " ", speciesForType(traits.species), " Bear ", token)), OnChain.keyValueArray("attributes", _attributesFromTraits(traits)), OnChain.keyValueString("image", OnChain.svgImageURI(bytes(createSvg(traits, tokenId)))) )); } return OnChain.dictionary(OnChain.commaSeparated( OnChain.keyValueString("name", abi.encodePacked("Rendering Bear ", token)), OnChain.keyValueString("image", "ipfs://QmUZ3ojSLv3rbu8egkS5brb4ETkNXXmcgCFG66HeFBXn54") )); } /// @inheritdoc IBearRenderTech function moodForType(IBear3Traits.MoodType mood) public pure override returns (string memory) { string[14] memory moods = ["Happy", "Hungry", "Sleepy", "Grumpy", "Cheerful", "Excited", "Snuggly", "Confused", "Ravenous", "Ferocious", "Hangry", "Drowsy", "Cranky", "Furious"]; return moods[uint256(mood)]; } /// @inheritdoc IBearRenderTech function nameForTraits(IBear3Traits.Traits memory traits) public view override onlyWenRevealed returns (string memory) { string[50] memory names = ["Cophi", "Trace", "Abel", "Ekko", "Goomba", "Milk", "Arth", "Roeleman", "Adjudicator", "Kelly", "Tropo", "Type3", "Jak", "Srsly", "Triggity", "SNR", "Drogate", "Scott", "Timm", "Nutsaw", "Rugged", "Vaypor", "XeR0", "Toasty", "BN3", "Dunks", "JFH", "Eallen", "Aspen", "Krueger", "Nouside", "Fonky", "Ian", "Metal", "Bones", "Cruz", "Daniel", "Buz", "Bliargh", "Strada", "Lanky", "Westwood", "Rie", "Moon", "Mango", "Hammer", "Pizza", "Java", "Gremlin", "Hash"]; return names[(uint(uint8(bytes22(traits.genes)[0])) + uint(traits.nameIndex)) % 50]; } /// Prevents a function from executing if not called by an authorized party modifier onlyRenderer() { if (_msgSender() != address(_blackBearRenderer) && _msgSender() != address(_brownBearRenderer) && _msgSender() != address(_pandaBearRenderer) && _msgSender() != address(_polarBearRenderer) && _msgSender() != address(this)) revert OnlyRenderer(); _; } /// Prevents a function from executing until wenReveal is set modifier onlyWenRevealed() { if (!_wenReveal) revert NotYetRevealed(); _; } /// @inheritdoc IBearRenderTechProvider function pathElement(bytes memory path, bytes memory fill) external view onlyRenderer returns (bytes memory result) { NumberEncoding memory encoding = _readEncoding(path); bytes memory attributes = " d='"; uint index = 1; while (index < path.length) { bytes1 control = path[index++]; attributes = abi.encodePacked(attributes, control); if (control == "C") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 6, index)); index += 6 * encoding.bytesPerPoint; } else if (control == "H") { // Not used by any IBearRenderers anymore attributes = abi.encodePacked(attributes, _readNext(path, encoding, 1, index)); index += encoding.bytesPerPoint; } else if (control == "L") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 2, index)); index += 2 * encoding.bytesPerPoint; } else if (control == "M") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 2, index)); index += 2 * encoding.bytesPerPoint; } else if (control == "V") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 1, index)); index += encoding.bytesPerPoint; } } return SVG.createElement("path", abi.encodePacked(attributes, "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTechProvider function polygonElement(bytes memory points, bytes memory fill) external view onlyRenderer returns (bytes memory) { return SVG.createElement("polygon", abi.encodePacked(" points='", _polygonPoints(points, new Substitution[](0)), "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTechProvider function rectElement(uint256 widthPercentage, uint256 heightPercentage, bytes memory attributes) external view onlyRenderer returns (bytes memory) { return abi.encodePacked("<rect width='", widthPercentage.toString(), "%' height='", heightPercentage.toString(), "%'", attributes, "/>"); } /// Wen the world is ready /// @dev Only the contract owner can invoke this function revealBears() external onlyOwner { _wenReveal = true; } /// @inheritdoc IBearRenderTech function scarsForTraits(IBear3Traits.Traits memory traits) public view onlyWenRevealed returns (IBear3Traits.ScarColor[] memory) { bytes22 geneBytes = bytes22(traits.genes); uint8 scarCountProvider = uint8(geneBytes[18]); uint scarCount = Randomization.randomIndex(scarCountProvider, _scarCountPercentages()); IBear3Traits.ScarColor[] memory scars = new IBear3Traits.ScarColor[](scarCount == 0 ? 1 : scarCount); if (scarCount == 0) { scars[0] = IBear3Traits.ScarColor.None; } else { uint8 scarColorProvider = uint8(geneBytes[17]); uint scarColor = Randomization.randomIndex(scarColorProvider, _scarColorPercentages()); for (uint scar = 0; scar < scarCount; scar++) { scars[scar] = IBear3Traits.ScarColor(scarColor+1); } } return scars; } /// @inheritdoc IBearRenderTech function scarForType(IBear3Traits.ScarColor scarColor) public pure override returns (string memory) { string[4] memory scarColors = ["None", "Blue", "Magenta", "Gold"]; return scarColors[uint256(scarColor)]; } /// @inheritdoc IBearRenderTech function speciesForType(IBear3Traits.SpeciesType species) public pure override returns (string memory) { string[4] memory specieses = ["Brown", "Black", "Polar", "Panda"]; return specieses[uint256(species)]; } function _attributesFromTraits(IBear3Traits.Traits memory traits) private view returns (bytes memory) { bytes memory attributes = OnChain.commaSeparated( OnChain.traitAttribute("Species", bytes(speciesForType(traits.species))), OnChain.traitAttribute("Mood", bytes(moodForType(traits.mood))), OnChain.traitAttribute("Background", bytes(backgroundForType(traits.background))), OnChain.traitAttribute("First Name", bytes(nameForTraits(traits))), OnChain.traitAttribute("Last Name (Gen 4 Scene)", bytes(familyForTraits(traits))), OnChain.traitAttribute("Parents", abi.encodePacked("#", uint(traits.firstParentTokenId).toString(), " & #", uint(traits.secondParentTokenId).toString())) ); bytes memory scarAttributes = OnChain.traitAttribute("Scars", _scarDescription(scarsForTraits(traits))); attributes = abi.encodePacked(attributes, OnChain.continuesWith(scarAttributes)); bytes memory gen4Attributes = OnChain.traitAttribute("Gen 4 Claim Status", bytes(traits.gen4Claimed ? "Claimed" : "Unclaimed")); return abi.encodePacked(attributes, OnChain.continuesWith(gen4Attributes)); } function _decimalStringFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding) private pure returns (bytes memory) { (uint value, bool isNegative) = _uintFromBytes(encoded, startIndex, encoding); return value.toDecimalString(encoding.decimals, isNegative); } function _defs(IBearRenderer renderer, IBear3Traits.Traits memory traits, ISVGTypes.Color memory eyeColor, uint256 tokenId) private view returns (bytes memory) { string[3] memory firstStop = ["#fff", "#F3FCEE", "#EAF4F9"]; string[3] memory lastStop = ["#9C9C9C", "#A6B39E", "#98ADB5"]; return SVG.createElement("defs", "", abi.encodePacked( this.linearGradient("background", hex'32000003ea000003e6', abi.encodePacked(" offset='0.44521' stop-color='", firstStop[uint(traits.background)], "'"), abi.encodePacked(" offset='0.986697' stop-color='", lastStop[uint(traits.background)], "'") ), renderer.customDefs(traits.genes, eyeColor, scarsForTraits(traits), tokenId) )); } function _polygonCoordinateFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding, Substitution[] memory substitutions) private pure returns (bytes memory) { (uint x, bool xIsNegative) = _uintFromBytes(encoded, startIndex, encoding); (uint y, bool yIsNegative) = _uintFromBytes(encoded, startIndex + encoding.bytesPerPoint, encoding); for (uint index = 0; index < substitutions.length; index++) { if (x == substitutions[index].matchingX && y == substitutions[index].matchingY) { x = substitutions[index].replacementX; y = substitutions[index].replacementY; break; } } return OnChain.commaSeparated(x.toDecimalString(encoding.decimals, xIsNegative), y.toDecimalString(encoding.decimals, yIsNegative)); } function _polygonPoints(bytes memory points, Substitution[] memory substitutions) private pure returns (bytes memory pointsValue) { NumberEncoding memory encoding = _readEncoding(points); pointsValue = abi.encodePacked(_polygonCoordinateFromBytes(points, 1, encoding, substitutions)); uint bytesPerIteration = encoding.bytesPerPoint << 1; // Double because this method processes 2 points at a time for (uint byteIndex = 1 + bytesPerIteration; byteIndex < points.length; byteIndex += bytesPerIteration) { pointsValue = abi.encodePacked(pointsValue, " ", _polygonCoordinateFromBytes(points, byteIndex, encoding, substitutions)); } } function _readEncoding(bytes memory encoded) private pure returns (NumberEncoding memory encoding) { encoding.decimals = uint8(encoded[0] >> 4) & 0xF; encoding.bytesPerPoint = uint8(encoded[0]) & 0x7; encoding.signed = uint8(encoded[0]) & 0x8 == 0x8; } function _readNext(bytes memory encoded, NumberEncoding memory encoding, uint numbers, uint startIndex) private pure returns (bytes memory result) { result = _decimalStringFromBytes(encoded, startIndex, encoding); for (uint index = startIndex + encoding.bytesPerPoint; index < startIndex + (numbers * encoding.bytesPerPoint); index += encoding.bytesPerPoint) { result = abi.encodePacked(result, " ", _decimalStringFromBytes(encoded, index, encoding)); } } function _rendererForTraits(IBear3Traits.Traits memory traits) private view returns (IBearRenderer) { if (traits.species == IBear3Traits.SpeciesType.Black) { return _blackBearRenderer; } else if (traits.species == IBear3Traits.SpeciesType.Brown) { return _brownBearRenderer; } else if (traits.species == IBear3Traits.SpeciesType.Panda) { return _pandaBearRenderer; } else /* if (traits.species == IBear3Traits.SpeciesType.Polar) */ { return _polarBearRenderer; } } function _scarColorPercentages() private pure returns (uint8[] memory percentages) { uint8[] memory array = new uint8[](2); array[0] = 60; // 60% Blue array[1] = 30; // 30% Magenta return array; // 10% Gold } function _scarCountPercentages() private pure returns (uint8[] memory percentages) { uint8[] memory array = new uint8[](2); array[0] = 70; // 70% None array[1] = 20; // 20% One return array; // 10% Two } function _scarDescription(IBear3Traits.ScarColor[] memory scarColors) private pure returns (bytes memory) { if (scarColors.length == 0 || scarColors[0] == IBear3Traits.ScarColor.None) { return bytes(scarForType(IBear3Traits.ScarColor.None)); } else { return abi.encodePacked(scarColors.length.toString(), " ", scarForType(scarColors[0])); } } function _uintFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding) private pure returns (uint result, bool isNegative) { result = uint8(encoded[startIndex]); if (encoding.signed) { isNegative = result & 0x80 == 0x80; result &= 0x7F; } uint stopIndex = startIndex + encoding.bytesPerPoint; for (uint index = startIndex + 1; index < stopIndex; index++) { result = (result << 8) + uint(uint8(encoded[index])); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the renderers are already configured error AlreadyConfigured(); /// @dev When Reveal is false error NotYetRevealed(); /// @dev Only the Renderer can make these calls error OnlyRenderer(); // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev The address passed in is not allowed error InvalidAddress(); /// @dev The caller of the method is not allowed error InvalidCaller(); /// @dev When the parent identifiers are not unique or not of the same species error InvalidParentCombination(); /// @dev When the TwoBitBear3 tokenId does not exist error InvalidTokenId(); /// @dev When the parent has already mated error ParentAlreadyMated(uint256 tokenId); /// @dev When the parent is not owned by the caller error ParentNotOwned(uint256 tokenId); /// @dev When the parent is not yet an adult error ParentTooYoung(uint256 tokenId);
Prevents a function from executing if not called by an authorized party
modifier onlyRenderer() { if (_msgSender() != address(_blackBearRenderer) && _msgSender() != address(_brownBearRenderer) && _msgSender() != address(_pandaBearRenderer) && _msgSender() != address(_polarBearRenderer) && _msgSender() != address(this)) revert OnlyRenderer(); _; }
1,010,341
[ 1, 25828, 87, 279, 445, 628, 11274, 309, 486, 2566, 635, 392, 10799, 18285, 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, 9606, 1338, 6747, 1435, 288, 203, 3639, 309, 261, 67, 3576, 12021, 1435, 480, 1758, 24899, 11223, 1919, 297, 6747, 13, 597, 203, 5411, 389, 3576, 12021, 1435, 480, 1758, 24899, 70, 26253, 1919, 297, 6747, 13, 597, 203, 5411, 389, 3576, 12021, 1435, 480, 1758, 24899, 84, 464, 69, 1919, 297, 6747, 13, 597, 203, 5411, 389, 3576, 12021, 1435, 480, 1758, 24899, 3915, 297, 1919, 297, 6747, 13, 597, 203, 5411, 389, 3576, 12021, 1435, 480, 1758, 12, 2211, 3719, 15226, 5098, 6747, 5621, 203, 3639, 389, 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 ]
./full_match/5/0xd5f676d542140DDA5eeD33575CecAEff2050583D/sources/@aave/periphery-v3/contracts/misc/WrappedTokenGatewayV3.sol
* @dev withdraws the WETH _reserves of msg.sender. @param amount amount of aWETH to withdraw and receive native ETH @param to address of the user who will receive native ETH @param deadline validity deadline of permit and so depositWithPermit signature @param permitV V parameter of ERC712 permit sig @param permitR R parameter of ERC712 permit sig @param permitS S parameter of ERC712 permit sig/ if amount is equal to type(uint256).max, the user wants to redeem everything
function withdrawETHWithPermit( address, uint256 amount, address to, uint256 deadline, uint8 permitV, bytes32 permitR, bytes32 permitS ) external override { IAToken aWETH = IAToken(POOL.getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); POOL.withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); }
7,054,526
[ 1, 1918, 9446, 87, 326, 678, 1584, 44, 389, 455, 264, 3324, 434, 1234, 18, 15330, 18, 225, 3844, 3844, 434, 279, 59, 1584, 44, 358, 598, 9446, 471, 6798, 6448, 512, 2455, 225, 358, 1758, 434, 326, 729, 10354, 903, 6798, 6448, 512, 2455, 225, 14096, 13800, 14096, 434, 21447, 471, 1427, 443, 1724, 1190, 9123, 305, 3372, 225, 21447, 58, 776, 1569, 434, 4232, 39, 27, 2138, 21447, 3553, 225, 21447, 54, 534, 1569, 434, 4232, 39, 27, 2138, 21447, 3553, 225, 21447, 55, 348, 1569, 434, 4232, 39, 27, 2138, 21447, 3553, 19, 309, 3844, 353, 3959, 358, 618, 12, 11890, 5034, 2934, 1896, 16, 326, 729, 14805, 358, 283, 24903, 7756, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 598, 9446, 1584, 44, 1190, 9123, 305, 12, 203, 565, 1758, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 14096, 16, 203, 565, 2254, 28, 21447, 58, 16, 203, 565, 1731, 1578, 21447, 54, 16, 203, 565, 1731, 1578, 21447, 55, 203, 225, 262, 3903, 3849, 288, 203, 565, 467, 789, 969, 279, 59, 1584, 44, 273, 467, 789, 969, 12, 20339, 18, 588, 607, 6527, 751, 12, 2867, 12, 59, 1584, 44, 13, 2934, 69, 1345, 1887, 1769, 203, 565, 2254, 5034, 729, 13937, 273, 279, 59, 1584, 44, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 565, 2254, 5034, 3844, 774, 1190, 9446, 273, 3844, 31, 203, 203, 565, 309, 261, 8949, 422, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 1377, 3844, 774, 1190, 9446, 273, 729, 13937, 31, 203, 565, 289, 203, 565, 279, 59, 1584, 44, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 774, 1190, 9446, 1769, 203, 565, 13803, 1741, 18, 1918, 9446, 12, 2867, 12, 59, 1584, 44, 3631, 3844, 774, 1190, 9446, 16, 1758, 12, 2211, 10019, 203, 565, 678, 1584, 44, 18, 1918, 9446, 12, 8949, 774, 1190, 9446, 1769, 203, 565, 389, 4626, 5912, 1584, 44, 12, 869, 16, 3844, 774, 1190, 9446, 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 ]
./partial_match/1/0xc9268c7F59850B26567b0f5d3Dcc317cEDC43490/sources/src/contracts/SlippageAuction.sol
@notice The ```stopAuction``` function ends the auction @dev Only callable by the auction owner @return _buyProceeds Amount of buyToken obtained from the auction @return _unsoldRemaining Amount of unsold sellTokens left over Get the auction info and perform checks Set Return params Effects: Update state with final balances; Return buyToken proceeds from the auction to the sender Return any unsold sellToken to the sender
function stopAuction() public nonReentrant returns (uint256 _buyProceeds, uint256 _unsoldRemaining) { _requireSenderIsTimelock(); uint256 _auctionNumber = auctions.length - 1; Auction memory _auction = auctions[_auctionNumber]; if (_auction.ended) revert AuctionAlreadyExited(); _auction.ended = true; _auction.buyTokenProceeds = uint128(_buyProceeds); _auction.amountLeft = uint128(_unsoldRemaining); auctions[_auctionNumber] = _auction; }
15,952,507
[ 1, 1986, 31621, 5681, 37, 4062, 10335, 68, 445, 3930, 326, 279, 4062, 225, 5098, 4140, 635, 326, 279, 4062, 3410, 327, 389, 70, 9835, 626, 5288, 87, 16811, 434, 30143, 1345, 12700, 628, 326, 279, 4062, 327, 389, 27595, 1673, 11429, 16811, 434, 16804, 1673, 357, 80, 5157, 2002, 1879, 968, 326, 279, 4062, 1123, 471, 3073, 4271, 1000, 2000, 859, 30755, 87, 30, 2315, 919, 598, 727, 324, 26488, 31, 2000, 30143, 1345, 11247, 87, 628, 326, 279, 4062, 358, 326, 5793, 2000, 1281, 16804, 1673, 357, 80, 1345, 358, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 2132, 37, 4062, 1435, 1071, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 389, 70, 9835, 626, 5288, 87, 16, 2254, 5034, 389, 27595, 1673, 11429, 13, 288, 203, 3639, 389, 6528, 12021, 2520, 10178, 292, 975, 5621, 203, 203, 3639, 2254, 5034, 389, 69, 4062, 1854, 273, 279, 4062, 87, 18, 2469, 300, 404, 31, 203, 3639, 432, 4062, 3778, 389, 69, 4062, 273, 279, 4062, 87, 63, 67, 69, 4062, 1854, 15533, 203, 3639, 309, 261, 67, 69, 4062, 18, 3934, 13, 15226, 432, 4062, 9430, 6767, 329, 5621, 203, 203, 203, 3639, 389, 69, 4062, 18, 3934, 273, 638, 31, 203, 3639, 389, 69, 4062, 18, 70, 9835, 1345, 626, 5288, 87, 273, 2254, 10392, 24899, 70, 9835, 626, 5288, 87, 1769, 203, 3639, 389, 69, 4062, 18, 8949, 3910, 273, 2254, 10392, 24899, 27595, 1673, 11429, 1769, 203, 203, 3639, 279, 4062, 87, 63, 67, 69, 4062, 1854, 65, 273, 389, 69, 4062, 31, 203, 203, 203, 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 ]
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(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].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(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 APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
event APPROVAL665(address indexed owner, address indexed spender, uint value);
2,554,119
[ 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, 871, 14410, 3373, 2669, 6028, 25, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 460, 1769, 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 ]
pragma solidity ^0.4.18; import "./Bounty.sol"; /** * @title BountyHub Contract * @author Benjamin M. Brown <[email protected]> * @dev The bounty hub contract acts as a container for bounties and keeps track of newly created bounties. * In addition to creative mechanisms, the bounty hub also provides some pass through administrative functionality * which allows the bounty to be stopped, started, and ran through the process */ contract BountyHub is Stoppable { address[] public bounties; mapping(address => bool) public bountyExists; mapping(address => address) public bountiesTakenBy; mapping(address => address) public bountiesCompletedBy; mapping(address => bool) public bountyVerified; //----MODIFIERS ----// modifier onlyIfBounty(address bounty) { require(bountyExists[bounty], "bounty does not exist"); _; } modifier onlyNotTaken(address bounty){ require(bountiesTakenBy[bounty] == address(0), "Bounty already taken"); _; } modifier onlyNotCompleted(address bounty){ require(bountiesCompletedBy[bounty] == address(0), "Bounty already completed"); _; } modifier onlyCompleted(address bounty){ require(bountiesCompletedBy[bounty] != address(0), "Bounty not completed yet"); _; } modifier onlyVerified(address bounty){ require(bountyVerified[bounty] == true, "Bounty not completed yet"); _; } modifier onlyNotVerified(address bounty){ require(bountyVerified[bounty] == false, "Bounty already verified"); _; } modifier hasTakenBounty(address bounty, address taker){ require(bountiesTakenBy[bounty]==taker, "Taker has not taken this bounty"); _; } modifier hasCompletedBounty(address bounty, address taker){ require(bountiesCompletedBy[bounty]==taker, "Taker has not completed this bounty"); _; } //----EVENTS ----// event LogNewBounty(address sponsor, address bounty, uint duration, uint goal); event LogBountyStopped(address sender, address bounty); event LogBountyStarted(address sender, address bounty); event LogBountyNewOwner(address sender, address bounty, address newOwner); event LogBountyTaken(address addr, address bounty); event LogBountyCompleted(address addr, address bounty); event LogBountyVerified(address addr, address bounty); event LogBountyClaimed(address addr, address bounty); /** * @author Benjamin M. Brown * @dev outside party can take the bounty if it's not taken etc * @notice anyone can take a bounty in this case * @param bounty Address of bounty itself */ function initiateBounty(address bounty) public onlyIfBounty(bounty) onlyNotTaken(bounty) onlyNotCompleted(bounty) returns (bool){ bountiesTakenBy[bounty] = msg.sender; emit LogBountyTaken(msg.sender,bounty); return true; } /** * @author Benjamin M. Brown * @dev outsid party can complete the bounty if party has taken it * @param bounty Address of bounty itself */ function completeBounty(address bounty) public onlyIfBounty(bounty) hasTakenBounty(bounty, msg.sender) onlyNotCompleted(bounty) returns (bool) { bountiesCompletedBy[bounty] = msg.sender; emit LogBountyCompleted(msg.sender,bounty); return true; } /** * @author Benjamin M. Brown * @dev bounty sponsor can verify the bounty * @param bounty Address of bounty itself */ function verifyBountyCompleted(address bounty) public onlyIfBounty(bounty) onlyCompleted(bounty) onlyNotVerified(bounty) returns (bool success) { Bounty trustedBounty = Bounty(bounty); bountyVerified[bounty] = true; emit LogBountyVerified(msg.sender,bounty); return trustedBounty.verify(msg.sender); } /** * @author Benjamin M. Brown * @dev bounty taker can claim his bounty for completed & verified bounties * @param bounty Address of bounty itself */ function claimBounty(address bounty) public onlyIfBounty(bounty) onlyVerified(bounty) hasTakenBounty(bounty,msg.sender) returns (bool success) { Bounty trustedBounty = Bounty(bounty); emit LogBountyClaimed(msg.sender,bounty); return trustedBounty.claim(msg.sender); } /** * @author Benjamin M. Brown * @dev Get's count of bounties in hub. * @return uint bountyCount The current length of bounties array */ function getBountyCount() public view returns(uint bountyCount) { return bounties.length; } /** * @author Benjamin M. Brown * @dev bounty creation and management * @param bountyDuration The time that the bounty should run before failing * @param bountyGoal The financial goal of the bounty in Wei * @return bountyContract The address of the newly created bounty */ function createBounty(uint bountyDuration, uint bountyGoal) public returns(address bountyContract) { Bounty trustedBounty = new Bounty(msg.sender,bountyDuration, bountyGoal); bounties.push(trustedBounty); bountyExists[trustedBounty] = true; emit LogNewBounty(msg.sender, trustedBounty, bountyDuration, bountyGoal); return trustedBounty; } // Pass-through controls /* * @author Benjamin M. Brown * @dev pass through admin function to stop a bounty * @param bounty address of the bounty that should be stopped * @return success bool if bounty was successfully stopped */ function stopBounty(address bounty) public onlyOwner onlyIfBounty(bounty) returns(bool success) { Bounty trustedBounty = Bounty(bounty); emit LogBountyStopped(msg.sender, bounty); return(trustedBounty.runSwitch(false)); } /** * @author Benjamin M. Brown * @dev pass through admin function to restart a stopped bounty * @param bounty address of the bounty that should be stopped * @return success bool if bounty was successfully started */ function startBounty(address bounty) public onlyOwner onlyIfBounty(bounty) returns(bool success) { Bounty trustedBounty = Bounty(bounty); emit LogBountyStarted(msg.sender, bounty); return(trustedBounty.runSwitch(true)); } /** * @author Benjamin M. Brown * @dev pass through admin function to change owners of a bounty in the Ownable.sol contract * @param bounty address of the bounty where change of ownership is needed * @param newOwner address of the new owner * @return success bool if bounty was successfully started */ function changeBountyOwner(address bounty, address newOwner) public onlyOwner onlyIfBounty(bounty) returns(bool success) { Bounty trustedBounty = Bounty(bounty); emit LogBountyNewOwner(msg.sender, bounty, newOwner); return(trustedBounty.transferOwnership(newOwner)); } }
* @author Benjamin M. Brown @dev bounty taker can claim his bounty for completed & verified bounties @param bounty Address of bounty itself/
function claimBounty(address bounty) public onlyIfBounty(bounty) onlyVerified(bounty) hasTakenBounty(bounty,msg.sender) returns (bool success) { Bounty trustedBounty = Bounty(bounty); emit LogBountyClaimed(msg.sender,bounty); return trustedBounty.claim(msg.sender); }
1,021,783
[ 1, 38, 275, 78, 301, 267, 490, 18, 605, 26253, 225, 324, 592, 93, 268, 6388, 848, 7516, 18423, 324, 592, 93, 364, 5951, 473, 13808, 324, 592, 606, 225, 324, 592, 93, 5267, 434, 324, 592, 93, 6174, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7516, 38, 592, 93, 12, 2867, 324, 592, 93, 13, 203, 565, 1071, 7010, 565, 1338, 2047, 38, 592, 93, 12, 70, 592, 93, 13, 203, 565, 1338, 24369, 12, 70, 592, 93, 13, 203, 565, 711, 27486, 38, 592, 93, 12, 70, 592, 93, 16, 3576, 18, 15330, 13, 203, 565, 1135, 261, 6430, 2216, 13, 203, 565, 288, 27699, 3639, 605, 592, 93, 13179, 38, 592, 93, 273, 605, 592, 93, 12, 70, 592, 93, 1769, 203, 3639, 3626, 1827, 38, 592, 93, 9762, 329, 12, 3576, 18, 15330, 16, 70, 592, 93, 1769, 203, 3639, 327, 13179, 38, 592, 93, 18, 14784, 12, 3576, 18, 15330, 1769, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./extensions/ERC721EnumerableForOwner.sol"; import "./extensions/IWETH.sol"; /* * @title Pools that incentivise long term holding with bonus and penalty mechanisms * for any ERC20 token (or ETH) deposit. * Each asset has one independent pool within the contract. * Bonuses are funded from the penalties for early withdrawals. * There are two bonus types for each pool - holding bonus (to incentivise holding), * and commitment bonus (to incentivise commiting to penalties & time). * The initial penalty and commitment time are chosen at the time of the deposit by * the user. * The deposits into this contract are transferrable and immutable ERC721 tokens. * ERC20 tokens may have fee-on-transfer or dynamic supply mechanisms, and for these * kinds of tokens this contract tracks everything as "shares of initial deposits". * @notice The mechanism rules: * - A depositor is committing for "commitment period" and an "initial penalty percent" * of his choice (within allowed ranges). After the commitment period the * deposit can be withdrawn with its share of both of the bonus pools. * - The two bonus pools are populated from the penalties for early withdrawals, * which are withdrawals done before a deposit's commitment period is elapsed. * - The penalties are split in half and added to both bonus pools (isolated per asset): * Hold bonus pool and Commit bonus pool. * - The share of the bonus pools is equal to the share of the bonus points (hold-points * and commit-points) for the deposit at the time of withdrawal relative to the other * deposits in the pool. * - Hold points are calculated as amount of asset x seconds held. So more tokens * held for longer add more points - and increase the bonus share. This bonus is * independent of commitment or penalties. The points keep increasing after commitment period * is over. * - Commit points are calculated as amount of asset x seconds committed to penalty. * These points depend only on commitment time and commitment penalty * at the time of the deposit. * - Withdrawal before commitment period is not entitled to any part of the bonus * and is instead "slashed" with a penalty (that is split between the bonuses pools). * - The penalty percent is decreasing with time from the chosen * initialPenaltyPercent to 0 at the end of the commitPeriod. * - Each deposit has a separate ERC721 tokenId with the usual tranfer mechanics. So * multiple deposits for same owner and asset but with different commitment * parameters can co-exist independently. * - Deposits can be deposited for another account as beneficiary, * so e.g. a team / DAO can deposit its tokens for its members to withdraw. * - Only the deposit "owner" can use the withdrawal functionality, so ERC721 approvals * allow transfers, but not withdrawals. * * @dev * 1. For safety and clarity, withdrawal functionality is split into * two methods, one for withdrawing with penalty, and the other one for withdrawing * with bonus. * 2. ERC20 token and ETH functionality is split into separate methods. * 3. Deposit for msg.sender and depositFor are split into separate methods * for clarity. * 4. For tokens with dynamic supply mechanisms and fee on transfer all internal * calculations are done using the "initial desposit amounts" as fair shares, and * upon withdrawal are translated to actual amounts of the contract's token balance. * This means that for these tokens the actual amounts received are depends on their * mechanisms (because the amount is unknowable before actual transfers). * 5. To reduce RPC calls and simplify interface, all the deposit and pool views are * batched in depositDetails and poolDetails which return arrays of values. * 6. To prevent relying on events tracking depositsOfOwner view shows all * deposits owned by a particular owner. * 7. The total of a pool's hold points are updated incrementally on each transaction * with a pool using the depositsSum in that pool for that period. * 8. TokenURI returns a JSON string with basic name and description for the deposit. * * @author artdgn (@github) */ contract HodlPoolV3 is ERC721EnumerableForOwner { using SafeERC20 for IERC20; using Strings for uint; /// @dev state variables for a deposit in a pool struct Deposit { address asset; uint40 time; uint16 initialPenaltyPercent; uint40 commitPeriod; uint amount; } /// @dev state variables for a token pool struct Pool { uint depositsSum; // sum of all current deposits uint holdBonusesSum; // sum of hold bonus pool uint commitBonusesSum; // sum of commit bonus pool uint totalHoldPoints; // sum of hold-points uint totalHoldPointsUpdateTime; // time of the latest hold-points update uint totalCommitPoints; // sum of commit-points } /// @notice minimum initial percent of penalty uint public immutable minInitialPenaltyPercent; /// @notice minimum commitment period for a deposit uint public immutable minCommitPeriod; /// @notice compatibility with ERC20 for e.g. viewing in metamask uint public constant decimals = 0; /// @notice WETH token contract this pool is using for handling ETH // slither-disable-next-line naming-convention address public immutable WETH; /// @dev tokenId incremted counter uint internal nextTokenId = 1; /// @dev deposit data for each tokenId mapping(uint => Deposit) deposits; /// @dev pool state for each token contract address /// default values are all zeros, no need to init // slither-disable-next-line uninitialized-state mapping(address => Pool) pools; /* * @param asset ERC20 token address for the deposited asset * @param account address that has made the deposit * @param amount size of new deposit, or deposit increase * @param amountReceived received balance after transfer (actual deposit) * which may be different due to transfer-fees and other token shenanigans * @param time timestamp from which the commitment period will be counted * @param initialPenaltyPercent initial penalty percent for the deposit * @param commitPeriod commitment period in seconds for the deposit * @param tokenId deposit ERC721 tokenId */ event Deposited( address indexed asset, address indexed account, uint amount, uint amountReceived, uint time, uint initialPenaltyPercent, uint commitPeriod, uint tokenId ); /* * @param asset ERC20 token address for the withdrawed asset * @param account address that has made the withdrawal * @param amount amount sent out to account as withdrawal * @param depositAmount the original amount deposited * @param penalty the penalty incurred for this withdrawal * @param holdBonus the hold-bonus included in this withdrawal * @param commitBonus the commit-bonus included in this withdrawal * @param timeHeld the time in seconds the deposit was held */ event Withdrawed( address indexed asset, address indexed account, uint amount, uint depositAmount, uint penalty, uint holdBonus, uint commitBonus, uint timeHeld ); /// @dev checks commitment params are within allowed ranges modifier validCommitment(uint initialPenaltyPercent, uint commitPeriod) { require(initialPenaltyPercent >= minInitialPenaltyPercent, "penalty too small"); require(initialPenaltyPercent <= 100, "initial penalty > 100%"); require(commitPeriod >= minCommitPeriod, "commitment period too short"); require(commitPeriod <= 4 * 365 days, "commitment period too long"); _; } /* * @param _minInitialPenaltyPercent the minimum penalty percent for deposits * @param _minCommitPeriod the minimum time in seconds for commitPeriod of a deposit * @param _WETH wrapped ETH contract address this pool will be using for ETH */ constructor ( uint _minInitialPenaltyPercent, uint _minCommitPeriod, address _WETH ) ERC721("HodlBonusPool V3", "HodlPoolV3") { require(_minInitialPenaltyPercent > 0, "no min penalty"); require(_minInitialPenaltyPercent <= 100, "minimum initial penalty > 100%"); require(_minCommitPeriod >= 10 seconds, "minimum commitment period too short"); require(_minCommitPeriod <= 4 * 365 days, "minimum commitment period too long"); require(_WETH != address(0), "WETH address can't be 0x0"); minInitialPenaltyPercent = _minInitialPenaltyPercent; minCommitPeriod = _minCommitPeriod; WETH = _WETH; } /// @notice contract doesn't support sending ETH directly receive() external payable { require( msg.sender == WETH, "no receive() except from WETH contract, use depositETH()"); } /* * * * * * * * * * * * * Public transactions * * * * * * * * * * * * */ /* * @notice adds a deposit into its asset pool and mints an ERC721 token * @param asset address of ERC20 token contract * @param amount of token to deposit * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function deposit( address asset, uint amount, uint initialPenaltyPercent, uint commitPeriod ) public validCommitment(initialPenaltyPercent, commitPeriod) returns (uint tokenId) { require(amount > 0, "empty deposit"); // interal accounting update tokenId = _depositAndMint( asset, msg.sender, amount, initialPenaltyPercent, commitPeriod ); // this contract's balance before the transfer uint beforeBalance = IERC20(asset).balanceOf(address(this)); // transfer IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); // what was actually received, this amount is only used in the event and // not used for any internal accounting so reentrancy from transfer is not // a substantial risk uint amountReceived = IERC20(asset).balanceOf(address(this)) - beforeBalance; // because we want to know how much was received, reentrancy-*events* is low-risk // slither-disable-next-line reentrancy-events emit Deposited( asset, msg.sender, amount, amountReceived, block.timestamp, initialPenaltyPercent, commitPeriod, tokenId ); } /* * @notice payable method for depositing ETH with same logic as deposit(), * adds a deposit into WETH asset pool and mints an ERC721 token * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function depositETH( uint initialPenaltyPercent, uint commitPeriod ) public validCommitment(initialPenaltyPercent, commitPeriod) payable returns (uint tokenId) { require(msg.value > 0, "empty deposit"); // interal accounting update tokenId = _depositAndMint( WETH, msg.sender, msg.value, initialPenaltyPercent, commitPeriod ); emit Deposited( WETH, msg.sender, msg.value, msg.value, block.timestamp, initialPenaltyPercent, commitPeriod, tokenId ); // note: no share vs. balance accounting for WETH because it's assumed to // exactly correspond to actual deposits and withdrawals (no fee-on-transfer etc) IWETH(WETH).deposit{value: msg.value}(); } /* * @notice adds a deposit, mints an ERC721 token, and transfers * its ownership to another account * @param account that will be the owner of this deposit (can withdraw) * @param asset address of ERC20 token contract * @param amount of token to deposit * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function depositFor( address account, address asset, uint amount, uint initialPenaltyPercent, uint commitPeriod ) external validCommitment(initialPenaltyPercent, commitPeriod) returns (uint tokenId) { tokenId = deposit(asset, amount, initialPenaltyPercent, commitPeriod); _transfer(msg.sender, account, tokenId); } /* * @notice adds an ETH deposit, mints an ERC721 token, and transfers * its ownership to another account * @param account that will be the owner of this deposit (can withdraw) * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function depositETHFor( address account, uint initialPenaltyPercent, uint commitPeriod ) external payable validCommitment(initialPenaltyPercent, commitPeriod) returns (uint tokenId) { tokenId = depositETH(initialPenaltyPercent, commitPeriod); _transfer(msg.sender, account, tokenId); } /* * @param tokenId ERC721 tokenId of the deposit to withdraw * @notice withdraw the full deposit with the proportional shares of bonus pools. * will fail for early withdawals (for which there is another method) * @dev checks that the deposit is non-zero */ function withdrawWithBonus(uint tokenId) external { require( _timeLeft(deposits[tokenId]) == 0, "cannot withdraw without penalty yet, use withdrawWithPenalty()" ); _withdrawERC20(tokenId); } /// @notice withdraw ETH with bonus with same logic as withdrawWithBonus() function withdrawWithBonusETH(uint tokenId) external { require( _timeLeft(deposits[tokenId]) == 0, "cannot withdraw without penalty yet, use withdrawWithPenaltyETH()" ); _withdrawETH(tokenId); } /* * @param tokenId ERC721 tokenId of the deposit to withdraw * @notice withdraw the deposit with any applicable penalty. Will withdraw * with any available bonus if penalty is 0 (commitment period elapsed). */ function withdrawWithPenalty(uint tokenId) external { _withdrawERC20(tokenId); } /// @notice withdraw ETH with penalty with same logic as withdrawWithPenalty() function withdrawWithPenaltyETH(uint tokenId) external { _withdrawETH(tokenId); } /* * * * * * * * * * Public views * * * * * * * * * */ /* * @param tokenId ERC721 tokenId of a deposit * @return array of 12 values corresponding to the details of the deposit: * 0. asset - asset address converted to uint * 1. owner - deposit owner * 2. balance - original deposit(s) value * 3. timeLeftToHold - time in seconds until deposit can be withdrawed * with bonus and no penalty * 4. penalty - penalty if withdrawed now * 5. holdBonus - hold-bonus if withdrawed now (if possible to withdraw with bonus) * 6. commitBonus - commit-bonus if withdrawed now (if possible to withdraw with bonus) * 7. holdPoints - current amount of hold-point * 8. commitPoints - current amount of commit-point * 9. initialPenaltyPercent - initial penalty percent (set at time od deposit) * 10. currentPenaltyPercent - current penalty percent (penalty percent if withdrawed now) * 11. commitPeriod - commitment period set at the time of deposit */ function depositDetails( uint tokenId ) external view returns (uint[12] memory) { Deposit storage dep = deposits[tokenId]; Pool storage pool = pools[dep.asset]; address owner = _exists(tokenId) ? ownerOf(tokenId) : address(0); return [ uint(uint160(dep.asset)), // asset uint(uint160(owner)), // account owner _sharesToAmount(dep.asset, dep.amount), // balance _timeLeft(dep), // timeLeftToHold _sharesToAmount(dep.asset, _depositPenalty(dep)), // penalty _sharesToAmount(dep.asset, _holdBonus(pool, dep)), // holdBonus _sharesToAmount(dep.asset, _commitBonus(pool, dep)), // commitBonus _holdPoints(dep), // holdPoints _commitPoints(dep), // commitPoints dep.initialPenaltyPercent, // initialPenaltyPercent _currentPenaltyPercent(dep), // currentPenaltyPercent dep.commitPeriod // commitPeriod ]; } /* * @param asset address of ERC20 token contract * @return array of 5 values corresponding to the details of the pool: * 0. depositsSum - sum of current deposits * 1. holdBonusesSum - sum of tokens to be distributed as hold bonuses * 2. commitBonusesSum - sum of tokens to be distributed as commitment bonuses * 3. totalHoldPoints - sum of hold-points of all current deposits * 4. totalCommitPoints - sum of commit-points of all current deposits */ function poolDetails(address asset) external view returns (uint[5] memory) { Pool storage pool = pools[asset]; return [ _sharesToAmount(asset, pool.depositsSum), // depositsSum _sharesToAmount(asset, pool.holdBonusesSum), // holdBonusesSum _sharesToAmount(asset, pool.commitBonusesSum), // commitBonusesSum _totalHoldPoints(pool), // totalHoldPoints pool.totalCommitPoints // totalCommitPoints ]; } /* * @param account address of an owner account * @return two arrays of the deposits owned by this account: * 0. array of deposits' tokenIds * 1. array of deposits' data (Deposit struct) */ function depositsOfOwner( address account ) external view returns ( uint[] memory tokenIds, Deposit[] memory accountDeposits ) { uint balance = balanceOf(account); tokenIds = new uint[](balance); accountDeposits = new Deposit[](balance); for (uint i; i < balance; i++) { tokenIds[i] = tokenOfOwnerByIndex(account, i); accountDeposits[i] = deposits[tokenIds[i]]; } } /* * @param tokenId ERC721 tokenId of a deposit * @return string with metadata JSON containing the NFT's name and description */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: nonexistent token"); Deposit storage dep = deposits[tokenId]; return string(abi.encodePacked( '{"name":"Hodl-bonus-pool deposit, tokenId: ', tokenId.toString(), '", "description":"ERC20 asset address: ', (uint(uint160(dep.asset))).toHexString(20), '\\nDeposited amount: ', dep.amount.toString(), ' wei (of token)\\nDeposited at: ', uint(dep.time).toString(), ' seconds unix epoch\\nInitial penalty percent: ', uint(dep.initialPenaltyPercent).toString(), '%\\nCommitment period: ', uint(dep.commitPeriod).toString(), ' seconds"}' )); } /* * * * * * * * * * * * * * Internal transactions * * * * * * * * * * * * * */ /// @dev the order of calculations is important for correct accounting function _depositAndMint( address asset, address account, uint amount, uint initialPenaltyPercent, uint commitPeriod ) internal returns (uint tokenId) { // get token id and increment tokenId = nextTokenId++; // mint token _mint(account, tokenId); // add deposit data deposits[tokenId] = Deposit({ asset: asset, time: uint40(block.timestamp), initialPenaltyPercent: uint16(initialPenaltyPercent), commitPeriod: uint40(commitPeriod), amount: amount }); // pool state update _addDepositToPool(asset, deposits[tokenId]); } /// @dev pool state update for new deposit function _addDepositToPool(address asset, Deposit storage dep) internal { Pool storage pool = pools[asset]; // update pool's total hold time due to passage of time // because the deposits sum is going to change _updatePoolHoldPoints(pool); // WARNING: the deposits sum needs to be updated after the hold-points // for the passed time were updated pool.depositsSum += dep.amount; pool.totalCommitPoints += _commitPoints(dep); } // this happens on every pool interaction (so every withdrawal and deposit to that pool) function _updatePoolHoldPoints(Pool storage pool) internal { // add points proportional to amount held in pool since last update pool.totalHoldPoints = _totalHoldPoints(pool); pool.totalHoldPointsUpdateTime = block.timestamp; } function _withdrawERC20(uint tokenId) internal { address asset = deposits[tokenId].asset; address account = ownerOf(tokenId); require(account == msg.sender, "not deposit owner"); uint amountOut = _amountOutAndBurn(tokenId); // WARNING: asset and account must be set before token is burned IERC20(asset).safeTransfer(account, amountOut); } function _withdrawETH(uint tokenId) internal { address account = ownerOf(tokenId); require(account == msg.sender, "not deposit owner"); require(deposits[tokenId].asset == WETH, "not an ETH / WETH deposit"); uint amountOut = _amountOutAndBurn(tokenId); IWETH(WETH).withdraw(amountOut); // WARNING: account must be set before token is burned // - call is used because if contract is withdrawing it may need more gas than what .transfer sends // slither-disable-next-line low-level-calls (bool success, ) = payable(account).call{value: amountOut}(""); require(success); } /// @dev the order of calculations is important for correct accounting function _amountOutAndBurn(uint tokenId) internal returns (uint amountOut) { // WARNING: deposit is only read here and is not updated until it's removal Deposit storage dep = deposits[tokenId]; address asset = dep.asset; Pool storage pool = pools[asset]; // update pool hold-time points due to passage of time // WARNING: failing to do so will break hold-time holdBonus calculation _updatePoolHoldPoints(pool); // calculate penalty & bunus before making changes uint penalty = _depositPenalty(dep); uint holdBonus = 0; uint commitBonus = 0; uint withdrawShare = dep.amount - penalty; if (penalty == 0) { // only get any bonuses if no penalty holdBonus = _holdBonus(pool, dep); commitBonus = _commitBonus(pool, dep); withdrawShare += holdBonus + commitBonus; } // WARNING: get amount here before state is updated amountOut = _sharesToAmount(asset, withdrawShare); // WARNING: emit event here with all the needed data, before pool state updates // affect shareToAmount calculations emit Withdrawed( asset, ownerOf(tokenId), amountOut, dep.amount, _sharesToAmount(asset, penalty), _sharesToAmount(asset, holdBonus), _sharesToAmount(asset, commitBonus), _timeHeld(dep.time) ); // pool state update // WARNING: shares calculations need to happen before this update // because the depositSum changes _removeDepositFromPool(pool, dep, penalty, holdBonus, commitBonus); // deposit update: remove deposit // WARNING: note that removing the deposit before this line will // change "dep" because it's used by reference and will affect the other // computations for pool state updates (e.g. hold points) delete deposits[tokenId]; // burn token _burn(tokenId); } /// @dev pool state update for removing a deposit function _removeDepositFromPool( Pool storage pool, Deposit storage dep, uint penalty, uint holdBonus, uint commitBonus ) internal { // update total deposits pool.depositsSum -= dep.amount; // remove the acrued hold-points for this deposit pool.totalHoldPoints -= _holdPoints(dep); // remove the commit-points pool.totalCommitPoints -= _commitPoints(dep); if (penalty == 0 && (holdBonus > 0 || commitBonus > 0)) { pool.holdBonusesSum -= holdBonus; // update commitBonus pool pool.commitBonusesSum -= commitBonus; } else { // update hold-bonus pool: split the penalty into two parts // half for hold bonuses, half for commit bonuses pool.holdBonusesSum += penalty / 2; // update commitBonus pool pool.commitBonusesSum += (penalty - (penalty / 2)); } } /* * * * * * * * * * * Internal views * * * * * * * * * * */ function _timeHeld(uint time) internal view returns (uint) { return block.timestamp - time; } function _timeLeft(Deposit storage dep) internal view returns (uint) { uint timeHeld = _timeHeld(dep.time); return (timeHeld >= dep.commitPeriod) ? 0 : (dep.commitPeriod - timeHeld); } function _holdPoints(Deposit storage dep) internal view returns (uint) { // points proportional to amount held since deposit start return dep.amount * _timeHeld(dep.time); } function _commitPoints(Deposit storage dep) internal view returns (uint) { // points proportional to amount held since deposit start // triangle area of commitpent time and penalty return ( dep.amount * dep.initialPenaltyPercent * dep.commitPeriod / 100 / 2 ); } function _currentPenaltyPercent(Deposit storage dep) internal view returns (uint) { uint timeLeft = _timeLeft(dep); if (timeLeft == 0) { // no penalty return 0; } else { // current penalty percent is proportional to time left uint curPercent = (dep.initialPenaltyPercent * timeLeft) / dep.commitPeriod; // add 1 to compensate for rounding down unless when below initial amount return curPercent < dep.initialPenaltyPercent ? curPercent + 1 : curPercent; } } function _depositPenalty(Deposit storage dep) internal view returns (uint) { uint timeLeft = _timeLeft(dep); if (timeLeft == 0) { // no penalty return 0; } else { // order important to prevent rounding to 0 return ( (dep.amount * dep.initialPenaltyPercent * timeLeft) / dep.commitPeriod) // can't be zero / 100; } } function _holdBonus(Pool storage pool, Deposit storage dep) internal view returns (uint) { // share of bonus is proportional to hold-points of this deposit relative // to total hold-points in the pool // order important to prevent rounding to 0 uint denom = _totalHoldPoints(pool); // don't divide by 0 uint holdPoints = _holdPoints(dep); return denom > 0 ? ((pool.holdBonusesSum * holdPoints) / denom) : 0; } function _commitBonus(Pool storage pool, Deposit storage dep) internal view returns (uint) { // share of bonus is proportional to commit-points of this deposit relative // to all other commit-points in the pool // order important to prevent rounding to 0 uint denom = pool.totalCommitPoints; // don't divide by 0 uint commitPoints = _commitPoints(dep); return denom > 0 ? ((pool.commitBonusesSum * commitPoints) / denom) : 0; } function _totalHoldPoints(Pool storage pool) internal view returns (uint) { uint elapsed = block.timestamp - pool.totalHoldPointsUpdateTime; // points proportional to amount held in pool since last update return pool.totalHoldPoints + (pool.depositsSum * elapsed); } /// @dev translates deposit shares to actual token amounts - which can be different /// from the initial deposit amount for tokens with funky fees and supply mechanisms. function _sharesToAmount(address asset, uint share) internal view returns (uint) { if (share == 0) { // gas savings return 0; } // all tokens that belong to this contract are either // in deposits or in the two bonuses pools Pool storage pool = pools[asset]; uint totalShares = pool.depositsSum + pool.holdBonusesSum + pool.commitBonusesSum; if (totalShares == 0) { // don't divide by zero return 0; } else { // it's safe to call external balanceOf here because // it's a view (and this method is also view) uint actualBalance = IERC20(asset).balanceOf(address(this)); return actualBalance * share / totalShares; } } // remove super implementation function _baseURI() internal view virtual override returns (string memory) {} }
WARNING: asset and account must be set before token is burned
function _withdrawERC20(uint tokenId) internal { address asset = deposits[tokenId].asset; address account = ownerOf(tokenId); require(account == msg.sender, "not deposit owner"); uint amountOut = _amountOutAndBurn(tokenId); IERC20(asset).safeTransfer(account, amountOut); }
7,269,841
[ 1, 9511, 30, 3310, 471, 2236, 1297, 506, 444, 1865, 1147, 353, 18305, 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, 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, 225, 445, 389, 1918, 9446, 654, 39, 3462, 12, 11890, 1147, 548, 13, 2713, 288, 203, 565, 1758, 3310, 273, 443, 917, 1282, 63, 2316, 548, 8009, 9406, 31, 203, 565, 1758, 2236, 273, 3410, 951, 12, 2316, 548, 1769, 203, 565, 2583, 12, 4631, 422, 1234, 18, 15330, 16, 315, 902, 443, 1724, 3410, 8863, 203, 565, 2254, 3844, 1182, 273, 389, 8949, 1182, 1876, 38, 321, 12, 2316, 548, 1769, 203, 565, 467, 654, 39, 3462, 12, 9406, 2934, 4626, 5912, 12, 4631, 16, 3844, 1182, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-04 */ // File: contracts/interfaces/IAMB.sol pragma solidity 0.4.24; interface IAMB { function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiTokenBridge.sol pragma solidity 0.4.24; contract BasicMultiTokenBridge is EternalStorage, Ownable { using SafeMath for uint256; // token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens event DailyLimitChanged(address indexed token, uint256 newLimit); event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token address is address(0) or token was already bridged. */ function isTokenRegistered(address _token) public view returns (bool) { return minPerTx(_token) > 0; } /** * @dev Retrieves the total spent amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens sent through the bridge to the other side. */ function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))]; } /** * @dev Retrieves the total executed amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens received from the bridge from the other side. */ function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))]; } /** * @dev Retrieves current daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be sent through the bridge per day. */ function dailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; } /** * @dev Retrieves current execution daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be received from the bridge on the other side per day. */ function executionDailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; } /** * @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can be sent through the bridge in one transfer. */ function maxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))]; } /** * @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can received from the bridge on the other side in one transaction. */ function executionMaxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))]; } /** * @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return minimum amount on tokens that can be sent through the bridge in one transfer. */ function minPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))]; } /** * @dev Checks that bridged amount of tokens conforms to the configured limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be bridged. */ function withinLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount); return dailyLimit(address(0)) > 0 && dailyLimit(_token) >= nextLimit && _amount <= maxPerTx(_token) && _amount >= minPerTx(_token); } /** * @dev Checks that bridged amount of tokens conforms to the configured execution limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be processed and executed. */ function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount); return executionDailyLimit(address(0)) > 0 && executionDailyLimit(_token) >= nextLimit && _amount <= executionMaxPerTx(_token); } /** * @dev Returns current day number. * @return day number. */ function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return now / 1 days; } /** * @dev Updates daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the efault limit. * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit; emit DailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit; emit ExecutionDailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx; } /** * @dev Updates maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx; } /** * @dev Updates minumum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _minPerTx minumum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit. */ function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token)); uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @param _token address of the token contract, or address(0) for the default limit. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx(address _token) public view returns (uint256) { uint256 _maxPerTx = maxPerTx(_token); uint256 _dailyLimit = dailyLimit(_token); uint256 _spent = totalSpentPerDay(_token, getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } /** * @dev Internal function for adding spent amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalSpentPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add( _value ); } /** * @dev Internal function for adding execcuted amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalExecutedPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay( _token, _day ) .add(_value); } /** * @dev Internal function for initializing limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]. */ function _setLimits(address _token, uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1]; uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2]; emit DailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing execution limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]. */ function _setExecutionLimits(address _token, uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing limits for some token relative to its decimals parameter. * @param _token address of the token contract. * @param _decimals token decimals parameter. */ function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal { uint256 factor; if (_decimals < 18) { factor = 10**(18 - _decimals); uint256 _minPerTx = minPerTx(address(0)).div(factor); uint256 _maxPerTx = maxPerTx(address(0)).div(factor); uint256 _dailyLimit = dailyLimit(address(0)).div(factor); uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor); uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor); // such situation can happen when calculated limits relative to the token decimals are too low // e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed. // in this case, limits are raised to the default values if (_minPerTx == 0) { // Numbers 1, 100, 10000 are chosen in a semi-random way, // so that any token with small decimals can still be bridged in some amounts. // It is possible to override limits for the particular token later if needed. _minPerTx = 1; if (_maxPerTx <= _minPerTx) { _maxPerTx = 100; _executionMaxPerTx = 100; if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) { _dailyLimit = 10000; _executionDailyLimit = 10000; } } } _setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]); _setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]); } else { factor = 10**(_decimals - 18); _setLimits( _token, [dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)] ); _setExecutionLimits( _token, [executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)] ); } } } // File: contracts/libraries/Bytes.sol pragma solidity 0.4.24; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Converts bytes array to bytes32. * Truncates bytes array if its size is more than 32 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 32 bytes. * A case when _bytes has length less than 32 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to bytes32 type * @return bytes32 type of the firsts 32 bytes array in parameter. */ function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } } /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes. * @param _bytes to be converted to address type * @return address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.4.24; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); _; } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _requestGasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner { _setRequestGasLimit(_requestGasLimit); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(AddressUtils.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _requestGasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _requestGasLimit) internal { require(_requestGasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit; } /** * @dev Tells the address that generated the message on the other network that is currently being executed by * the AMB bridge. * @return the address of the message sender. */ function messageSender() internal view returns (address) { return bridgeContract().messageSender(); } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } } // File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol pragma solidity 0.4.24; contract ChooseReceiverHelper { /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of tokens sender. * @param _data passed data in the transfer message. * @return address of the receiver on the other side. */ function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); require(recipient != address(0)); require(recipient != bridgeContractOnOtherSide()); } } /* solcov ignore next */ function bridgeContractOnOtherSide() internal view returns (address); } // File: contracts/upgradeable_contracts/TransferInfoStorage.sol pragma solidity 0.4.24; contract TransferInfoStorage is EternalStorage { /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenBridgeMediator.sol pragma solidity 0.4.24; /** * @title MultiTokenBridgeMediator * @dev Common mediator functionality to handle operations related to multi-token bridge messages sent to AMB bridge. */ contract MultiTokenBridgeMediator is BasicAMBMediator, BasicMultiTokenBridge, TransferInfoStorage, ChooseReceiverHelper { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 value, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId); /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20/ERC677 token * @param _recipient address that will receive the tokens * @param _value amount of tokens to be received */ function _handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) internal { if (withinExecutionLimit(_token, _value)) { addTotalExecutedPerDay(_token, getCurrentDay(), _value); executeActionOnBridgedTokens(_token, _recipient, _value); } else { executeActionOnBridgedTokensOutOfLimit(_token, _recipient, _value); } } /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { require(!bridgeContract().messageCallStatus(_messageId)); require(bridgeContract().failedMessageReceiver(_messageId) == address(this)); require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Execute the action to be performed when the bridge tokens are out of execution limits. */ function executeActionOnBridgedTokensOutOfLimit(address, address, uint256) internal { revert(); } /* solcov ignore next */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal; /* solcov ignore next */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.4.24; contract ReentrancyGuard { function lock() internal returns (bool res) { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock")) } } function setLock(bool _lock) internal { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock")) } } } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (5, 2, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title BasicMultiAMBErc20ToErc677 * @dev Common functionality for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. */ contract BasicMultiAMBErc20ToErc677 is Initializable, ReentrancyGuard, Upgradeable, Claimable, VersionableBridge, MultiTokenBridgeMediator { /** * @dev Tells the address of the mediator contract on the other side, used by chooseReceiver method * to avoid sending the native tokens to that address. * @return address of the mediator contract con the other side */ function bridgeContractOnOtherSide() internal view returns (address) { return mediatorContractOnOtherSide(); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, address _receiver, uint256 _value) external { _relayTokens(token, _receiver, _value); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, uint256 _value) external { _relayTokens(token, msg.sender, _value); } /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (1, 5, 0); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure returns (bytes4 _data) { return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb"))) } /** * @dev Claims stucked tokens. Only unsupported tokens can be claimed. * When dealing with already supported tokens, fixMediatorBalance can be used instead. * @param _token address of claimed token, address(0) for native * @param _to address of tokens receiver */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Only unregistered tokens and native coins are allowed to be claimed with the use of this function require(_token == address(0) || !isTokenRegistered(_token)); claimValues(_token, _to); } /* solcov ignore next */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool); /* solcov ignore next */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal; /* solcov ignore next */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value) internal; } // File: contracts/upgradeability/Proxy.sol pragma solidity 0.4.24; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ /* solcov ignore next */ function implementation() public view returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function() public payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize)) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/TokenProxy.sol pragma solidity 0.4.24; interface IPermittableTokenVersion { function version() external pure returns (string); } /** * @title TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract TokenProxy is Proxy { // storage layout is copied from PermittableToken.sol string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr; // string public constant version = "1"; bytes32 internal DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; mapping(address => uint256) internal nonces; mapping(address => mapping(address => uint256)) internal expirations; /** * @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _decimals token decimals. * @param _chainId chain id for current network. */ constructor(address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId) public { string memory version = IPermittableTokenVersion(_tokenImage).version(); assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage) } name = _name; symbol = _symbol; decimals = _decimals; owner = msg.sender; // msg.sender == HomeMultiAMBErc20ToErc677 mediator bridgeContractAddr = msg.sender; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), _chainId, address(this) ) ); } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return token image address. */ function implementation() public view returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } } } // File: contracts/upgradeable_contracts/BaseRewardAddressList.sol pragma solidity 0.4.24; /** * @title BaseRewardAddressList * @dev Implements the logic to store, add and remove reward account addresses. Works as a linked list. */ contract BaseRewardAddressList is EternalStorage { using SafeMath for uint256; address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; uint256 internal constant MAX_REWARD_ADDRESSES = 50; bytes32 internal constant REWARD_ADDRESS_COUNT = 0xabc77c82721ced73eef2645facebe8c30249e6ac372cce6eb9d1fed31bd6648f; // keccak256(abi.encodePacked("rewardAddressCount")) event RewardAddressAdded(address indexed addr); event RewardAddressRemoved(address indexed addr); /** * @dev Retrieves all registered reward accounts. * @return address list of the registered reward receivers. */ function rewardAddressList() external view returns (address[]) { address[] memory list = new address[](rewardAddressCount()); uint256 counter = 0; address nextAddr = getNextRewardAddress(F_ADDR); while (nextAddr != F_ADDR) { require(nextAddr != address(0)); list[counter] = nextAddr; nextAddr = getNextRewardAddress(nextAddr); counter++; } return list; } /** * @dev Retrieves amount of registered reward accounts. * @return length of reward addresses list. */ function rewardAddressCount() public view returns (uint256) { return uintStorage[REWARD_ADDRESS_COUNT]; } /** * @dev Checks if specified address is included into the registered rewards receivers list. * @param _addr address to verify. * @return true, if specified address is associated with one of the registered reward accounts. */ function isRewardAddress(address _addr) public view returns (bool) { return _addr != F_ADDR && getNextRewardAddress(_addr) != address(0); } /** * @dev Retrieves next reward address in the linked list, or F_ADDR if given address is the last one. * @param _address address of some reward account. * @return address of the next reward receiver. */ function getNextRewardAddress(address _address) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("rewardAddressList", _address))]; } /** * @dev Internal function for adding a new reward address to the linked list. * @param _addr new reward account. */ function _addRewardAddress(address _addr) internal { require(_addr != address(0) && _addr != F_ADDR); require(!isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != address(0)); _setNextRewardAddress(_addr, nextAddr); _setNextRewardAddress(F_ADDR, _addr); _setRewardAddressCount(rewardAddressCount().add(1)); } /** * @dev Internal function for removing existing reward address from the linked list. * @param _addr old reward account which should be removed. */ function _removeRewardAddress(address _addr) internal { require(isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(_addr); address index = F_ADDR; address next = getNextRewardAddress(index); while (next != _addr) { require(next != address(0)); index = next; next = getNextRewardAddress(index); require(next != F_ADDR); } _setNextRewardAddress(index, nextAddr); delete addressStorage[keccak256(abi.encodePacked("rewardAddressList", _addr))]; _setRewardAddressCount(rewardAddressCount().sub(1)); } /** * @dev Internal function for initializing linked list with the array of the initial reward addresses. * @param _rewardAddresses initial reward addresses list, should be non-empty. */ function _setRewardAddressList(address[] _rewardAddresses) internal { require(_rewardAddresses.length > 0); _setNextRewardAddress(F_ADDR, _rewardAddresses[0]); for (uint256 i = 0; i < _rewardAddresses.length; i++) { require(_rewardAddresses[i] != address(0) && _rewardAddresses[i] != F_ADDR); require(!isRewardAddress(_rewardAddresses[i])); if (i == _rewardAddresses.length - 1) { _setNextRewardAddress(_rewardAddresses[i], F_ADDR); } else { _setNextRewardAddress(_rewardAddresses[i], _rewardAddresses[i + 1]); } emit RewardAddressAdded(_rewardAddresses[i]); } _setRewardAddressCount(_rewardAddresses.length); } /** * @dev Internal function for updating the length of the reward accounts list. * @param _rewardAddressCount new linked list length. */ function _setRewardAddressCount(uint256 _rewardAddressCount) internal { require(_rewardAddressCount <= MAX_REWARD_ADDRESSES); uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount; } /** * @dev Internal function for updating the pointer to the next reward receiver. * @param _prevAddr address of some reward receiver. * @param _addr address of the next receiver to which _prevAddr should point to. */ function _setNextRewardAddress(address _prevAddr, address _addr) internal { addressStorage[keccak256(abi.encodePacked("rewardAddressList", _prevAddr))] = _addr; } } // File: contracts/interfaces/IBurnableMintableERC677Token.sol pragma solidity 0.4.24; contract IBurnableMintableERC677Token is ERC677 { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _value) public; function claimTokens(address _token, address _to) external; } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeFeeManagerMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeFeeManagerMultiAMBErc20ToErc677 * @dev Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations. * The fees are distributed in the form of native tokens to the list of reward accounts. */ contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge { using SafeMath for uint256; event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee); event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId); // This is not a real fee value but a relative value used to calculate the fee percentage uint256 internal constant MAX_FEE = 1 ether; bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee")) bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee")) /** * @dev Throws if given fee percentage is >= 100%. */ modifier validFee(uint256 _fee) { require(_fee < MAX_FEE); /* solcov ignore next */ _; } /** * @dev Throws if given fee type is unknown. */ modifier validFeeType(bytes32 _feeType) { require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE); /* solcov ignore next */ _; } /** * @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations. * Only the owner can call this method. * @param _addr new reward account. */ function addRewardAddress(address _addr) external onlyOwner { _addRewardAddress(_addr); } /** * @dev Removes a reward address from the rewards list. * Only the owner can call this method. * @param _addr old reward account, that should be removed. */ function removeRewardAddress(address _addr) external onlyOwner { _removeRewardAddress(_addr); } /** * @dev Updates the value for the particular fee type. * Only the owner can call this method. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner { require(isTokenRegistered(_token)); _setFee(_feeType, _token, _fee); } /** * @dev Retrieves the value for the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @return fee value associated with the requested fee type. */ function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { return uintStorage[keccak256(abi.encodePacked(_feeType, _token))]; } /** * @dev Calculates the amount of fee to pay for the value of the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return amount of fee to be subtracted from the transferred value. */ function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) { uint256 _fee = getFee(_feeType, _token); return _value.mul(_fee).div(MAX_FEE); } /** * @dev Internal function for updating the fee value for the given fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) { uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee; emit FeeUpdated(_feeType, _token, _fee); } /** * @dev Calculates a random number based on the block number. * @param _count the max value for the random number. * @return a number between 0 and _count. */ function random(uint256 _count) internal view returns (uint256) { return uint256(blockhash(block.number.sub(1))) % _count; } /** * @dev Calculates and distributes the amount of fee proportionally between registered reward addresses. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return total amount of fee subtracted from the transferred value and distributed between the reward accounts. */ function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) { uint256 numOfAccounts = rewardAddressCount(); uint256 _fee = calculateFee(_feeType, _token, _value); if (numOfAccounts == 0 || _fee == 0) { return 0; } uint256 feePerAccount = _fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != F_ADDR && nextAddr != address(0)); uint256 i = 0; while (nextAddr != F_ADDR) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } if (_feeType == HOME_TO_FOREIGN_FEE) { ERC677(_token).transfer(nextAddr, feeToDistribute); } else { _getMinterFor(_token).mint(nextAddr, feeToDistribute); } nextAddr = getNextRewardAddress(nextAddr); require(nextAddr != address(0)); i = i + 1; } return _fee; } function _getMinterFor(address _token) internal view returns (IBurnableMintableERC677Token); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenForwardingRules.sol pragma solidity 0.4.24; /** * @title MultiTokenForwardingRules * @dev Multi token mediator functionality for managing destination AMB lanes permissions. */ contract MultiTokenForwardingRules is Ownable { address internal constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; event ForwardingRuleUpdated(address token, address sender, address receiver, int256 lane); /** * @dev Tells the destination lane for a particular bridge operation by checking several wildcard forwarding rules. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return destination lane identifier, where the message should be forwarded to. * 1 - oracle-driven-lane should be used. * 0 - default behaviour should be applied. * -1 - manual lane should be used. */ function destinationLane(address _token, address _sender, address _receiver) public view returns (int256) { int256 defaultLane = forwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS); // specific token for all senders and receivers int256 lane; if (defaultLane < 0) { lane = forwardingRule(_token, _sender, ANY_ADDRESS); // specific token for specific sender if (lane != 0) return lane; lane = forwardingRule(_token, ANY_ADDRESS, _receiver); // specific token for specific receiver if (lane != 0) return lane; return defaultLane; } lane = forwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS); // all tokens for specific sender if (lane != 0) return lane; return forwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver); // all tokens for specific receiver } /** * Updates the forwarding rule for bridging specific token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _enable true, if bridge operations for a given token should be forwarded to the manual lane. */ function setTokenForwardingRule(address _token, bool _enable) external { require(_token != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Allows a particular address to send bridge requests to the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _sender address of the tokens sender on the home side of the bridge. * @param _enable true, if bridge operations for a given token and sender should be forwarded to the oracle-driven lane. */ function setSenderExceptionForTokenForwardingRule(address _token, address _sender, bool _enable) external { require(_token != ANY_ADDRESS); require(_sender != ANY_ADDRESS); _setForwardingRule(_token, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } /** * Allows a particular address to receive bridged tokens from the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _enable true, if bridge operations for a given token and receiver should be forwarded to the oracle-driven lane. */ function setReceiverExceptionForTokenForwardingRule(address _token, address _receiver, bool _enable) external { require(_token != ANY_ADDRESS); require(_receiver != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0)); } /** * Updates the forwarding rule for the specific sender. * Only owner can call this method. * @param _sender address of the tokens sender on the home side. * @param _enable true, if all bridge operations from a given sender should be forwarded to the manual lane. */ function setSenderForwardingRule(address _sender, bool _enable) external { require(_sender != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Updates the forwarding rule for the specific receiver. * Only owner can call this method. * @param _receiver address of the tokens receiver on the foreign side. * @param _enable true, if all bridge operations to a given receiver should be forwarded to the manual lane. */ function setReceiverForwardingRule(address _receiver, bool _enable) external { require(_receiver != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(-1) : int256(0)); } /** * @dev Tells forwarding rule set up for a particular bridge operation. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return preferred destination lane for the particular bridge operation. */ function forwardingRule(address _token, address _sender, address _receiver) public view returns (int256) { return intStorage[keccak256(abi.encodePacked("forwardTo", _token, _sender, _receiver))]; } /** * @dev Internal function for updating the preferred destination lane for the specific wildcard pattern. * Only owner can call this method. * Examples: * _setForwardingRule(tokenA, ANY_ADDRESS, ANY_ADDRESS, -1) - forward all operations on tokenA to the manual lane * _setForwardingRule(tokenA, Alice, ANY_ADDRESS, 1) - allow Alice to use the oracle-driven lane for bridging tokenA * _setForwardingRule(tokenA, ANY_ADDRESS, Bob, 1) - forward all tokenA bridge operations, where Bob is the receiver, to the oracle-driven lane * _setForwardingRule(ANY_ADDRESS, Mallory, ANY_ADDRESS, -1) - forward all bridge operations from Mallory to the manual lane * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _lane preferred destination lane for the particular sender. * 1 - forward to the oracle-driven lane. * 0 - behaviour is unset, proceed by checking other less-specific rules. * -1 - manual lane should be used. */ function _setForwardingRule(address _token, address _sender, address _receiver, int256 _lane) internal onlyOwner { intStorage[keccak256(abi.encodePacked("forwardTo", _token, _sender, _receiver))] = _lane; emit ForwardingRuleUpdated(_token, _sender, _receiver, _lane); } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeMultiAMBErc20ToErc677 * @dev Home side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract HomeMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677, HomeFeeManagerMultiAMBErc20ToErc677, MultiTokenForwardingRules { bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract")) event NewTokenRegistered(address indexed foreignToken, address indexed homeToken); /** * @dev Throws if called by any account other than the owner. * Overrides modifier from the Ownable contract in order to reduce bytecode size. */ modifier onlyOwner() { _onlyOwner(); /* solcov ignore next */ _; } /** * @dev Internal function for reducing onlyOwner modifier bytecode size overhead. */ function _onlyOwner() internal { require(msg.sender == owner()); } /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator() { _onlyMediator(); /* solcov ignore next */ _; } /** * @dev Internal function for reducing onlyMediator modifier bytecode size overhead. */ function _onlyMediator() internal { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); } /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _tokenImage address of the PermittableToken contract that will be used for deploying of new tokens. * @param _rewardAddresses list of reward addresses, between whom fees will be distributed. * @param _fees array with initial fees for both bridge directions. * [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner, address _tokenImage, address[] _rewardAddresses, uint256[2] _fees // [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImage(_tokenImage); if (_rewardAddresses.length > 0) { _setRewardAddressList(_rewardAddresses); } _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]); _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]); setInitialize(); return isInitialized(); } /** * @dev Updates an address of the token image contract used for proxifying newly created tokens. * @param _tokenImage address of PermittableToken contract. */ function setTokenImage(address _tokenImage) external onlyOwner { _setTokenImage(_tokenImage); } /** * @dev Retrieves address of the token image contract. * @return address of block reward contract. */ function tokenImage() public view returns (address) { return addressStorage[TOKEN_IMAGE_CONTRACT]; } /** * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract. * Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token address of the bridged ERC20/ERC677 token on the foreign side. * @param _name name of the bridged token, "x" will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, "x" will be appended, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function deployAndHandleBridgedTokens( address _token, string _name, string _symbol, uint8 _decimals, address _recipient, uint256 _value ) external onlyMediator { require(owner() == _recipient); string memory name = _name; string memory symbol = _symbol; require(bytes(name).length > 0 || bytes(symbol).length > 0); if (bytes(name).length == 0) { name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } name = string(abi.encodePacked(name, " on ETH")); address homeToken = new TokenProxy(tokenImage(), name, symbol, _decimals, bridgeContract().sourceChainId()); _setTokenAddressPair(_token, homeToken); _initializeTokenBridgeLimits(homeToken, _decimals); _setFee(HOME_TO_FOREIGN_FEE, homeToken, getFee(HOME_TO_FOREIGN_FEE, address(0))); _setFee(FOREIGN_TO_HOME_FEE, homeToken, getFee(FOREIGN_TO_HOME_FEE, address(0))); _handleBridgedTokens(ERC677(homeToken), _recipient, _value); emit NewTokenRegistered(_token, homeToken); } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator { ERC677 homeToken = ERC677(homeTokenAddress(_token)); require(isTokenRegistered(homeToken)); _handleBridgedTokens(homeToken, _recipient, _value); } /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { // if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing if (!lock()) { ERC677 token = ERC677(msg.sender); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); bridgeSpecificActionsOnTokenTransfer(token, _from, chooseReceiver(_from, _data), _value); } return true; } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); address to = address(this); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); setLock(true); token.transferFrom(msg.sender, to, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _receiver, _value); } /** * @dev Executes action on the request to deposit tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); uint256 valueToMint = _value; uint256 fee = _distributeFee(FOREIGN_TO_HOME_FEE, _token, minPerTx(_token)); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); valueToMint = _value.sub(fee); } _getMinterFor(_token).mint(_recipient, valueToMint); emit TokensBridged(_token, _recipient, valueToMint, _messageId); } /** * @dev Mints back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal { _getMinterFor(_token).mint(_recipient, _value); } /** * @dev Retrieves address of the home bridged token contract associated with a specific foreign token contract. * @param _foreignToken address of the created home token contract. * @return address of the home token contract. */ function homeTokenAddress(address _foreignToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))]; } /** * @dev Retrieves address of the foreign bridged token contract associated with a specific home token contract. * @param _homeToken address of the created home token contract. * @return address of the foreign token contract. */ function foreignTokenAddress(address _homeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))]; } /** * @dev Internal function for updating an address of the token image contract. * @param _foreignToken address of bridged foreign token contract. * @param _foreignToken address of created home token contract. */ function _setTokenAddressPair(address _foreignToken, address _homeToken) internal { addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))] = _homeToken; addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))] = _foreignToken; } /** * @dev Internal function for updating an address of the token image contract. * @param _tokenImage address of deployed PermittableToken contract. */ function _setTokenImage(address _tokenImage) internal { require(AddressUtils.isContract(_tokenImage)); addressStorage[TOKEN_IMAGE_CONTRACT] = _tokenImage; } /** * @dev Executes action on withdrawal of bridged tokens * @param _token address of token contract * @param _from address of tokens sender * @param _receiver address of tokens receiver on the other side * @param _value requested amount of bridged tokens */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value) internal { uint256 valueToBridge = _value; uint256 fee = 0; // Next line disables fee collection in case sender is one of the reward addresses. // It is needed to allow a 100% withdrawal of tokens from the home side. // If fees are not disabled for reward receivers, small fraction of tokens will always // be redistributed between the same set of reward addresses, which is not the desired behaviour. if (!isRewardAddress(_from)) { fee = _distributeFee(HOME_TO_FOREIGN_FEE, _token, minPerTx(_token)); valueToBridge = _value.sub(fee); } IBurnableMintableERC677Token(_token).burn(valueToBridge); bytes32 _messageId = passMessage(_token, _from, _receiver, valueToBridge); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); } } /** * @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network. * Store information related to the bridged tokens in case the message execution fails on the other network * and the action needs to be fixed/rolled back. * @param _token bridged ERC20 token * @param _from address of sender, if bridge operation fails, tokens will be returned to this address * @param _receiver address of receiver on the other side, will eventually receive bridged tokens * @param _value bridged amount of tokens * @return id of the created and passed message */ function passMessage(ERC677 _token, address _from, address _receiver, uint256 _value) internal returns (bytes32) { bytes4 methodSelector = this.handleBridgedTokens.selector; address foreignToken = foreignTokenAddress(_token); bytes memory data = abi.encodeWithSelector(methodSelector, foreignToken, _receiver, _value); address executor = mediatorContractOnOtherSide(); uint256 gasLimit = requestGasLimit(); IAMB bridge = bridgeContract(); // Address of the foreign token is used here for determining lane permissions. // Such decision makes it possible to set rules for tokens that are not bridged yet. bytes32 _messageId = destinationLane(foreignToken, _from, _receiver) >= 0 ? bridge.requireToPassMessage(executor, data, gasLimit) : bridge.requireToConfirmMessage(executor, data, gasLimit); setMessageToken(_messageId, _token); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); emit TokensBridgingInitiated(_token, _from, _value, _messageId); return _messageId; } /** * @dev Internal function for getting minter proxy address. * Returns the token address itself, expect for the case with bridged STAKE token. * For bridged STAKE token, returns the hardcoded TokenMinter contract address. * @param _token address of the token to mint. * @return address of the minter contract that should be used for calling mint(address,uint256) */ function _getMinterFor(address _token) internal view returns (IBurnableMintableERC677Token) { return IBurnableMintableERC677Token(_token); } /** * @dev Withdraws erc20 tokens or native coins from the bridged token contract. * Only the proxy owner is allowed to call this method. * @param _bridgedToken address of the bridged token contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokensFromTokenContract(address _bridgedToken, address _token, address _to) external onlyIfUpgradeabilityOwner { IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to); } }
* @dev Withdraws erc20 tokens or native coins from the bridged token contract. Only the proxy owner is allowed to call this method. @param _bridgedToken address of the bridged token contract. @param _token address of the claimed token or address(0) for native coins. @param _to address of the tokens/coins receiver./
function claimTokensFromTokenContract(address _bridgedToken, address _token, address _to) external onlyIfUpgradeabilityOwner { IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to); }
7,814,827
[ 1, 1190, 9446, 87, 6445, 71, 3462, 2430, 578, 6448, 276, 9896, 628, 326, 324, 1691, 2423, 1147, 6835, 18, 5098, 326, 2889, 3410, 353, 2935, 358, 745, 333, 707, 18, 225, 389, 14400, 2423, 1345, 1758, 434, 326, 324, 1691, 2423, 1147, 6835, 18, 225, 389, 2316, 1758, 434, 326, 7516, 329, 1147, 578, 1758, 12, 20, 13, 364, 6448, 276, 9896, 18, 225, 389, 869, 1758, 434, 326, 2430, 19, 71, 9896, 5971, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7516, 5157, 1265, 1345, 8924, 12, 2867, 389, 14400, 2423, 1345, 16, 1758, 389, 2316, 16, 1758, 389, 869, 13, 203, 3639, 3903, 203, 3639, 1338, 2047, 10784, 2967, 5541, 203, 565, 288, 203, 3639, 23450, 321, 429, 49, 474, 429, 654, 39, 26, 4700, 1345, 24899, 14400, 2423, 1345, 2934, 14784, 5157, 24899, 2316, 16, 389, 869, 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 ]
./full_match/4/0xFd7F543b64257e8e83af5601756C28C611FA4Ae2/sources/contracts/NagaToken.sol
@notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
802,122
[ 1, 37, 1409, 434, 19588, 26402, 364, 1517, 2236, 16, 635, 770, 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, 282, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 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 ]
pragma solidity 0.5.12; pragma experimental ABIEncoderV2; // File: @airswap/types/contracts/Types.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { bytes constant internal EIP191_HEADER = "\x19\x01"; struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } bytes32 constant internal DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant internal ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "Party signer,", "Party sender,", "Party affiliate", ")", "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 amount,", "uint256 id", ")" )); bytes32 constant internal PARTY_TYPEHASH = keccak256(abi.encodePacked( "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 amount,", "uint256 id", ")" )); /** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param order Order The order to be hashed * @param domainSeparator bytes32 * @return bytes32 A keccak256 abi.encodePacked value */ function hashOrder( Order calldata order, bytes32 domainSeparator ) external pure returns (bytes32) { return keccak256(abi.encodePacked( EIP191_HEADER, domainSeparator, keccak256(abi.encode( ORDER_TYPEHASH, order.nonce, order.expiry, keccak256(abi.encode( PARTY_TYPEHASH, order.signer.kind, order.signer.wallet, order.signer.token, order.signer.amount, order.signer.id )), keccak256(abi.encode( PARTY_TYPEHASH, order.sender.kind, order.sender.wallet, order.sender.token, order.sender.amount, order.sender.id )), keccak256(abi.encode( PARTY_TYPEHASH, order.affiliate.kind, order.affiliate.wallet, order.affiliate.token, order.affiliate.amount, order.affiliate.id )) )) )); } /** * @notice Hash domain parameters into bytes32 * @dev Used for signature validation (EIP-712) * @param name bytes * @param version bytes * @param verifyingContract address * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashDomain( bytes calldata name, bytes calldata version, address verifyingContract ) external pure returns (bytes32) { return keccak256(abi.encode( DOMAIN_TYPEHASH, keccak256(name), keccak256(version), verifyingContract )); } } // File: @airswap/delegate/contracts/interfaces/IDelegate.sol /* Copyright 2020 Swap Holdings 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. */ interface IDelegate { struct Rule { uint256 maxSenderAmount; // The maximum amount of ERC-20 token the delegate would send uint256 priceCoef; // Number to be multiplied by 10^(-priceExp) - the price coefficient uint256 priceExp; // Indicates location of the decimal priceCoef * 10^(-priceExp) } event SetRule( address indexed owner, address indexed senderToken, address indexed signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ); event UnsetRule( address indexed owner, address indexed senderToken, address indexed signerToken ); event ProvideOrder( address indexed owner, address tradeWallet, address indexed senderToken, address indexed signerToken, uint256 senderAmount, uint256 priceCoef, uint256 priceExp ); function setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) external; function unsetRule( address senderToken, address signerToken ) external; function provideOrder( Types.Order calldata order ) external; function rules(address, address) external view returns (Rule memory); function getSignerSideQuote( uint256 senderAmount, address senderToken, address signerToken ) external view returns ( uint256 signerAmount ); function getSenderSideQuote( uint256 signerAmount, address signerToken, address senderToken ) external view returns ( uint256 senderAmount ); function getMaxQuote( address senderToken, address signerToken ) external view returns ( uint256 senderAmount, uint256 signerAmount ); function owner() external view returns (address); function tradeWallet() external view returns (address); } // File: @airswap/indexer/contracts/interfaces/IIndexer.sol /* Copyright 2020 Swap Holdings 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. */ interface IIndexer { event CreateIndex( address indexed signerToken, address indexed senderToken, bytes2 protocol, address indexAddress ); event Stake( address indexed staker, address indexed signerToken, address indexed senderToken, bytes2 protocol, uint256 stakeAmount ); event Unstake( address indexed staker, address indexed signerToken, address indexed senderToken, bytes2 protocol, uint256 stakeAmount ); event AddTokenToBlacklist( address token ); event RemoveTokenFromBlacklist( address token ); function setLocatorWhitelist( bytes2 protocol, address newLocatorWhitelist ) external; function createIndex( address signerToken, address senderToken, bytes2 protocol ) external returns (address); function addTokenToBlacklist( address token ) external; function removeTokenFromBlacklist( address token ) external; function setIntent( address signerToken, address senderToken, bytes2 protocol, uint256 stakingAmount, bytes32 locator ) external; function unsetIntent( address signerToken, address senderToken, bytes2 protocol ) external; function stakingToken() external view returns (address); function indexes(address, address, bytes2) external view returns (address); function tokenBlacklist(address) external view returns (bool); function getStakedAmount( address user, address signerToken, address senderToken, bytes2 protocol ) external view returns (uint256); function getLocators( address signerToken, address senderToken, bytes2 protocol, address cursor, uint256 limit ) external view returns ( bytes32[] memory, uint256[] memory, address ); } // File: @airswap/transfers/contracts/interfaces/ITransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title ITransferHandler: interface for token transfers */ interface ITransferHandler { /** * @notice Function to wrap token transfer for different token types * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id token ID for ERC-721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool); } // File: openzeppelin-solidity/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.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. * * 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @airswap/transfers/contracts/TransferHandlerRegistry.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title TransferHandlerRegistry: holds registry of contract to * facilitate token transfers */ contract TransferHandlerRegistry is Ownable { event AddTransferHandler( bytes4 kind, address contractAddress ); // Mapping of bytes4 to contract interface type mapping (bytes4 => ITransferHandler) public transferHandlers; /** * @notice Adds handler to mapping * @param kind bytes4 Key value that defines a token type * @param transferHandler ITransferHandler */ function addTransferHandler(bytes4 kind, ITransferHandler transferHandler) external onlyOwner { require(address(transferHandlers[kind]) == address(0), "HANDLER_EXISTS_FOR_KIND"); transferHandlers[kind] = transferHandler; emit AddTransferHandler(kind, address(transferHandler)); } } // File: @airswap/swap/contracts/interfaces/ISwap.sol /* Copyright 2020 Swap Holdings 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. */ interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel( uint256 indexed nonce, address indexed signerWallet ); event CancelUpTo( uint256 indexed nonce, address indexed signerWallet ); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap( Types.Order calldata order ) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel( uint256[] calldata nonces ) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo( uint256 minimumNonce ) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender( address authorizedSender ) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner( address authorizedSigner ) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender( address authorizedSender ) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner( address authorizedSigner ) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (byte); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (TransferHandlerRegistry); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _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-solidity/contracts/token/ERC20/IERC20.sol /** * @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: @airswap/delegate/contracts/Delegate.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Delegate: Deployable Trading Rules for the AirSwap Network * @notice Supports fungible tokens (ERC-20) * @dev inherits IDelegate, Ownable uses SafeMath library */ contract Delegate is IDelegate, Ownable { using SafeMath for uint256; // The Swap contract to be used to settle trades ISwap public swapContract; // The Indexer to stake intent to trade on IIndexer public indexer; // Maximum integer for token transfer approval uint256 constant internal MAX_INT = 2**256 - 1; // Address holding tokens that will be trading through this delegate address public tradeWallet; // Mapping of senderToken to signerToken for rule lookup mapping (address => mapping (address => Rule)) public rules; // ERC-20 (fungible token) interface identifier (ERC-165) bytes4 constant internal ERC20_INTERFACE_ID = 0x36372b07; // The protocol identifier for setting intents on an Index bytes2 public protocol; /** * @notice Contract Constructor * @dev owner defaults to msg.sender if delegateContractOwner is provided as address(0) * @param delegateSwap address Swap contract the delegate will deploy with * @param delegateIndexer address Indexer contract the delegate will deploy with * @param delegateContractOwner address Owner of the delegate * @param delegateTradeWallet address Wallet the delegate will trade from * @param delegateProtocol bytes2 The protocol identifier for Delegate contracts */ constructor( ISwap delegateSwap, IIndexer delegateIndexer, address delegateContractOwner, address delegateTradeWallet, bytes2 delegateProtocol ) public { swapContract = delegateSwap; indexer = delegateIndexer; protocol = delegateProtocol; // If no delegate owner is provided, the deploying address is the owner. if (delegateContractOwner != address(0)) { transferOwnership(delegateContractOwner); } // If no trade wallet is provided, the owner's wallet is the trade wallet. if (delegateTradeWallet != address(0)) { tradeWallet = delegateTradeWallet; } else { tradeWallet = owner(); } // Ensure that the indexer can pull funds from delegate account. require( IERC20(indexer.stakingToken()) .approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED" ); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) external onlyOwner { _setRule( senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @dev only callable by the owner of the contract, removes from a mapping * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function unsetRule( address senderToken, address signerToken ) external onlyOwner { _unsetRule( senderToken, signerToken ); } /** * @notice sets a rule on the delegate and an intent on the indexer * @dev only callable by owner * @dev delegate needs to be given allowance from msg.sender for the newStakeAmount * @dev swap needs to be given permission to move funds from the delegate * @param senderToken address Token the delgeate will send * @param signerToken address Token the delegate will receive * @param rule Rule Rule to set on a delegate * @param newStakeAmount uint256 Amount to stake for an intent */ function setRuleAndIntent( address senderToken, address signerToken, Rule calldata rule, uint256 newStakeAmount ) external onlyOwner { _setRule( senderToken, signerToken, rule.maxSenderAmount, rule.priceCoef, rule.priceExp ); // get currentAmount staked or 0 if never staked uint256 oldStakeAmount = indexer.getStakedAmount(address(this), signerToken, senderToken, protocol); if (oldStakeAmount == newStakeAmount && oldStakeAmount > 0) { return; // forgo trying to reset intent with non-zero same stake amount } else if (oldStakeAmount < newStakeAmount) { // transfer only the difference from the sender to the Delegate. require( IERC20(indexer.stakingToken()) .transferFrom(msg.sender, address(this), newStakeAmount - oldStakeAmount), "STAKING_TRANSFER_FAILED" ); } indexer.setIntent( signerToken, senderToken, protocol, newStakeAmount, bytes32(uint256(address(this)) << 96) //NOTE: this will pad 0's to the right ); if (oldStakeAmount > newStakeAmount) { // return excess stake back require( IERC20(indexer.stakingToken()) .transfer(msg.sender, oldStakeAmount - newStakeAmount), "STAKING_RETURN_FAILED" ); } } /** * @notice unsets a rule on the delegate and removes an intent on the indexer * @dev only callable by owner * @param senderToken address Maker token in the token pair for rules and intents * @param signerToken address Taker token in the token pair for rules and intents */ function unsetRuleAndIntent( address senderToken, address signerToken ) external onlyOwner { _unsetRule(senderToken, signerToken); // Query the indexer for the amount staked. uint256 stakedAmount = indexer.getStakedAmount(address(this), signerToken, senderToken, protocol); indexer.unsetIntent(signerToken, senderToken, protocol); // Upon unstaking, the Delegate will be given the staking amount. // This is returned to the msg.sender. if (stakedAmount > 0) { require( IERC20(indexer.stakingToken()) .transfer(msg.sender, stakedAmount),"STAKING_RETURN_FAILED" ); } } /** * @notice Provide an Order * @dev Rules get reset with new maxSenderAmount * @param order Types.Order Order a user wants to submit to Swap. */ function provideOrder( Types.Order calldata order ) external { Rule memory rule = rules[order.sender.token][order.signer.token]; require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Ensure the order is for the trade wallet. require(order.sender.wallet == tradeWallet, "SENDER_WALLET_INVALID"); // Ensure the tokens are valid ERC20 tokens. require(order.signer.kind == ERC20_INTERFACE_ID, "SIGNER_KIND_MUST_BE_ERC20"); require(order.sender.kind == ERC20_INTERFACE_ID, "SENDER_KIND_MUST_BE_ERC20"); // Ensure that a rule exists. require(rule.maxSenderAmount != 0, "TOKEN_PAIR_INACTIVE"); // Ensure the order does not exceed the maximum amount. require(order.sender.amount <= rule.maxSenderAmount, "AMOUNT_EXCEEDS_MAX"); // Ensure the order is priced according to the rule. require(order.sender.amount <= _calculateSenderAmount(order.signer.amount, rule.priceCoef, rule.priceExp), "PRICE_INVALID"); // Overwrite the rule with a decremented maxSenderAmount. rules[order.sender.token][order.signer.token] = Rule({ maxSenderAmount: (rule.maxSenderAmount).sub(order.sender.amount), priceCoef: rule.priceCoef, priceExp: rule.priceExp }); // Perform the swap. swapContract.swap(order); emit ProvideOrder( owner(), tradeWallet, order.sender.token, order.signer.token, order.sender.amount, rule.priceCoef, rule.priceExp ); } /** * @notice Set a new trade wallet * @param newTradeWallet address Address of the new trade wallet */ function setTradeWallet(address newTradeWallet) external onlyOwner { require(newTradeWallet != address(0), "TRADE_WALLET_REQUIRED"); tradeWallet = newTradeWallet; } /** * @notice Get a Signer-Side Quote from the Delegate * @param senderAmount uint256 Amount of ERC-20 token the delegate would send * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 signerAmount Amount of ERC-20 token the consumer would send */ function getSignerSideQuote( uint256 senderAmount, address senderToken, address signerToken ) external view returns ( uint256 signerAmount ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Ensure the senderAmount does not exceed maximum for the rule. if(senderAmount <= rule.maxSenderAmount) { signerAmount = _calculateSignerAmount(senderAmount, rule.priceCoef, rule.priceExp); // Return the quote. return signerAmount; } } return 0; } /** * @notice Get a Sender-Side Quote from the Delegate * @param signerAmount uint256 Amount of ERC-20 token the consumer would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param senderToken address Address of an ERC-20 token the delegate would send * @return uint256 senderAmount Amount of ERC-20 token the delegate would send */ function getSenderSideQuote( uint256 signerAmount, address signerToken, address senderToken ) external view returns ( uint256 senderAmount ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Calculate the senderAmount. senderAmount = _calculateSenderAmount(signerAmount, rule.priceCoef, rule.priceExp); // Ensure the senderAmount does not exceed the maximum trade amount. if(senderAmount <= rule.maxSenderAmount) { return senderAmount; } } return 0; } /** * @notice Get a Maximum Quote from the Delegate * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 senderAmount Amount the delegate would send * @return uint256 signerAmount Amount the consumer would send */ function getMaxQuote( address senderToken, address signerToken ) external view returns ( uint256 senderAmount, uint256 signerAmount ) { Rule memory rule = rules[senderToken][signerToken]; senderAmount = rule.maxSenderAmount; // Ensure that a rule exists. if (senderAmount > 0) { // calculate the signerAmount signerAmount = _calculateSignerAmount(senderAmount, rule.priceCoef, rule.priceExp); // Return the maxSenderAmount and calculated signerAmount. return ( senderAmount, signerAmount ); } return (0, 0); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function _setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) internal { require(priceCoef > 0, "PRICE_COEF_INVALID"); rules[senderToken][signerToken] = Rule({ maxSenderAmount: maxSenderAmount, priceCoef: priceCoef, priceExp: priceExp }); emit SetRule( owner(), senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function _unsetRule( address senderToken, address signerToken ) internal { // using non-zero rule.priceCoef for rule existence check if (rules[senderToken][signerToken].priceCoef > 0) { // Delete the rule. delete rules[senderToken][signerToken]; emit UnsetRule( owner(), senderToken, signerToken ); } } /** * @notice Calculate the signer amount for a given sender amount and price * @param senderAmount uint256 The amount the delegate would send in the swap * @param priceCoef uint256 Coefficient of the token price defined in the rule * @param priceExp uint256 Exponent of the token price defined in the rule */ function _calculateSignerAmount( uint256 senderAmount, uint256 priceCoef, uint256 priceExp ) internal pure returns ( uint256 signerAmount ) { // Calculate the signer amount using the price formula uint256 multiplier = senderAmount.mul(priceCoef); signerAmount = multiplier.div(10 ** priceExp); // If the div rounded down, round up if (multiplier.mod(10 ** priceExp) > 0) { signerAmount++; } } /** * @notice Calculate the sender amount for a given signer amount and price * @param signerAmount uint256 The amount the signer would send in the swap * @param priceCoef uint256 Coefficient of the token price defined in the rule * @param priceExp uint256 Exponent of the token price defined in the rule */ function _calculateSenderAmount( uint256 signerAmount, uint256 priceCoef, uint256 priceExp ) internal pure returns ( uint256 senderAmount ) { // Calculate the sender anount using the price formula senderAmount = signerAmount .mul(10 ** priceExp) .div(priceCoef); } } // File: @airswap/delegate/contracts/interfaces/IDelegateFactory.sol /* Copyright 2020 Swap Holdings 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. */ interface IDelegateFactory { event CreateDelegate( address indexed delegateContract, address swapContract, address indexerContract, address indexed delegateContractOwner, address delegateTradeWallet ); /** * @notice Deploy a trusted delegate contract * @param delegateTradeWallet the wallet the delegate will trade from * @return delegateContractAddress address of the delegate contract created */ function createDelegate( address delegateTradeWallet ) external returns (address delegateContractAddress); } // File: @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol /* Copyright 2020 Swap Holdings 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. */ interface ILocatorWhitelist { function has( bytes32 locator ) external view returns (bool); } // File: @airswap/delegate/contracts/DelegateFactory.sol /* Copyright 2020 Swap Holdings 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. */ contract DelegateFactory is IDelegateFactory, ILocatorWhitelist { // Mapping specifying whether an address was deployed by this factory mapping(address => bool) internal _deployedAddresses; // The swap and indexer contracts to use in the deployment of Delegates ISwap public swapContract; IIndexer public indexerContract; bytes2 public protocol; /** * @notice Create a new Delegate contract * @dev swapContract is unable to be changed after the factory sets it * @param factorySwapContract address Swap contract the delegate will deploy with * @param factoryIndexerContract address Indexer contract the delegate will deploy with * @param factoryProtocol bytes2 Protocol type of the delegates the factory deploys */ constructor( ISwap factorySwapContract, IIndexer factoryIndexerContract, bytes2 factoryProtocol ) public { swapContract = factorySwapContract; indexerContract = factoryIndexerContract; protocol = factoryProtocol; } /** * @param delegateTradeWallet address Wallet the delegate will trade from * @return address delegateContractAddress Address of the delegate contract created */ function createDelegate( address delegateTradeWallet ) external returns (address delegateContractAddress) { delegateContractAddress = address( new Delegate(swapContract, indexerContract, msg.sender, delegateTradeWallet, protocol) ); _deployedAddresses[delegateContractAddress] = true; emit CreateDelegate( delegateContractAddress, address(swapContract), address(indexerContract), msg.sender, delegateTradeWallet ); return delegateContractAddress; } /** * @notice To check whether a locator was deployed * @dev Implements ILocatorWhitelist.has * @param locator bytes32 Locator of the delegate in question * @return bool True if the delegate was deployed by this contract */ function has(bytes32 locator) external view returns (bool) { return _deployedAddresses[address(bytes20(locator))]; } } // File: @airswap/indexer/contracts/Index.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Index: A List of Locators * @notice The Locators are sorted in reverse order based on the score * meaning that the first element in the list has the largest score * and final element has the smallest * @dev A mapping is used to mimic a circular linked list structure * where every mapping Entry contains a pointer to the next * and the previous */ contract Index is Ownable { // The number of entries in the index uint256 public length; // Identifier to use for the head of the list address constant internal HEAD = address(uint160(2**160-1)); // Mapping of an identifier to its entry mapping(address => Entry) public entries; /** * @notice Index Entry * @param score uint256 * @param locator bytes32 * @param prev address Previous address in the linked list * @param next address Next address in the linked list */ struct Entry { bytes32 locator; uint256 score; address prev; address next; } /** * @notice Contract Events */ event SetLocator( address indexed identifier, uint256 score, bytes32 indexed locator ); event UnsetLocator( address indexed identifier ); /** * @notice Contract Constructor */ constructor() public { // Create initial entry. entries[HEAD] = Entry(bytes32(0), 0, HEAD, HEAD); } /** * @notice Set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function setLocator( address identifier, uint256 score, bytes32 locator ) external onlyOwner { // Ensure the entry does not already exist. require(!_hasEntry(identifier), "ENTRY_ALREADY_EXISTS"); _setLocator(identifier, score, locator); // Increment the index length. length = length + 1; emit SetLocator(identifier, score, locator); } /** * @notice Unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function unsetLocator( address identifier ) external onlyOwner { _unsetLocator(identifier); // Decrement the index length. length = length - 1; emit UnsetLocator(identifier); } /** * @notice Update a Locator * @dev score and/or locator do not need to be different from old values * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function updateLocator( address identifier, uint256 score, bytes32 locator ) external onlyOwner { // Don't need to update length as it is not used in set/unset logic _unsetLocator(identifier); _setLocator(identifier, score, locator); emit SetLocator(identifier, score, locator); } /** * @notice Get a Score * @param identifier address On-chain address identifying the owner of a locator * @return uint256 Score corresponding to the identifier */ function getScore( address identifier ) external view returns (uint256) { return entries[identifier].score; } /** * @notice Get a Locator * @param identifier address On-chain address identifying the owner of a locator * @return bytes32 Locator information */ function getLocator( address identifier ) external view returns (bytes32) { return entries[identifier].locator; } /** * @notice Get a Range of Locators * @dev start value of 0x0 starts at the head * @param cursor address Cursor to start with * @param limit uint256 Maximum number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { address identifier; // If a valid cursor is provided, start there. if (cursor != address(0) && cursor != HEAD) { // Check that the provided cursor exists. if (!_hasEntry(cursor)) { return (new bytes32[](0), new uint256[](0), address(0)); } // Set the starting identifier to the provided cursor. identifier = cursor; } else { identifier = entries[HEAD].next; } // Although it's not known how many entries are between `cursor` and the end // We know that it is no more than `length` uint256 size = (length < limit) ? length : limit; locators = new bytes32[](size); scores = new uint256[](size); // Iterate over the list until the end or size. uint256 i; while (i < size && identifier != HEAD) { locators[i] = entries[identifier].locator; scores[i] = entries[identifier].score; i = i + 1; identifier = entries[identifier].next; } return (locators, scores, identifier); } /** * @notice Internal function to set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function _setLocator( address identifier, uint256 score, bytes32 locator ) internal { // Disallow locator set to 0x0 to ensure list integrity. require(locator != bytes32(0), "LOCATOR_MUST_BE_SENT"); // Find the first entry with a lower score. address nextEntry = _getEntryLowerThan(score); // Link the new entry between previous and next. address prevEntry = entries[nextEntry].prev; entries[prevEntry].next = identifier; entries[nextEntry].prev = identifier; entries[identifier] = Entry(locator, score, prevEntry, nextEntry); } /** * @notice Internal function to unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function _unsetLocator( address identifier ) internal { // Ensure the entry exists. require(_hasEntry(identifier), "ENTRY_DOES_NOT_EXIST"); // Link the previous and next entries together. address prevUser = entries[identifier].prev; address nextUser = entries[identifier].next; entries[prevUser].next = nextUser; entries[nextUser].prev = prevUser; // Delete entry from the index. delete entries[identifier]; } /** * @notice Check if the Index has an Entry * @param identifier address On-chain address identifying the owner of a locator * @return bool True if the identifier corresponds to an Entry in the list */ function _hasEntry( address identifier ) internal view returns (bool) { return entries[identifier].locator != bytes32(0); } /** * @notice Returns the largest scoring Entry Lower than a Score * @param score uint256 Score in question * @return address Identifier of the largest score lower than score */ function _getEntryLowerThan( uint256 score ) internal view returns (address) { address identifier = entries[HEAD].next; // Head indicates last because the list is circular. if (score == 0) { return HEAD; } // Iterate until a lower score is found. while (score <= entries[identifier].score) { identifier = entries[identifier].next; } return identifier; } } // File: @airswap/indexer/contracts/Indexer.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Indexer: A Collection of Index contracts by Token Pair */ contract Indexer is IIndexer, Ownable { // Token to be used for staking (ERC-20) IERC20 public stakingToken; // Mapping of signer token to sender token to protocol type to index mapping (address => mapping (address => mapping (bytes2 => Index))) public indexes; // The whitelist contract for checking whether a peer is whitelisted per peer type mapping (bytes2 => address) public locatorWhitelists; // Mapping of token address to boolean mapping (address => bool) public tokenBlacklist; /** * @notice Contract Constructor * @param indexerStakingToken address */ constructor( address indexerStakingToken ) public { stakingToken = IERC20(indexerStakingToken); } /** * @notice Modifier to check an index exists */ modifier indexExists(address signerToken, address senderToken, bytes2 protocol) { require(indexes[signerToken][senderToken][protocol] != Index(0), "INDEX_DOES_NOT_EXIST"); _; } /** * @notice Set the address of an ILocatorWhitelist to use * @dev Allows removal of locatorWhitelist by passing 0x0 * @param protocol bytes2 Protocol type for locators * @param newLocatorWhitelist address Locator whitelist */ function setLocatorWhitelist( bytes2 protocol, address newLocatorWhitelist ) external onlyOwner { locatorWhitelists[protocol] = newLocatorWhitelist; } /** * @notice Create an Index (List of Locators for a Token Pair) * @dev Deploys a new Index contract and stores the address. If the Index already * @dev exists, returns its address, and does not emit a CreateIndex event * @param signerToken address Signer token for the Index * @param senderToken address Sender token for the Index * @param protocol bytes2 Protocol type for locators in Index */ function createIndex( address signerToken, address senderToken, bytes2 protocol ) external returns (address) { // If the Index does not exist, create it. if (indexes[signerToken][senderToken][protocol] == Index(0)) { // Create a new Index contract for the token pair. indexes[signerToken][senderToken][protocol] = new Index(); emit CreateIndex(signerToken, senderToken, protocol, address(indexes[signerToken][senderToken][protocol])); } // Return the address of the Index contract. return address(indexes[signerToken][senderToken][protocol]); } /** * @notice Add a Token to the Blacklist * @param token address Token to blacklist */ function addTokenToBlacklist( address token ) external onlyOwner { if (!tokenBlacklist[token]) { tokenBlacklist[token] = true; emit AddTokenToBlacklist(token); } } /** * @notice Remove a Token from the Blacklist * @param token address Token to remove from the blacklist */ function removeTokenFromBlacklist( address token ) external onlyOwner { if (tokenBlacklist[token]) { tokenBlacklist[token] = false; emit RemoveTokenFromBlacklist(token); } } /** * @notice Set an Intent to Trade * @dev Requires approval to transfer staking token for sender * * @param signerToken address Signer token of the Index being staked * @param senderToken address Sender token of the Index being staked * @param protocol bytes2 Protocol type for locator in Intent * @param stakingAmount uint256 Amount being staked * @param locator bytes32 Locator of the staker */ function setIntent( address signerToken, address senderToken, bytes2 protocol, uint256 stakingAmount, bytes32 locator ) external indexExists(signerToken, senderToken, protocol) { // If whitelist set, ensure the locator is valid. if (locatorWhitelists[protocol] != address(0)) { require(ILocatorWhitelist(locatorWhitelists[protocol]).has(locator), "LOCATOR_NOT_WHITELISTED"); } // Ensure neither of the tokens are blacklisted. require(!tokenBlacklist[signerToken] && !tokenBlacklist[senderToken], "PAIR_IS_BLACKLISTED"); bool notPreviouslySet = (indexes[signerToken][senderToken][protocol].getLocator(msg.sender) == bytes32(0)); if (notPreviouslySet) { // Only transfer for staking if stakingAmount is set. if (stakingAmount > 0) { // Transfer the stakingAmount for staking. require(stakingToken.transferFrom(msg.sender, address(this), stakingAmount), "STAKING_FAILED"); } // Set the locator on the index. indexes[signerToken][senderToken][protocol].setLocator(msg.sender, stakingAmount, locator); emit Stake(msg.sender, signerToken, senderToken, protocol, stakingAmount); } else { uint256 oldStake = indexes[signerToken][senderToken][protocol].getScore(msg.sender); _updateIntent(msg.sender, signerToken, senderToken, protocol, stakingAmount, locator, oldStake); } } /** * @notice Unset an Intent to Trade * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the Index being unstaked * @param senderToken address Sender token of the Index being staked * @param protocol bytes2 Protocol type for locators in Intent */ function unsetIntent( address signerToken, address senderToken, bytes2 protocol ) external { _unsetIntent(msg.sender, signerToken, senderToken, protocol); } /** * @notice Get the locators of those trading a token pair * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair * @param protocol bytes2 Protocol type for locators in Intent * @param cursor address Address to start from * @param limit uint256 Total number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address signerToken, address senderToken, bytes2 protocol, address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { // Ensure neither token is blacklisted. if (tokenBlacklist[signerToken] || tokenBlacklist[senderToken]) { return (new bytes32[](0), new uint256[](0), address(0)); } // Ensure the index exists. if (indexes[signerToken][senderToken][protocol] == Index(0)) { return (new bytes32[](0), new uint256[](0), address(0)); } return indexes[signerToken][senderToken][protocol].getLocators(cursor, limit); } /** * @notice Gets the Stake Amount for a User * @param user address User who staked * @param signerToken address Signer token the user staked on * @param senderToken address Sender token the user staked on * @param protocol bytes2 Protocol type for locators in Intent * @return uint256 Amount the user staked */ function getStakedAmount( address user, address signerToken, address senderToken, bytes2 protocol ) public view returns (uint256 stakedAmount) { if (indexes[signerToken][senderToken][protocol] == Index(0)) { return 0; } // Return the score, equivalent to the stake amount. return indexes[signerToken][senderToken][protocol].getScore(user); } function _updateIntent( address user, address signerToken, address senderToken, bytes2 protocol, uint256 newAmount, bytes32 newLocator, uint256 oldAmount ) internal { // If the new stake is bigger, collect the difference. if (oldAmount < newAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transferFrom(user, address(this), newAmount - oldAmount), "STAKING_FAILED"); } // If the old stake is bigger, return the excess. if (newAmount < oldAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transfer(user, oldAmount - newAmount)); } // Update their intent. indexes[signerToken][senderToken][protocol].updateLocator(user, newAmount, newLocator); emit Stake(user, signerToken, senderToken, protocol, newAmount); } /** * @notice Unset intents and return staked tokens * @param user address Address of the user who staked * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair * @param protocol bytes2 Protocol type for locators in Intent */ function _unsetIntent( address user, address signerToken, address senderToken, bytes2 protocol ) internal indexExists(signerToken, senderToken, protocol) { // Get the score for the user. uint256 score = indexes[signerToken][senderToken][protocol].getScore(user); // Unset the locator on the index. indexes[signerToken][senderToken][protocol].unsetLocator(user); if (score > 0) { // Return the staked tokens. Reverts on failure. require(stakingToken.transfer(user, score)); } emit Unstake(user, signerToken, senderToken, protocol, score); } } // File: @airswap/swap/contracts/Swap.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Swap: The Atomic Swap used on the AirSwap Network */ contract Swap is ISwap { // Domain and version for use in signatures (EIP-712) bytes constant internal DOMAIN_NAME = "SWAP"; bytes constant internal DOMAIN_VERSION = "2"; // Unique domain identifier for use in signatures (EIP-712) bytes32 private _domainSeparator; // Possible nonce statuses byte constant internal AVAILABLE = 0x00; byte constant internal UNAVAILABLE = 0x01; // Mapping of sender address to a delegated sender address and bool mapping (address => mapping (address => bool)) public senderAuthorizations; // Mapping of signer address to a delegated signer and bool mapping (address => mapping (address => bool)) public signerAuthorizations; // Mapping of signers to nonces with value AVAILABLE (0x00) or UNAVAILABLE (0x01) mapping (address => mapping (uint256 => byte)) public signerNonceStatus; // Mapping of signer addresses to an optionally set minimum valid nonce mapping (address => uint256) public signerMinimumNonce; // A registry storing a transfer handler for different token kinds TransferHandlerRegistry public registry; /** * @notice Contract Constructor * @dev Sets domain for signature validation (EIP-712) * @param swapRegistry TransferHandlerRegistry */ constructor(TransferHandlerRegistry swapRegistry) public { _domainSeparator = Types.hashDomain( DOMAIN_NAME, DOMAIN_VERSION, address(this) ); registry = swapRegistry; } /** * @notice Atomic Token Swap * @param order Types.Order Order to settle */ function swap( Types.Order calldata order ) external { // Ensure the order is not expired. require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the nonce is AVAILABLE (0x00). require(signerNonceStatus[order.signer.wallet][order.nonce] == AVAILABLE, "ORDER_TAKEN_OR_CANCELLED"); // Ensure the order nonce is above the minimum. require(order.nonce >= signerMinimumNonce[order.signer.wallet], "NONCE_TOO_LOW"); // Mark the nonce UNAVAILABLE (0x01). signerNonceStatus[order.signer.wallet][order.nonce] = UNAVAILABLE; // Validate the sender side of the trade. address finalSenderWallet; if (order.sender.wallet == address(0)) { /** * Sender is not specified. The msg.sender of the transaction becomes * the sender of the order. */ finalSenderWallet = msg.sender; } else { /** * Sender is specified. If the msg.sender is not the specified sender, * this determines whether the msg.sender is an authorized sender. */ require(isSenderAuthorized(order.sender.wallet, msg.sender), "SENDER_UNAUTHORIZED"); // The msg.sender is authorized. finalSenderWallet = order.sender.wallet; } // Validate the signer side of the trade. if (order.signature.v == 0) { /** * Signature is not provided. The signer may have authorized the * msg.sender to swap on its behalf, which does not require a signature. */ require(isSignerAuthorized(order.signer.wallet, msg.sender), "SIGNER_UNAUTHORIZED"); } else { /** * The signature is provided. Determine whether the signer is * authorized and if so validate the signature itself. */ require(isSignerAuthorized(order.signer.wallet, order.signature.signatory), "SIGNER_UNAUTHORIZED"); // Ensure the signature is valid. require(isValid(order, _domainSeparator), "SIGNATURE_INVALID"); } // Transfer token from sender to signer. transferToken( finalSenderWallet, order.signer.wallet, order.sender.amount, order.sender.id, order.sender.token, order.sender.kind ); // Transfer token from signer to sender. transferToken( order.signer.wallet, finalSenderWallet, order.signer.amount, order.signer.id, order.signer.token, order.signer.kind ); // Transfer token from signer to affiliate if specified. if (order.affiliate.token != address(0)) { transferToken( order.signer.wallet, order.affiliate.wallet, order.affiliate.amount, order.affiliate.id, order.affiliate.token, order.affiliate.kind ); } emit Swap( order.nonce, block.timestamp, order.signer.wallet, order.signer.amount, order.signer.id, order.signer.token, finalSenderWallet, order.sender.amount, order.sender.id, order.sender.token, order.affiliate.wallet, order.affiliate.amount, order.affiliate.id, order.affiliate.token ); } /** * @notice Cancel one or more open orders by nonce * @dev Cancelled nonces are marked UNAVAILABLE (0x01) * @dev Emits a Cancel event * @dev Out of gas may occur in arrays of length > 400 * @param nonces uint256[] List of nonces to cancel */ function cancel( uint256[] calldata nonces ) external { for (uint256 i = 0; i < nonces.length; i++) { if (signerNonceStatus[msg.sender][nonces[i]] == AVAILABLE) { signerNonceStatus[msg.sender][nonces[i]] = UNAVAILABLE; emit Cancel(nonces[i], msg.sender); } } } /** * @notice Cancels all orders below a nonce value * @dev Emits a CancelUpTo event * @param minimumNonce uint256 Minimum valid nonce */ function cancelUpTo( uint256 minimumNonce ) external { signerMinimumNonce[msg.sender] = minimumNonce; emit CancelUpTo(minimumNonce, msg.sender); } /** * @notice Authorize a delegated sender * @dev Emits an AuthorizeSender event * @param authorizedSender address Address to authorize */ function authorizeSender( address authorizedSender ) external { require(msg.sender != authorizedSender, "SELF_AUTH_INVALID"); if (!senderAuthorizations[msg.sender][authorizedSender]) { senderAuthorizations[msg.sender][authorizedSender] = true; emit AuthorizeSender(msg.sender, authorizedSender); } } /** * @notice Authorize a delegated signer * @dev Emits an AuthorizeSigner event * @param authorizedSigner address Address to authorize */ function authorizeSigner( address authorizedSigner ) external { require(msg.sender != authorizedSigner, "SELF_AUTH_INVALID"); if (!signerAuthorizations[msg.sender][authorizedSigner]) { signerAuthorizations[msg.sender][authorizedSigner] = true; emit AuthorizeSigner(msg.sender, authorizedSigner); } } /** * @notice Revoke an authorized sender * @dev Emits a RevokeSender event * @param authorizedSender address Address to revoke */ function revokeSender( address authorizedSender ) external { if (senderAuthorizations[msg.sender][authorizedSender]) { delete senderAuthorizations[msg.sender][authorizedSender]; emit RevokeSender(msg.sender, authorizedSender); } } /** * @notice Revoke an authorized signer * @dev Emits a RevokeSigner event * @param authorizedSigner address Address to revoke */ function revokeSigner( address authorizedSigner ) external { if (signerAuthorizations[msg.sender][authorizedSigner]) { delete signerAuthorizations[msg.sender][authorizedSigner]; emit RevokeSigner(msg.sender, authorizedSigner); } } /** * @notice Determine whether a sender delegate is authorized * @param authorizer address Address doing the authorization * @param delegate address Address being authorized * @return bool True if a delegate is authorized to send */ function isSenderAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || senderAuthorizations[authorizer][delegate]); } /** * @notice Determine whether a signer delegate is authorized * @param authorizer address Address doing the authorization * @param delegate address Address being authorized * @return bool True if a delegate is authorized to sign */ function isSignerAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || signerAuthorizations[authorizer][delegate]); } /** * @notice Validate signature using an EIP-712 typed data hash * @param order Types.Order Order to validate * @param domainSeparator bytes32 Domain identifier used in signatures (EIP-712) * @return bool True if order has a valid signature */ function isValid( Types.Order memory order, bytes32 domainSeparator ) internal pure returns (bool) { if (order.signature.version == byte(0x01)) { return order.signature.signatory == ecrecover( Types.hashOrder( order, domainSeparator ), order.signature.v, order.signature.r, order.signature.s ); } if (order.signature.version == byte(0x45)) { return order.signature.signatory == ecrecover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", Types.hashOrder(order, domainSeparator) ) ), order.signature.v, order.signature.r, order.signature.s ); } return false; } /** * @notice Perform token transfer for tokens in registry * @dev Transfer type specified by the bytes4 kind param * @dev ERC721: uses transferFrom for transfer * @dev ERC20: Takes into account non-standard ERC-20 tokens. * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id token ID for ERC-721 * @param token address Contract address of token * @param kind bytes4 EIP-165 interface ID of the token */ function transferToken( address from, address to, uint256 amount, uint256 id, address token, bytes4 kind ) internal { // Ensure the transfer is not to self. require(from != to, "SELF_TRANSFER_INVALID"); ITransferHandler transferHandler = registry.transferHandlers(kind); require(address(transferHandler) != address(0), "TOKEN_KIND_UNKNOWN"); // delegatecall required to pass msg.sender as Swap contract to handle the // token transfer in the calling contract (bool success, bytes memory data) = address(transferHandler). delegatecall(abi.encodeWithSelector( transferHandler.transferTokens.selector, from, to, amount, id, token )); require(success && abi.decode(data, (bool)), "TRANSFER_FAILED"); } } // File: @airswap/tokens/contracts/interfaces/IWETH.sol interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); } // File: @airswap/wrapper/contracts/Wrapper.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Wrapper: Send and receive ether for WETH trades */ contract Wrapper { // The Swap contract to settle trades ISwap public swapContract; // The WETH contract to wrap ether IWETH public wethContract; /** * @notice Contract Constructor * @param wrapperSwapContract address * @param wrapperWethContract address */ constructor( address wrapperSwapContract, address wrapperWethContract ) public { swapContract = ISwap(wrapperSwapContract); wethContract = IWETH(wrapperWethContract); } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ function() external payable { // Ensure the message sender is the WETH contract. if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Send an Order to be forwarded to Swap * @dev Sender must authorize this contract on the swapContract * @dev Sender must approve this contract on the wethContract * @param order Types.Order The Order */ function swap( Types.Order calldata order ) external payable { // Ensure msg.sender is sender wallet. require(order.sender.wallet == msg.sender, "MSG_SENDER_MUST_BE_ORDER_SENDER"); // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the sender provides ETH and the order is WETH _wrapEther(order.sender); // Perform the swap. swapContract.swap(order); // Unwraps WETH to ETH when the sender receives WETH _unwrapEther(order.sender.wallet, order.signer.token, order.signer.amount); } /** * @notice Send an Order to be forwarded to a Delegate * @dev Sender must authorize the Delegate contract on the swapContract * @dev Sender must approve this contract on the wethContract * @dev Delegate's tradeWallet must be order.sender - checked in Delegate * @param order Types.Order The Order * @param delegate IDelegate The Delegate to provide the order to */ function provideDelegateOrder( Types.Order calldata order, IDelegate delegate ) external payable { // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the signer provides ETH and the order is WETH _wrapEther(order.signer); // Provide the order to the Delegate. delegate.provideOrder(order); // Unwraps WETH to ETH when the signer receives WETH _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount); } /** * @notice Wraps ETH to WETH when a trade requires it * @param party Types.Party The side of the trade that may need wrapping */ function _wrapEther(Types.Party memory party) internal { // Check whether ether needs wrapping if (party.token == address(wethContract)) { // Ensure message value is param. require(party.amount == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer the WETH from the wrapper to party. // Return value not checked - WETH throws on error and does not return false wethContract.transfer(party.wallet, party.amount); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } } /** * @notice Unwraps WETH to ETH when a trade requires it * @dev The unwrapping only succeeds if recipientWallet has approved transferFrom * @param recipientWallet address The trade recipient, who may have received WETH * @param receivingToken address The token address the recipient received * @param amount uint256 The amount of token the recipient received */ function _unwrapEther(address recipientWallet, address receivingToken, uint256 amount) internal { // Check whether ether needs unwrapping if (receivingToken == address(wethContract)) { // Transfer weth from the recipient to the wrapper. wethContract.transferFrom(recipientWallet, address(this), amount); // Unwrap (withdraw) the ether. wethContract.withdraw(amount); // Transfer ether to the recipient. // solium-disable-next-line security/no-call-value (bool success, ) = recipientWallet.call.value(amount)(""); require(success, "ETH_RETURN_FAILED"); } } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @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: @airswap/tokens/contracts/interfaces/IERC1155.sol /** * * Copied from OpenZeppelin ERC1155 feature branch from (20642cca30fa18fb167df6db1889b558742d189a) * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feature-erc1155/contracts/token/ERC1155/ERC1155.sol */ /** @title ERC-1155 Multi Token Standard basic interface @dev See https://eips.ethereum.org/EIPS/eip-1155 */ contract IERC1155 is IERC165 { event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); event ApprovalForAll(address indexed account, address indexed operator, bool approved); event URI(string value, uint256 indexed id); function balanceOf(address account, uint256 id) public view returns (uint256); function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view returns (uint256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address account, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external; function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data) external; } // File: @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract ERC1155TransferHandler is ITransferHandler { /** * @notice Function to wrap safeTransferFrom for ERC1155 * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-1155 * @param id uint256 token ID for ERC-1155 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool) { IERC1155(token).safeTransferFrom( from, to, id, amount, "" // bytes are empty ); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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: @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract ERC20TransferHandler is ITransferHandler { using SafeERC20 for IERC20; /** * @notice Function to wrap safeTransferFrom for ERC20 * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id uint256 ID, must be 0 for this contract * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool) { require(id == 0, "ID_INVALID"); IERC20(token).safeTransferFrom(from, to, amount); return true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract ERC721TransferHandler is ITransferHandler { /** * @notice Function to wrap safeTransferFrom for ERC721 * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256, must be 0 for this contract * @param id uint256 ID for ERC721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token) external returns (bool) { require(amount == 0, "AMOUNT_INVALID"); IERC721(token).safeTransferFrom(from, to, id); return true; } } // File: @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title IKittyCoreTokenTransfer * @dev transferFrom function from KittyCore */ contract IKittyCoreTokenTransfer { function transferFrom(address from, address to, uint256 tokenId) external; } // File: @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract KittyCoreTransferHandler is ITransferHandler { /** * @notice Function to wrap transferFrom for CKitty * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256, must be 0 for this contract * @param id uint256 ID for ERC721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool) { require(amount == 0, "AMOUNT_INVALID"); IKittyCoreTokenTransfer(token).transferFrom(from, to, id); return true; } } // File: contracts/Imports.sol //Import all the contracts desired to be deployed contract Imports {}
* @notice Send an Order to be forwarded to a Delegate @dev Sender must authorize the Delegate contract on the swapContract @dev Sender must approve this contract on the wethContract @dev Delegate's tradeWallet must be order.sender - checked in Delegate @param order Types.Order The Order @param delegate IDelegate The Delegate to provide the order to/ Ensure that the signature is present. The signature will be explicitly checked in Swap. Wraps ETH to WETH when the signer provides ETH and the order is WETH Provide the order to the Delegate. Unwraps WETH to ETH when the signer receives WETH
function provideDelegateOrder( Types.Order calldata order, IDelegate delegate ) external payable { require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); _wrapEther(order.signer); delegate.provideOrder(order); _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount); }
12,682,709
[ 1, 3826, 392, 4347, 358, 506, 19683, 358, 279, 27687, 225, 15044, 1297, 12229, 326, 27687, 6835, 603, 326, 7720, 8924, 225, 15044, 1297, 6617, 537, 333, 6835, 603, 326, 341, 546, 8924, 225, 27687, 1807, 18542, 16936, 1297, 506, 1353, 18, 15330, 300, 5950, 316, 27687, 225, 1353, 7658, 18, 2448, 1021, 4347, 225, 7152, 1599, 292, 4784, 1021, 27687, 358, 5615, 326, 1353, 358, 19, 7693, 716, 326, 3372, 353, 3430, 18, 1021, 3372, 903, 506, 8122, 5950, 316, 12738, 18, 678, 7506, 512, 2455, 358, 678, 1584, 44, 1347, 326, 10363, 8121, 512, 2455, 471, 326, 1353, 353, 678, 1584, 44, 26569, 326, 1353, 358, 326, 27687, 18, 1351, 91, 7506, 678, 1584, 44, 358, 512, 2455, 1347, 326, 10363, 17024, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 5615, 9586, 2448, 12, 203, 565, 7658, 18, 2448, 745, 892, 1353, 16, 203, 565, 1599, 292, 4784, 7152, 203, 225, 262, 3903, 8843, 429, 288, 203, 565, 2583, 12, 1019, 18, 8195, 18, 90, 480, 374, 16, 203, 1377, 315, 26587, 67, 49, 5996, 67, 5948, 67, 17418, 8863, 203, 565, 389, 4113, 41, 1136, 12, 1019, 18, 2977, 264, 1769, 203, 565, 7152, 18, 685, 6768, 2448, 12, 1019, 1769, 203, 565, 389, 318, 4113, 41, 1136, 12, 1019, 18, 2977, 264, 18, 19177, 16, 1353, 18, 15330, 18, 2316, 16, 1353, 18, 15330, 18, 8949, 1769, 203, 225, 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 ]
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity =0.6.10; pragma experimental ABIEncoderV2; // File: contracts/packages/oz/upgradeability/Initializable.sol /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/packages/oz/upgradeability/GSN/ContextUpgradeable.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: contracts/packages/oz/upgradeability/OwnableUpgradeSafe.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, 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(address _sender) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(_sender); } function __Ownable_init_unchained(address _sender) internal initializer { _owner = _sender; emit OwnershipTransferred(address(0), _sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts/packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.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]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: contracts/packages/oz/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/libs/MarginVault.sol /** * MarginVault Error Codes * V1: invalid short otoken amount * V2: invalid short otoken index * V3: short otoken address mismatch * V4: invalid long otoken amount * V5: invalid long otoken index * V6: long otoken address mismatch * V7: invalid collateral amount * V8: invalid collateral token index * V9: collateral token address mismatch */ /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { using SafeMath for uint256; // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } /** * @dev increase the short oToken balance in a vault when a new oToken is minted * @param _vault vault to add or increase the short position in * @param _shortOtoken address of the _shortOtoken being minted from the user's vault * @param _amount number of _shortOtoken being minted from the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function addShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V1"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) { _vault.shortOtokens.push(_shortOtoken); _vault.shortAmounts.push(_amount); } else { require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2"); address existingShort = _vault.shortOtokens[_index]; require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3"); _vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount); _vault.shortOtokens[_index] = _shortOtoken; } } /** * @dev decrease the short oToken balance in a vault when an oToken is burned * @param _vault vault to decrease short position in * @param _shortOtoken address of the _shortOtoken being reduced in the user's vault * @param _amount number of _shortOtoken being reduced in the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function removeShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { // check that the removed short oToken exists in the vault at the specified index require(_index < _vault.shortOtokens.length, "V2"); require(_vault.shortOtokens[_index] == _shortOtoken, "V3"); uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount); if (newShortAmount == 0) { delete _vault.shortOtokens[_index]; } _vault.shortAmounts[_index] = newShortAmount; } /** * @dev increase the long oToken balance in a vault when an oToken is deposited * @param _vault vault to add a long position to * @param _longOtoken address of the _longOtoken being added to the user's vault * @param _amount number of _longOtoken the protocol is adding to the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V4"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) { _vault.longOtokens.push(_longOtoken); _vault.longAmounts.push(_amount); } else { require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5"); address existingLong = _vault.longOtokens[_index]; require((existingLong == _longOtoken) || (existingLong == address(0)), "V6"); _vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount); _vault.longOtokens[_index] = _longOtoken; } } /** * @dev decrease the long oToken balance in a vault when an oToken is withdrawn * @param _vault vault to remove a long position from * @param _longOtoken address of the _longOtoken being removed from the user's vault * @param _amount number of _longOtoken the protocol is removing from the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function removeLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { // check that the removed long oToken exists in the vault at the specified index require(_index < _vault.longOtokens.length, "V5"); require(_vault.longOtokens[_index] == _longOtoken, "V6"); uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount); if (newLongAmount == 0) { delete _vault.longOtokens[_index]; } _vault.longAmounts[_index] = newLongAmount; } /** * @dev increase the collateral balance in a vault * @param _vault vault to add collateral to * @param _collateralAsset address of the _collateralAsset being added to the user's vault * @param _amount number of _collateralAsset being added to the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function addCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V7"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) { _vault.collateralAssets.push(_collateralAsset); _vault.collateralAmounts.push(_amount); } else { require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8"); address existingCollateral = _vault.collateralAssets[_index]; require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9"); _vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount); _vault.collateralAssets[_index] = _collateralAsset; } } /** * @dev decrease the collateral balance in a vault * @param _vault vault to remove collateral from * @param _collateralAsset address of the _collateralAsset being removed from the user's vault * @param _amount number of _collateralAsset being removed from the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function removeCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { // check that the removed collateral exists in the vault at the specified index require(_index < _vault.collateralAssets.length, "V8"); require(_vault.collateralAssets[_index] == _collateralAsset, "V9"); uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount); if (newCollateralAmount == 0) { delete _vault.collateralAssets[_index]; } _vault.collateralAmounts[_index] = newCollateralAmount; } } // File: contracts/libs/Actions.sol /** * @title Actions * @author Opyn Team * @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions. * errorCode * A1 can only parse arguments for open vault actions * A2 cannot open vault for an invalid account * A3 cannot open vault with an invalid type * A4 can only parse arguments for mint actions * A5 cannot mint from an invalid account * A6 can only parse arguments for burn actions * A7 cannot burn from an invalid account * A8 can only parse arguments for deposit actions * A9 cannot deposit to an invalid account * A10 can only parse arguments for withdraw actions * A11 cannot withdraw from an invalid account * A12 cannot withdraw to an invalid account * A13 can only parse arguments for redeem actions * A14 cannot redeem to an invalid account * A15 can only parse arguments for settle vault actions * A16 cannot settle vault for an invalid account * A17 cannot withdraw payout to an invalid account * A18 can only parse arguments for liquidate action * A19 cannot liquidate vault for an invalid account owner * A20 cannot send collateral to an invalid account * A21 cannot parse liquidate action with no round id * A22 can only parse arguments for call actions * A23 target address cannot be address(0) */ library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct MintArgs { // address of the account owner address owner; // index of the vault from which the asset will be minted uint256 vaultId; // address to which we transfer the minted oTokens address to; // oToken that is to be minted address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be minted uint256 amount; } struct BurnArgs { // address of the account owner address owner; // index of the vault from which the oToken will be burned uint256 vaultId; // address from which we transfer the oTokens address from; // oToken that is to be burned address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be burned uint256 amount; } struct OpenVaultArgs { // address of the account owner address owner; // vault id to create uint256 vaultId; // vault type, 0 for spread/max loss and 1 for naked margin vault uint256 vaultType; } struct DepositArgs { // address of the account owner address owner; // index of the vault to which the asset will be added uint256 vaultId; // address from which we transfer the asset address from; // asset that is to be deposited address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be deposited uint256 amount; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } struct WithdrawArgs { // address of the account owner address owner; // index of the vault from which the asset will be withdrawn uint256 vaultId; // address to which we transfer the asset address to; // asset that is to be withdrawn address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be withdrawn uint256 amount; } struct SettleVaultArgs { // address of the account owner address owner; // index of the vault to which is to be settled uint256 vaultId; // address to which we transfer the remaining collateral address to; } struct LiquidateArgs { // address of the vault owner to liquidate address owner; // address of the liquidated collateral receiver address receiver; // vault id to liquidate uint256 vaultId; // amount of debt(otoken) to repay uint256 amount; // chainlink round id uint256 roundId; } struct CallArgs { // address of the callee contract address callee; // data field for external calls bytes data; } /** * @notice parses the passed in action arguments to get the arguments for an open vault action * @param _args general action arguments structure * @return arguments for a open vault action */ function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require(_args.actionType == ActionType.OpenVault, "A1"); require(_args.owner != address(0), "A2"); // if not _args.data included, vault type will be 0 by default uint256 vaultType; if (_args.data.length == 32) { // decode vault type from _args.data vaultType = abi.decode(_args.data, (uint256)); } // for now we only have 2 vault types require(vaultType < 2, "A3"); return OpenVaultArgs({owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType}); } /** * @notice parses the passed in action arguments to get the arguments for a mint action * @param _args general action arguments structure * @return arguments for a mint action */ function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require(_args.actionType == ActionType.MintShortOption, "A4"); require(_args.owner != address(0), "A5"); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a burn action * @param _args general action arguments structure * @return arguments for a burn action */ function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require(_args.actionType == ActionType.BurnShortOption, "A6"); require(_args.owner != address(0), "A7"); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a deposit action * @param _args general action arguments structure * @return arguments for a deposit action */ function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "A8" ); require(_args.owner != address(0), "A9"); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a withdraw action * @param _args general action arguments structure * @return arguments for a withdraw action */ function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); require(_args.secondAddress != address(0), "A12"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for an redeem action * @param _args general action arguments structure * @return arguments for a redeem action */ function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require(_args.actionType == ActionType.Redeem, "A13"); require(_args.secondAddress != address(0), "A14"); return RedeemArgs({receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount}); } /** * @notice parses the passed in action arguments to get the arguments for a settle vault action * @param _args general action arguments structure * @return arguments for a settle vault action */ function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require(_args.actionType == ActionType.SettleVault, "A15"); require(_args.owner != address(0), "A16"); require(_args.secondAddress != address(0), "A17"); return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress}); } function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) { require(_args.actionType == ActionType.Liquidate, "A18"); require(_args.owner != address(0), "A19"); require(_args.secondAddress != address(0), "A20"); require(_args.data.length == 32, "A21"); // decode chainlink round id from _args.data uint256 roundId = abi.decode(_args.data, (uint256)); return LiquidateArgs({ owner: _args.owner, receiver: _args.secondAddress, vaultId: _args.vaultId, amount: _args.amount, roundId: roundId }); } /** * @notice parses the passed in action arguments to get the arguments for a call action * @param _args general action arguments structure * @return arguments for a call action */ function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require(_args.actionType == ActionType.Call, "A22"); require(_args.secondAddress != address(0), "A23"); return CallArgs({callee: _args.secondAddress, data: _args.data}); } } // File: contracts/interfaces/AddressBookInterface.sol interface AddressBookInterface { /* Getters */ function getOtokenImpl() external view returns (address); function getOtokenFactory() external view returns (address); function getWhitelist() external view returns (address); function getController() external view returns (address); function getOracle() external view returns (address); function getMarginPool() external view returns (address); function getMarginCalculator() external view returns (address); function getLiquidationManager() external view returns (address); function getAddress(bytes32 _id) external view returns (address); /* Setters */ function setOtokenImpl(address _otokenImpl) external; function setOtokenFactory(address _factory) external; function setOracleImpl(address _otokenImpl) external; function setWhitelist(address _whitelist) external; function setController(address _controller) external; function setMarginPool(address _marginPool) external; function setMarginCalculator(address _calculator) external; function setLiquidationManager(address _liquidationManager) external; function setAddress(bytes32 _id, address _newImpl) external; } // File: contracts/interfaces/OtokenInterface.sol interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // File: contracts/interfaces/MarginCalculatorInterface.sol interface MarginCalculatorInterface { function addressBook() external view returns (address); function getExpiredPayoutRate(address _otoken) external view returns (uint256); function getExcessCollateral(MarginVault.Vault calldata _vault, uint256 _vaultType) external view returns (uint256 netValue, bool isExcess); function isLiquidatable( MarginVault.Vault memory _vault, uint256 _vaultType, uint256 _vaultLatestUpdate, uint256 _roundId ) external view returns ( bool, uint256, uint256 ); } // File: contracts/interfaces/OracleInterface.sol interface OracleInterface { function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool); function getDisputer() external view returns (address); function getPricer(address _asset) external view returns (address); function getPrice(address _asset) external view returns (uint256); function getPricerLockingPeriod(address _pricer) external view returns (uint256); function getPricerDisputePeriod(address _pricer) external view returns (uint256); function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256); // Non-view function function setAssetPricer(address _asset, address _pricer) external; function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external; function setDisputePeriod(address _pricer, uint256 _disputePeriod) external; function setExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function disputeExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function setDisputer(address _disputer) external; } // File: contracts/interfaces/WhitelistInterface.sol interface WhitelistInterface { /* View functions */ function addressBook() external view returns (address); function isWhitelistedProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external view returns (bool); function isWhitelistedCollateral(address _collateral) external view returns (bool); function isWhitelistedOtoken(address _otoken) external view returns (bool); function isWhitelistedCallee(address _callee) external view returns (bool); /* Admin / factory only functions */ function whitelistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external; function blacklistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external; function whitelistCollateral(address _collateral) external; function blacklistCollateral(address _collateral) external; function whitelistOtoken(address _otoken) external; function blacklistOtoken(address _otoken) external; function whitelistCallee(address _callee) external; function blacklistCallee(address _callee) external; } // File: contracts/interfaces/MarginPoolInterface.sol interface MarginPoolInterface { /* Getters */ function addressBook() external view returns (address); function farmer() external view returns (address); function getStoredBalance(address _asset) external view returns (uint256); /* Admin-only functions */ function setFarmer(address _farmer) external; function farm( address _asset, address _receiver, uint256 _amount ) external; /* Controller-only functions */ function transferToPool( address _asset, address _user, uint256 _amount ) external; function transferToUser( address _asset, address _user, uint256 _amount ) external; function batchTransferToPool( address[] calldata _asset, address[] calldata _user, uint256[] calldata _amount ) external; function batchTransferToUser( address[] calldata _asset, address[] calldata _user, uint256[] calldata _amount ) external; } // File: contracts/interfaces/CalleeInterface.sol /** * @dev Contract interface that can be called from Controller as a call action. */ interface CalleeInterface { /** * Allows users to send this contract arbitrary data. * @param _sender The msg.sender to Controller * @param _data Arbitrary data given by the sender */ function callFunction(address payable _sender, bytes memory _data) external; } // File: contracts/core/Controller.sol /** * Controller Error Codes * C1: sender is not full pauser * C2: sender is not partial pauser * C3: callee is not a whitelisted address * C4: system is partially paused * C5: system is fully paused * C6: msg.sender is not authorized to run action * C7: invalid addressbook address * C8: invalid owner address * C9: invalid input * C10: fullPauser cannot be set to address zero * C11: partialPauser cannot be set to address zero * C12: can not run actions for different owners * C13: can not run actions on different vaults * C14: invalid final vault state * C15: can not run actions on inexistent vault * C16: cannot deposit long otoken from this address * C17: otoken is not whitelisted to be used as collateral * C18: otoken used as collateral is already expired * C19: can not withdraw an expired otoken * C20: cannot deposit collateral from this address * C21: asset is not whitelisted to be used as collateral * C22: can not withdraw collateral from a vault with an expired short otoken * C23: otoken is not whitelisted to be minted * C24: can not mint expired otoken * C25: cannot burn from this address * C26: can not burn expired otoken * C27: otoken is not whitelisted to be redeemed * C28: can not redeem un-expired otoken * C29: asset prices not finalized yet * C30: can't settle vault with no otoken * C31: can not settle vault with un-expired otoken * C32: can not settle undercollateralized vault * C33: can not liquidate vault * C34: can not leave less than collateral dust * C35: invalid vault id * C36: cap amount should be greater than zero * C37: collateral exceed naked margin cap */ /** * @title Controller * @author Opyn Team * @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts */ contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe { using MarginVault for MarginVault.Vault; using SafeMath for uint256; AddressBookInterface public addressbook; WhitelistInterface public whitelist; OracleInterface public oracle; MarginCalculatorInterface public calculator; MarginPoolInterface public pool; ///@dev scale used in MarginCalculator uint256 internal constant BASE = 8; /// @notice address that has permission to partially pause the system, where system functionality is paused /// except redeem and settleVault address public partialPauser; /// @notice address that has permission to fully pause the system, where all system functionality is paused address public fullPauser; /// @notice True if all system functionality is paused other than redeem and settle vault bool public systemPartiallyPaused; /// @notice True if all system functionality is paused bool public systemFullyPaused; /// @notice True if a call action can only be executed to a whitelisted callee bool public callRestricted; /// @dev mapping between an owner address and the number of owner address vaults mapping(address => uint256) internal accountVaultCounter; /// @dev mapping between an owner address and a specific vault using a vault id mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults; /// @dev mapping between an account owner and their approved or unapproved account operators mapping(address => mapping(address => bool)) internal operators; /******************************************************************** V2.0.0 storage upgrade ******************************************************/ /// @dev mapping to map vault by each vault type, naked margin vault should be set to 1, spread/max loss vault should be set to 0 mapping(address => mapping(uint256 => uint256)) internal vaultType; /// @dev mapping to store the timestamp at which the vault was last updated, will be updated in every action that changes the vault state or when calling sync() mapping(address => mapping(uint256 => uint256)) internal vaultLatestUpdate; /// @dev mapping to store cap amount for naked margin vault per options collateral asset (scaled by collateral asset decimals) mapping(address => uint256) internal nakedCap; /// @dev mapping to store amount of naked margin vaults in pool mapping(address => uint256) internal nakedPoolBalance; /// @notice emits an event when an account operator is updated for a specific account owner event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet); /// @notice emits an event when a new vault is opened event VaultOpened(address indexed accountOwner, uint256 vaultId, uint256 indexed vaultType); /// @notice emits an event when a long oToken is deposited into a vault event LongOtokenDeposited( address indexed otoken, address indexed accountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when a long oToken is withdrawn from a vault event LongOtokenWithdrawed( address indexed otoken, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a collateral asset is deposited into a vault event CollateralAssetDeposited( address indexed asset, address indexed accountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when a collateral asset is withdrawn from a vault event CollateralAssetWithdrawed( address indexed asset, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a short oToken is minted from a vault event ShortOtokenMinted( address indexed otoken, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a short oToken is burned event ShortOtokenBurned( address indexed otoken, address indexed AccountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when an oToken is redeemed event Redeem( address indexed otoken, address indexed redeemer, address indexed receiver, address collateralAsset, uint256 otokenBurned, uint256 payout ); /// @notice emits an event when a vault is settled event VaultSettled( address indexed accountOwner, address indexed oTokenAddress, address to, uint256 payout, uint256 vaultId, uint256 indexed vaultType ); /// @notice emits an event when a vault is liquidated event VaultLiquidated( address indexed liquidator, address indexed receiver, address indexed vaultOwner, uint256 auctionPrice, uint256 auctionStartingRound, uint256 collateralPayout, uint256 debtAmount, uint256 vaultId ); /// @notice emits an event when a call action is executed event CallExecuted(address indexed from, address indexed to, bytes data); /// @notice emits an event when the fullPauser address changes event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser); /// @notice emits an event when the partialPauser address changes event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser); /// @notice emits an event when the system partial paused status changes event SystemPartiallyPaused(bool isPaused); /// @notice emits an event when the system fully paused status changes event SystemFullyPaused(bool isPaused); /// @notice emits an event when the call action restriction changes event CallRestricted(bool isRestricted); /// @notice emits an event when a donation transfer executed event Donated(address indexed donator, address indexed asset, uint256 amount); /// @notice emits an event when naked cap is updated event NakedCapUpdated(address indexed collateral, uint256 cap); /** * @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed */ modifier notPartiallyPaused() { _isNotPartiallyPaused(); _; } /** * @notice modifier to check if the system is not fully paused, where no functionality is allowed */ modifier notFullyPaused() { _isNotFullyPaused(); _; } /** * @notice modifier to check if sender is the fullPauser address */ modifier onlyFullPauser() { require(msg.sender == fullPauser, "C1"); _; } /** * @notice modifier to check if the sender is the partialPauser address */ modifier onlyPartialPauser() { require(msg.sender == partialPauser, "C2"); _; } /** * @notice modifier to check if the sender is the account owner or an approved account operator * @param _sender sender address * @param _accountOwner account owner address */ modifier onlyAuthorized(address _sender, address _accountOwner) { _isAuthorized(_sender, _accountOwner); _; } /** * @notice modifier to check if the called address is a whitelisted callee address * @param _callee called address */ modifier onlyWhitelistedCallee(address _callee) { if (callRestricted) { require(_isCalleeWhitelisted(_callee), "C3"); } _; } /** * @dev check if the system is not in a partiallyPaused state */ function _isNotPartiallyPaused() internal view { require(!systemPartiallyPaused, "C4"); } /** * @dev check if the system is not in an fullyPaused state */ function _isNotFullyPaused() internal view { require(!systemFullyPaused, "C5"); } /** * @dev check if the sender is an authorized operator * @param _sender msg.sender * @param _accountOwner owner of a vault */ function _isAuthorized(address _sender, address _accountOwner) internal view { require((_sender == _accountOwner) || (operators[_accountOwner][_sender]), "C6"); } /** * @notice initalize the deployed contract * @param _addressBook addressbook module * @param _owner account owner address */ function initialize(address _addressBook, address _owner) external initializer { require(_addressBook != address(0), "C7"); require(_owner != address(0), "C8"); __Ownable_init(_owner); __ReentrancyGuard_init_unchained(); addressbook = AddressBookInterface(_addressBook); _refreshConfigInternal(); callRestricted = true; } /** * @notice send asset amount to margin pool * @dev use donate() instead of direct transfer() to store the balance in assetBalance * @param _asset asset address * @param _amount amount to donate to pool */ function donate(address _asset, uint256 _amount) external { pool.transferToPool(_asset, msg.sender, _amount); emit Donated(msg.sender, _asset, _amount); } /** * @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system * @dev can only be called by the partialPauser * @param _partiallyPaused new boolean value to set systemPartiallyPaused to */ function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser { require(systemPartiallyPaused != _partiallyPaused, "C9"); systemPartiallyPaused = _partiallyPaused; emit SystemPartiallyPaused(systemPartiallyPaused); } /** * @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system * @dev can only be called by the fullyPauser * @param _fullyPaused new boolean value to set systemFullyPaused to */ function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser { require(systemFullyPaused != _fullyPaused, "C9"); systemFullyPaused = _fullyPaused; emit SystemFullyPaused(systemFullyPaused); } /** * @notice allows the owner to set the fullPauser address * @dev can only be called by the owner * @param _fullPauser new fullPauser address */ function setFullPauser(address _fullPauser) external onlyOwner { require(_fullPauser != address(0), "C10"); require(fullPauser != _fullPauser, "C9"); emit FullPauserUpdated(fullPauser, _fullPauser); fullPauser = _fullPauser; } /** * @notice allows the owner to set the partialPauser address * @dev can only be called by the owner * @param _partialPauser new partialPauser address */ function setPartialPauser(address _partialPauser) external onlyOwner { require(_partialPauser != address(0), "C11"); require(partialPauser != _partialPauser, "C9"); emit PartialPauserUpdated(partialPauser, _partialPauser); partialPauser = _partialPauser; } /** * @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted * call addresses or allow any arbitrary call addresses * @dev can only be called by the owner * @param _isRestricted new call restriction state */ function setCallRestriction(bool _isRestricted) external onlyOwner { require(callRestricted != _isRestricted, "C9"); callRestricted = _isRestricted; emit CallRestricted(callRestricted); } /** * @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults * @dev can only be updated by the vault owner * @param _operator operator that the sender wants to give privileges to or revoke them from * @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator */ function setOperator(address _operator, bool _isOperator) external { require(operators[msg.sender][_operator] != _isOperator, "C9"); operators[msg.sender][_operator] = _isOperator; emit AccountOperatorUpdated(msg.sender, _operator, _isOperator); } /** * @dev updates the configuration of the controller. can only be called by the owner */ function refreshConfiguration() external onlyOwner { _refreshConfigInternal(); } /** * @notice set cap amount for collateral asset used in naked margin * @dev can only be called by owner * @param _collateral collateral asset address * @param _cap cap amount, should be scaled by collateral asset decimals */ function setNakedCap(address _collateral, uint256 _cap) external onlyOwner { require(_cap > 0, "C36"); nakedCap[_collateral] = _cap; emit NakedCapUpdated(_collateral, _cap); } /** * @notice execute a number of actions on specific vaults * @dev can only be called when the system is not fully paused * @param _actions array of actions arguments */ function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused { (bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions); if (vaultUpdated) { _verifyFinalState(vaultOwner, vaultId); vaultLatestUpdate[vaultOwner][vaultId] = now; } } /** * @notice sync vault latest update timestamp * @dev anyone can update the latest time the vault was touched by calling this function * vaultLatestUpdate will sync if the vault is well collateralized * @param _owner vault owner address * @param _vaultId vault id */ function sync(address _owner, uint256 _vaultId) external nonReentrant notFullyPaused { _verifyFinalState(_owner, _vaultId); vaultLatestUpdate[_owner][_vaultId] = now; } /** * @notice check if a specific address is an operator for an owner account * @param _owner account owner address * @param _operator account operator address * @return True if the _operator is an approved operator for the _owner account */ function isOperator(address _owner, address _operator) external view returns (bool) { return operators[_owner][_operator]; } /** * @notice returns the current controller configuration * @return whitelist, the address of the whitelist module * @return oracle, the address of the oracle module * @return calculator, the address of the calculator module * @return pool, the address of the pool module */ function getConfiguration() external view returns ( address, address, address, address ) { return (address(whitelist), address(oracle), address(calculator), address(pool)); } /** * @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault * @param _owner account owner of the vault * @param _vaultId vaultId to return balances for * @return amount of collateral that can be taken out */ function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (uint256 netValue, bool isExcess) = calculator.getExcessCollateral(vault, typeVault); if (!isExcess) return 0; return netValue; } /** * @notice check if a vault is liquidatable in a specific round id * @param _owner vault owner address * @param _vaultId vault id to check * @param _roundId chainlink round id to check vault status at * @return isUnderCollat, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount */ function isLiquidatable( address _owner, uint256 _vaultId, uint256 _roundId ) external view returns ( bool, uint256, uint256 ) { (, bool isUnderCollat, uint256 price, uint256 dust) = _isLiquidatable(_owner, _vaultId, _roundId); return (isUnderCollat, price, dust); } /** * @notice get an oToken's payout/cash value after expiry, in the collateral asset * @param _otoken oToken address * @param _amount amount of the oToken to calculate the payout for, always represented in 1e8 * @return amount of collateral to pay out */ function getPayout(address _otoken, uint256 _amount) public view returns (uint256) { return calculator.getExpiredPayoutRate(_otoken).mul(_amount).div(10**BASE); } /** * @dev return if an expired oToken is ready to be settled, only true when price for underlying, * strike and collateral assets at this specific expiry is available in our Oracle module * @param _otoken oToken */ function isSettlementAllowed(address _otoken) external view returns (bool) { (address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken); return _canSettleAssets(underlying, strike, collateral, expiry); } /** * @dev return if underlying, strike, collateral are all allowed to be settled * @param _underlying oToken underlying asset * @param _strike oToken strike asset * @param _collateral oToken collateral asset * @param _expiry otoken expiry timestamp * @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not */ function canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool) { return _canSettleAssets(_underlying, _strike, _collateral, _expiry); } /** * @notice get the number of vaults for a specified account owner * @param _accountOwner account owner address * @return number of vaults */ function getAccountVaultCounter(address _accountOwner) external view returns (uint256) { return accountVaultCounter[_accountOwner]; } /** * @notice check if an oToken has expired * @param _otoken oToken address * @return True if the otoken has expired, False if not */ function hasExpired(address _otoken) external view returns (bool) { return now >= OtokenInterface(_otoken).expiryTimestamp(); } /** * @notice return a specific vault * @param _owner account owner * @param _vaultId vault id of vault to return * @return Vault struct that corresponds to the _vaultId of _owner */ function getVault(address _owner, uint256 _vaultId) external view returns (MarginVault.Vault memory) { return (vaults[_owner][_vaultId]); } /** * @notice return a specific vault * @param _owner account owner * @param _vaultId vault id of vault to return * @return Vault struct that corresponds to the _vaultId of _owner, vault type and the latest timestamp when the vault was updated */ function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return (vaults[_owner][_vaultId], vaultType[_owner][_vaultId], vaultLatestUpdate[_owner][_vaultId]); } /** * @notice get cap amount for collateral asset * @param _asset collateral asset address * @return cap amount */ function getNakedCap(address _asset) external view returns (uint256) { return nakedCap[_asset]; } /** * @notice get amount of collateral deposited in all naked margin vaults * @param _asset collateral asset address * @return naked pool balance */ function getNakedPoolBalance(address _asset) external view returns (uint256) { return nakedPoolBalance[_asset]; } /** * @notice execute a variety of actions * @dev for each action in the action array, execute the corresponding action, only one vault can be modified * for all actions except SettleVault, Redeem, and Call * @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute * @return vaultUpdated, indicates if a vault has changed * @return owner, the vault owner if a vault has changed * @return vaultId, the vault Id if a vault has changed */ function _runActions(Actions.ActionArgs[] memory _actions) internal returns ( bool, address, uint256 ) { address vaultOwner; uint256 vaultId; bool vaultUpdated; for (uint256 i = 0; i < _actions.length; i++) { Actions.ActionArgs memory action = _actions[i]; Actions.ActionType actionType = action.actionType; // actions except Settle, Redeem, Liquidate and Call are "Vault-updating actinos" // only allow update 1 vault in each operate call if ( (actionType != Actions.ActionType.SettleVault) && (actionType != Actions.ActionType.Redeem) && (actionType != Actions.ActionType.Liquidate) && (actionType != Actions.ActionType.Call) ) { // check if this action is manipulating the same vault as all other actions, if a vault has already been updated if (vaultUpdated) { require(vaultOwner == action.owner, "C12"); require(vaultId == action.vaultId, "C13"); } vaultUpdated = true; vaultId = action.vaultId; vaultOwner = action.owner; } if (actionType == Actions.ActionType.OpenVault) { _openVault(Actions._parseOpenVaultArgs(action)); } else if (actionType == Actions.ActionType.DepositLongOption) { _depositLong(Actions._parseDepositArgs(action)); } else if (actionType == Actions.ActionType.WithdrawLongOption) { _withdrawLong(Actions._parseWithdrawArgs(action)); } else if (actionType == Actions.ActionType.DepositCollateral) { _depositCollateral(Actions._parseDepositArgs(action)); } else if (actionType == Actions.ActionType.WithdrawCollateral) { _withdrawCollateral(Actions._parseWithdrawArgs(action)); } else if (actionType == Actions.ActionType.MintShortOption) { _mintOtoken(Actions._parseMintArgs(action)); } else if (actionType == Actions.ActionType.BurnShortOption) { _burnOtoken(Actions._parseBurnArgs(action)); } else if (actionType == Actions.ActionType.Redeem) { _redeem(Actions._parseRedeemArgs(action)); } else if (actionType == Actions.ActionType.SettleVault) { _settleVault(Actions._parseSettleVaultArgs(action)); } else if (actionType == Actions.ActionType.Liquidate) { _liquidate(Actions._parseLiquidateArgs(action)); } else if (actionType == Actions.ActionType.Call) { _call(Actions._parseCallArgs(action)); } } return (vaultUpdated, vaultOwner, vaultId); } /** * @notice verify the vault final state after executing all actions * @param _owner account owner address * @param _vaultId vault id of the final vault */ function _verifyFinalState(address _owner, uint256 _vaultId) internal view { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); require(isValidVault, "C14"); } /** * @notice open a new vault inside an account * @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused * @param _args OpenVaultArgs structure */ function _openVault(Actions.OpenVaultArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { uint256 vaultId = accountVaultCounter[_args.owner].add(1); require(_args.vaultId == vaultId, "C15"); // store new vault accountVaultCounter[_args.owner] = vaultId; vaultType[_args.owner][vaultId] = _args.vaultType; emit VaultOpened(_args.owner, vaultId, _args.vaultType); } /** * @notice deposit a long oToken into a vault * @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args DepositArgs structure */ function _depositLong(Actions.DepositArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to deposit long otoken require((_args.from == msg.sender) || (_args.from == _args.owner), "C16"); require(whitelist.isWhitelistedOtoken(_args.asset), "C17"); OtokenInterface otoken = OtokenInterface(_args.asset); require(now < otoken.expiryTimestamp(), "C18"); vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index); pool.transferToPool(_args.asset, _args.from, _args.amount); emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice withdraw a long oToken from a vault * @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args WithdrawArgs structure */ function _withdrawLong(Actions.WithdrawArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); OtokenInterface otoken = OtokenInterface(_args.asset); require(now < otoken.expiryTimestamp(), "C19"); vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index); pool.transferToUser(_args.asset, _args.to, _args.amount); emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice deposit a collateral asset into a vault * @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused * @param _args DepositArgs structure */ function _depositCollateral(Actions.DepositArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to deposit collateral require((_args.from == msg.sender) || (_args.from == _args.owner), "C20"); require(whitelist.isWhitelistedCollateral(_args.asset), "C21"); (, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); if (typeVault == 1) { nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].add(_args.amount); require(nakedPoolBalance[_args.asset] <= nakedCap[_args.asset], "C37"); } vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index); pool.transferToPool(_args.asset, _args.from, _args.amount); emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice withdraw a collateral asset from a vault * @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused * @param _args WithdrawArgs structure */ function _withdrawCollateral(Actions.WithdrawArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); if (_isNotEmpty(vault.shortOtokens)) { OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]); require(now < otoken.expiryTimestamp(), "C22"); } if (typeVault == 1) { nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].sub(_args.amount); } vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index); pool.transferToUser(_args.asset, _args.to, _args.amount); emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault * @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args MintArgs structure */ function _mintOtoken(Actions.MintArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); require(whitelist.isWhitelistedOtoken(_args.otoken), "C23"); OtokenInterface otoken = OtokenInterface(_args.otoken); require(now < otoken.expiryTimestamp(), "C24"); vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index); otoken.mintOtoken(_args.to, _args.amount); emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault * @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args MintArgs structure */ function _burnOtoken(Actions.BurnArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { // check that vault id is valid for this vault owner require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to burn otoken require((_args.from == msg.sender) || (_args.from == _args.owner), "C25"); OtokenInterface otoken = OtokenInterface(_args.otoken); // do not allow burning expired otoken require(now < otoken.expiryTimestamp(), "C26"); // remove otoken from vault vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index); // burn otoken otoken.burnOtoken(_args.from, _args.amount); emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset * @dev cannot be called when system is fullyPaused * @param _args RedeemArgs structure */ function _redeem(Actions.RedeemArgs memory _args) internal { OtokenInterface otoken = OtokenInterface(_args.otoken); // check that otoken to redeem is whitelisted require(whitelist.isWhitelistedOtoken(_args.otoken), "C27"); (address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken)); // only allow redeeming expired otoken require(now >= expiry, "C28"); require(_canSettleAssets(underlying, strike, collateral, expiry), "C29"); uint256 payout = getPayout(_args.otoken, _args.amount); otoken.burnOtoken(msg.sender, _args.amount); pool.transferToUser(collateral, _args.receiver, payout); emit Redeem(_args.otoken, msg.sender, _args.receiver, collateral, _args.amount, payout); } /** * @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled * @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused * @param _args SettleVaultArgs structure */ function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); OtokenInterface otoken; // new scope to avoid stack too deep error // check if there is short or long otoken in vault // do not allow settling vault that have no short or long otoken // if there is a long otoken, burn it // store otoken address outside of this scope { bool hasShort = _isNotEmpty(vault.shortOtokens); bool hasLong = _isNotEmpty(vault.longOtokens); require(hasShort || hasLong, "C30"); otoken = hasShort ? OtokenInterface(vault.shortOtokens[0]) : OtokenInterface(vault.longOtokens[0]); if (hasLong) { OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]); longOtoken.burnOtoken(address(pool), vault.longAmounts[0]); } } (address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken)); // do not allow settling vault with un-expired otoken require(now >= expiry, "C31"); require(_canSettleAssets(underlying, strike, collateral, expiry), "C29"); (uint256 payout, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); // require that vault is valid (has excess collateral) before settling // to avoid allowing settling undercollateralized naked margin vault require(isValidVault, "C32"); delete vaults[_args.owner][_args.vaultId]; if (typeVault == 1) { nakedPoolBalance[collateral] = nakedPoolBalance[collateral].sub(payout); } pool.transferToUser(collateral, _args.to, payout); uint256 vaultId = _args.vaultId; address payoutRecipient = _args.to; emit VaultSettled(_args.owner, address(otoken), payoutRecipient, payout, vaultId, typeVault); } /** * @notice liquidate naked margin vault * @dev can liquidate different vaults id in the same operate() call * @param _args liquidation action arguments struct */ function _liquidate(Actions.LiquidateArgs memory _args) internal notPartiallyPaused { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // check if vault is undercollateralized // the price is the amount of collateral asset to pay per 1 repaid debt(otoken) // collateralDust is the minimum amount of collateral that can be left in the vault when a partial liquidation occurs (MarginVault.Vault memory vault, bool isUnderCollat, uint256 price, uint256 collateralDust) = _isLiquidatable( _args.owner, _args.vaultId, _args.roundId ); require(isUnderCollat, "C33"); // amount of collateral to offer to liquidator uint256 collateralToSell = _args.amount.mul(price).div(1e8); // if vault is partially liquidated (amount of short otoken is still greater than zero) // make sure remaining collateral amount is greater than dust amount if (vault.shortAmounts[0].sub(_args.amount) > 0) { require(vault.collateralAmounts[0].sub(collateralToSell) >= collateralDust, "C34"); } // burn short otoken from liquidator address, index of short otoken hardcoded at 0 // this should always work, if vault have no short otoken, it will not reach this step OtokenInterface(vault.shortOtokens[0]).burnOtoken(msg.sender, _args.amount); // decrease amount of collateral in liquidated vault, index of collateral to decrease is hardcoded at 0 vaults[_args.owner][_args.vaultId].removeCollateral(vault.collateralAssets[0], collateralToSell, 0); // decrease amount of short otoken in liquidated vault, index of short otoken to decrease is hardcoded at 0 vaults[_args.owner][_args.vaultId].removeShort(vault.shortOtokens[0], _args.amount, 0); // decrease internal naked margin collateral amount nakedPoolBalance[vault.collateralAssets[0]] = nakedPoolBalance[vault.collateralAssets[0]].sub(collateralToSell); pool.transferToUser(vault.collateralAssets[0], _args.receiver, collateralToSell); emit VaultLiquidated( msg.sender, _args.receiver, _args.owner, price, _args.roundId, collateralToSell, _args.amount, _args.vaultId ); } /** * @notice execute arbitrary calls * @dev cannot be called when system is partiallyPaused or fullyPaused * @param _args Call action */ function _call(Actions.CallArgs memory _args) internal notPartiallyPaused onlyWhitelistedCallee(_args.callee) { CalleeInterface(_args.callee).callFunction(msg.sender, _args.data); emit CallExecuted(msg.sender, _args.callee, _args.data); } /** * @notice check if a vault id is valid for a given account owner address * @param _accountOwner account owner address * @param _vaultId vault id to check * @return True if the _vaultId is valid, False if not */ function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) { return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner])); } function _isNotEmpty(address[] memory _array) internal pure returns (bool) { return (_array.length > 0) && (_array[0] != address(0)); } /** * @notice return if a callee address is whitelisted or not * @param _callee callee address * @return True if callee address is whitelisted, False if not */ function _isCalleeWhitelisted(address _callee) internal view returns (bool) { return whitelist.isWhitelistedCallee(_callee); } /** * @notice check if a vault is liquidatable in a specific round id * @param _owner vault owner address * @param _vaultId vault id to check * @param _roundId chainlink round id to check vault status at * @return vault struct, isLiquidatable, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount */ function _isLiquidatable( address _owner, uint256 _vaultId, uint256 _roundId ) internal view returns ( MarginVault.Vault memory, bool, uint256, uint256 ) { (MarginVault.Vault memory vault, uint256 typeVault, uint256 latestUpdateTimestamp) = getVaultWithDetails( _owner, _vaultId ); (bool isUnderCollat, uint256 price, uint256 collateralDust) = calculator.isLiquidatable( vault, typeVault, latestUpdateTimestamp, _roundId ); return (vault, isUnderCollat, price, collateralDust); } /** * @dev get otoken detail, from both otoken versions */ function _getOtokenDetails(address _otoken) internal view returns ( address, address, address, uint256 ) { OtokenInterface otoken = OtokenInterface(_otoken); try otoken.getOtokenDetails() returns ( address collateral, address underlying, address strike, uint256, uint256 expiry, bool ) { return (collateral, underlying, strike, expiry); } catch { return (otoken.collateralAsset(), otoken.underlyingAsset(), otoken.strikeAsset(), otoken.expiryTimestamp()); } } /** * @dev return if an expired oToken is ready to be settled, only true when price for underlying, * strike and collateral assets at this specific expiry is available in our Oracle module * @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not */ function _canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) internal view returns (bool) { return oracle.isDisputePeriodOver(_underlying, _expiry) && oracle.isDisputePeriodOver(_strike, _expiry) && oracle.isDisputePeriodOver(_collateral, _expiry); } /** * @dev updates the internal configuration of the controller */ function _refreshConfigInternal() internal { whitelist = WhitelistInterface(addressbook.getWhitelist()); oracle = OracleInterface(addressbook.getOracle()); calculator = MarginCalculatorInterface(addressbook.getMarginCalculator()); pool = MarginPoolInterface(addressbook.getMarginPool()); } }
* @notice verify the vault final state after executing all actions @param _owner account owner address @param _vaultId vault id of the final vault/
function _verifyFinalState(address _owner, uint256 _vaultId) internal view { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); require(isValidVault, "C14"); }
6,146,105
[ 1, 8705, 326, 9229, 727, 919, 1839, 11274, 777, 4209, 225, 389, 8443, 2236, 3410, 1758, 225, 389, 26983, 548, 9229, 612, 434, 326, 727, 9229, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8705, 7951, 1119, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 26983, 548, 13, 2713, 1476, 288, 203, 3639, 261, 9524, 12003, 18, 12003, 3778, 9229, 16, 2254, 5034, 618, 12003, 16, 262, 273, 11031, 3714, 1190, 3790, 24899, 8443, 16, 389, 26983, 548, 1769, 203, 3639, 261, 16, 1426, 4908, 12003, 13, 273, 15497, 18, 588, 424, 614, 13535, 2045, 287, 12, 26983, 16, 618, 12003, 1769, 203, 203, 3639, 2583, 12, 26810, 12003, 16, 315, 39, 3461, 8863, 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 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./interfaces/IPriceOracleProxy.sol"; import "./interfaces/IFantomMintAddressProvider.sol"; import "./interfaces/IFantomMintTokenRegistry.sol"; import "./interfaces/IFantomDeFiTokenStorage.sol"; import "./interfaces/IFantomMintRewardManager.sol"; import "./modules/FantomMintErrorCodes.sol"; import "./modules/FantomMintBalanceGuard.sol"; import "./modules/FantomMintCollateral.sol"; import "./modules/FantomMintDebt.sol"; import "./modules/FantomMintConfig.sol"; // FantomMint implements the contract of core DeFi function // for minting tokens against a deposited collateral. The collateral // management is linked from the Fantom Collateral implementation. // Minting is burdened with a minting fee defined as the amount // of percent of the minted tokens value in fUSD. Burning is free // of any fee. contract FantomMint is Initializable, FantomMintBalanceGuard, FantomMintCollateral, FantomMintDebt, FantomMintConfig { // define used libs using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; // ---------------------------- // Fantom minter configuration // ---------------------------- // addressProvider represents the connection to other FMint related // contracts. IFantomMintAddressProvider public addressProvider; // initialize initializes the contract properly before the first use. function initialize(address owner, address _addressProvider) public initializer { // remember the address provider connecting satellite contracts to the minter addressProvider = IFantomMintAddressProvider(_addressProvider); // init the underlying party FantomMintConfig.initialize(owner); FantomMintCollateral.initialize(); FantomMintDebt.initialize(); } // ------------------------------------------------------------- // Minter parameters resolved from the Config contract // ------------------------------------------------------------- // getCollateralLowestDebtRatio4dec represents the lowest ratio between // collateral value and debt value allowed for the user. // User can not withdraw his collateral if the active ratio would // drop below this value. function getCollateralLowestDebtRatio4dec() public view returns (uint256) { return collateralLowestDebtRatio4dec; } // getRewardEligibilityRatio4dec represents the collateral to debt ratio user has to have // to be able to receive rewards. function getRewardEligibilityRatio4dec() public view returns (uint256) { return rewardEligibilityRatio4dec; } // getFMintFee4dec represents the current percentage of the created tokens // captured as a fee. function getFMintFee4dec() public view returns (uint256) { return fMintFee4dec; } // getMinDebtValue returns the minimum debt value. function getMinDebtValue() public view returns (uint256) { return minDebtValue; } // ------------------------------------------------------------- // Pool balances and values // ------------------------------------------------------------- // getCollateralPool returns the address of collateral pool. function getCollateralPool() public view returns (IFantomDeFiTokenStorage) { return addressProvider.getCollateralPool(); } // getDebtPool returns the address of debt pool. function getDebtPool() public view returns (IFantomDeFiTokenStorage) { return addressProvider.getDebtPool(); } // canDeposit checks if the given token can be deposited to the collateral pool. function canDeposit(address _token) public view returns (bool) { return addressProvider.getTokenRegistry().canDeposit(_token); } // canMint checks if the given token can be minted in the fMint protocol. function canMint(address _token) public view returns (bool) { return addressProvider.getTokenRegistry().canMint(_token); } // checkCollateralCanDecrease checks if the specified amount of collateral can be removed from account // without breaking collateral to debt ratio rule. function checkCollateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool) { return collateralCanDecrease(_account, _token, _amount); } // checkDebtCanIncrease (abstract) checks if the specified // amount of debt can be added to the account // without breaking collateral to debt ratio rule. function checkDebtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool) { return debtCanIncrease(_account, _token, _amount); } // debtValueOf returns the value of account debt. function debtValueOf(address _account, address _token, uint256 _add) public view returns (uint256) { // do we have a request to calculate increased debt value? if ((0 != _add) && (address(0x0) != _token)) { // return current value with increased balance on given token return addressProvider.getDebtPool().totalOfInc(_account, _token, _add); } // return current debt value as-is return addressProvider.getDebtPool().totalOf(_account); } // collateralValueOf returns the value of account collateral. function collateralValueOf(address _account, address _token, uint256 _sub) public view returns (uint256) { // do we have a request to calculate decreased collateral value? if ((0 != _sub) && (address(0x0) != _token)) { // return current value with reduced balance on given token return addressProvider.getCollateralPool().totalOfDec(_account, _token, _sub); } // return current collateral value as-is return addressProvider.getCollateralPool().totalOf(_account); } // getMaxToWithdraw returns the max amount of tokens to withdraw with the given ratio. function getMaxToWithdraw(address _account, address _token, uint256 _ratio) public view returns (uint256) { return maxToWithdraw(_account, _token, _ratio); } // getMaxToMint returns the max amount of tokens to mint with the given ratio. function getMaxToMint(address _account, address _token, uint256 _ratio) public view returns (uint256) { return maxToMint(_account, _token, _ratio); } // ------------------------------------------------------------- // Reward update events routing // ------------------------------------------------------------- // rewardUpdate notifies the reward distribution to update state // of the given account. function rewardUpdate(address _account) public { addressProvider.getRewardDistribution().rewardUpdate(_account); } // ------------------------------------------------------------- // Token price calculation functions // ------------------------------------------------------------- // getPrice returns the price of given ERC20 token using on-chain oracle // expression of an exchange rate between the token and base denomination. function getPrice(address _token) public view returns (uint256) { // use linked price oracle aggregate to get the token exchange price return addressProvider.getPriceOracleProxy().getPrice(_token); } // getExtendedPrice returns the price of given ERC20 token using on-chain oracle // expression of an exchange rate between the token and base denomination and also // the number of digits of the price. function getExtendedPrice(address _token) public view returns (uint256 _price, uint256 _digits) { // use linked price oracle aggregate to get the token exchange price _price = addressProvider.getPriceOracleProxy().getPrice(_token); _digits = 10 ** uint256(addressProvider.getTokenRegistry().priceDecimals(_token)); return (_price, _digits); } modifier onlyLiquidationManager() { require(msg.sender == address(addressProvider.getFantomLiquidationManager()), "token storage access restricted"); _; } function settleLiquidationBid(address _token, address _destination, uint256 _amount) public onlyLiquidationManager { ERC20(_token).transfer(_destination, _amount); } }
getCollateralLowestDebtRatio4dec represents the lowest ratio between collateral value and debt value allowed for the user. User can not withdraw his collateral if the active ratio would drop below this value.
function getCollateralLowestDebtRatio4dec() public view returns (uint256) { return collateralLowestDebtRatio4dec; }
13,127,156
[ 1, 588, 13535, 2045, 287, 10520, 395, 758, 23602, 8541, 24, 4924, 8686, 326, 11981, 7169, 3086, 4508, 2045, 287, 460, 471, 18202, 88, 460, 2935, 364, 326, 729, 18, 2177, 848, 486, 598, 9446, 18423, 4508, 2045, 287, 309, 326, 2695, 7169, 4102, 3640, 5712, 333, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 336, 13535, 2045, 287, 10520, 395, 758, 23602, 8541, 24, 4924, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 4508, 2045, 287, 10520, 395, 758, 23602, 8541, 24, 4924, 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 ]
./full_match/1/0x46b13E7E8f1aEF156973AE3eD975E738cAFB08C8/sources/contracts/storage/PoolStorage.sol
* @notice The fee charged when swapping synthetic tokens @dev Use 18 decimals (e.g. 1e16 = 1%)/
uint256 public swapFee;
3,134,091
[ 1, 1986, 14036, 1149, 2423, 1347, 7720, 1382, 25535, 2430, 225, 2672, 6549, 15105, 261, 73, 18, 75, 18, 404, 73, 2313, 273, 404, 9, 13176, 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, 2254, 5034, 1071, 7720, 14667, 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.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./library/ERC1155.sol"; import "./library/ERC1155MintBurn.sol"; import "./library/ERC1155Metadata.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title PiArtTradablePrivate * PiArtTradablePrivate - ERC1155 contract that whitelists an operator address, * has mint functionality, and supports useful standards from OpenZeppelin, like _exists(), name(), symbol(), and totalSupply() */ contract PiArtTradablePrivate is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable { uint256 private _currentTokenID = 0; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; // Contract name string public name; // Contract symbol string public symbol; // Platform fee uint256 public platformFee; // Platform fee receipient address payable public feeReceipient; // Pi Marketplace contract address marketplace; // Pi Bundle Marketplace contract address bundleMarketplace; constructor( string memory _name, string memory _symbol, uint256 _platformFee, address payable _feeReceipient, address _marketplace, address _bundleMarketplace ) public { name = _name; symbol = _symbol; platformFee = _platformFee; feeReceipient = _feeReceipient; marketplace = _marketplace; bundleMarketplace = _bundleMarketplace; } function uri(uint256 _id) public view override returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return _tokenURIs[_id]; } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Creates a new token type and assigns _supply to an address * @param _to owner address of the new token * @param _supply Optional amount to supply the first owner * @param _uri Optional URI for this token type */ function mint( address _to, uint256 _supply, string calldata _uri ) external payable onlyOwner { require(msg.value >= platformFee, "Insufficient funds to mint."); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; _setTokenURI(_id, _uri); if (bytes(_uri).length > 0) { emit URI(_uri, _id); } _mint(_to, _id, _supply, bytes("")); tokenSupply[_id] = _supply; // Send ETH fee to fee recipient (bool success, ) = feeReceipient.call{value: msg.value}(""); require(success, "Transfer failed"); } function getCurrentTokenID() public view returns (uint256) { return _currentTokenID; } /** * Override isApprovedForAll to whitelist Pi contracts to enable gas-less listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist Pi marketplace, bundle marketplace contracts for easy trading. if (marketplace == _operator || bundleMarketplace == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) public view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param _id uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _id, string memory _uri) internal { require(_exists(_id), "_setTokenURI: Token should exist"); _tokenURIs[_id] = _uri; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; import './IERC165.sol'; import './IERC1155TokenReceiver.sol'; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; // Events event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _uri, uint256 indexed _id); /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator Bool of approved for all */ function isApprovedForAll(address _owner, address _operator) public view virtual returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) external view override returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } pragma solidity 0.6.12; import './ERC1155.sol'; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } pragma solidity 0.6.12; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view virtual returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } } // 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; } } pragma solidity 0.6.12; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } pragma solidity 0.6.12; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
* @dev ERC-1155 interface for accepting safe transfers./
interface IERC1155TokenReceiver { function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); function supportsInterface(bytes4 interfaceID) external view returns (bool); } }
145,490
[ 1, 654, 39, 17, 2499, 2539, 1560, 364, 25806, 4183, 29375, 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 ]
[ 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, 5831, 467, 654, 39, 2499, 2539, 1345, 12952, 288, 203, 203, 225, 445, 603, 654, 39, 2499, 2539, 8872, 12, 2867, 389, 9497, 16, 1758, 389, 2080, 16, 2254, 5034, 389, 350, 16, 2254, 5034, 389, 8949, 16, 1731, 745, 892, 389, 892, 13, 3903, 1135, 12, 3890, 24, 1769, 203, 203, 225, 445, 603, 654, 39, 2499, 2539, 4497, 8872, 12, 2867, 389, 9497, 16, 1758, 389, 2080, 16, 2254, 5034, 8526, 745, 892, 389, 2232, 16, 2254, 5034, 8526, 745, 892, 389, 8949, 87, 16, 1731, 745, 892, 389, 892, 13, 3903, 1135, 12, 3890, 24, 1769, 203, 203, 225, 445, 6146, 1358, 12, 3890, 24, 1560, 734, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 97, 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 ]
/* ・ * ★ ・ 。  ・ ゚☆ 。     * ★ ゚・。 * 。   * ☆ 。・゚*.。    ゚ *.。☆。★ ・ ​ ` .-:::::-.` `-::---...``` `-:` .:+ssssoooo++//:.` .-/+shhhhhhhhhhhhhyyyssooo: .--::. .+ossso+/////++/:://-` .////+shhhhhhhhhhhhhhhhhhhhhy `-----::. `/+////+++///+++/:--:/+/- -////+shhhhhhhhhhhhhhhhhhhhhy `------:::-` `//-.``.-/+ooosso+:-.-/oso- -////+shhhhhhhhhhhhhhhhhhhhhy .--------:::-` :+:.` .-/osyyyyyyso++syhyo.-////+shhhhhhhhhhhhhhhhhhhhhy `-----------:::-. +o+:-.-:/oyhhhhhhdhhhhhdddy:-////+shhhhhhhhhhhhhhhhhhhhhy .------------::::-- `oys+/::/+shhhhhhhdddddddddy/-////+shhhhhhhhhhhhhhhhhhhhhy .--------------:::::-` +ys+////+yhhhhhhhddddddddhy:-////+yhhhhhhhhhhhhhhhhhhhhhy `----------------::::::-`.ss+/:::+oyhhhhhhhhhhhhhhho`-////+shhhhhhhhhhhhhhhhhhhhhy .------------------:::::::.-so//::/+osyyyhhhhhhhhhys` -////+shhhhhhhhhhhhhhhhhhhhhy `.-------------------::/:::::..+o+////+oosssyyyyyyys+` .////+shhhhhhhhhhhhhhhhhhhhhy .--------------------::/:::.` -+o++++++oooosssss/. `-//+shhhhhhhhhhhhhhhhhhhhyo .------- ``````.......--` `-/+ooooosso+/-` `./++++///:::--...``hhhhyo ````` *  ・ 。     ・  ゚☆ 。     * ★ ゚・。 * 。   * ☆ 。・゚*.。    ゚ *.。☆。★ ・ *  ゚。·*・。 ゚*    ☆゚・。°*. ゚   ・ ゚*。・゚★。   ・ *゚。   *  ・゚*。★・ ☆∴。 * ・ 。 */ // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-solc-8/proxy/Clones.sol"; import "@openzeppelin/contracts-solc-8/utils/Address.sol"; import "@openzeppelin/contracts-solc-8/utils/Strings.sol"; import "./interfaces/solc8/ICollectionContractInitializer.sol"; import "./interfaces/solc8/IRoles.sol"; import "./interfaces/solc8/ICollectionFactory.sol"; import "./interfaces/solc8/IProxyCall.sol"; /** * @title A factory to create NFT collections. * @notice Call this factory to create and initialize a minimal proxy pointing to the NFT collection contract. */ contract FNDCollectionFactory is ICollectionFactory { using Address for address; using Address for address payable; using Clones for address; using Strings for uint256; /** * @notice The contract address which manages common roles. * @dev Used by the collections for a shared operator definition. */ IRoles public rolesContract; /** * @notice The address of the template all new collections will leverage. */ address public implementation; /** * @notice The address of the proxy call contract implementation. * @dev Used by the collections to safely call another contract with arbitrary call data. */ IProxyCall public proxyCallContract; /** * @notice The implementation version new collections will use. * @dev This is auto-incremented each time the implementation is changed. */ uint256 public version; event RolesContractUpdated(address indexed rolesContract); event CollectionCreated( address indexed collectionContract, address indexed creator, uint256 indexed version, string name, string symbol, uint256 nonce ); event ImplementationUpdated(address indexed implementation, uint256 indexed version); event ProxyCallContractUpdated(address indexed proxyCallContract); modifier onlyAdmin() { require(rolesContract.isAdmin(msg.sender), "FNDCollectionFactory: Caller does not have the Admin role"); _; } constructor(address _proxyCallContract, address _rolesContract) { _updateRolesContract(_rolesContract); _updateProxyCallContract(_proxyCallContract); } /** * @notice Create a new collection contract. * @param nonce An arbitrary value used to allow a creator to mint multiple collections. * @dev The nonce is required and must be unique for the msg.sender + implementation version, * otherwise this call will revert. */ function createCollection( string calldata name, string calldata symbol, uint256 nonce ) external returns (address) { require(bytes(symbol).length > 0, "FNDCollectionFactory: Symbol is required"); // This reverts if the NFT was previously created using this implementation version + msg.sender + nonce address proxy = implementation.cloneDeterministic(_getSalt(msg.sender, nonce)); ICollectionContractInitializer(proxy).initialize(payable(msg.sender), name, symbol); emit CollectionCreated(proxy, msg.sender, version, name, symbol, nonce); // Returning the address created allows other contracts to integrate with this call return address(proxy); } /** * @notice Allows Foundation to change the admin role contract address. */ function adminUpdateRolesContract(address _rolesContract) external onlyAdmin { _updateRolesContract(_rolesContract); } /** * @notice Allows Foundation to change the collection implementation used for future collections. * This call will auto-increment the version. * Existing collections are not impacted. */ function adminUpdateImplementation(address _implementation) external onlyAdmin { _updateImplementation(_implementation); } /** * @notice Allows Foundation to change the proxy call contract address. */ function adminUpdateProxyCallContract(address _proxyCallContract) external onlyAdmin { _updateProxyCallContract(_proxyCallContract); } /** * @notice Returns the address of a collection given the current implementation version, creator, and nonce. * This will return the same address whether the collection has already been created or not. * @param nonce An arbitrary value used to allow a creator to mint multiple collections. */ function predictCollectionAddress(address creator, uint256 nonce) external view returns (address) { return implementation.predictDeterministicAddress(_getSalt(creator, nonce)); } function _updateRolesContract(address _rolesContract) private { require(_rolesContract.isContract(), "FNDCollectionFactory: RolesContract is not a contract"); rolesContract = IRoles(_rolesContract); emit RolesContractUpdated(_rolesContract); } /** * @dev Updates the implementation address, increments the version, and initializes the template. * Since the template is initialized when set, implementations cannot be re-used. * To downgrade the implementation, deploy the same bytecode again and then update to that. */ function _updateImplementation(address _implementation) private { require(_implementation.isContract(), "FNDCollectionFactory: Implementation is not a contract"); implementation = _implementation; version++; // The implementation is initialized when assigned so that others may not claim it as their own. ICollectionContractInitializer(_implementation).initialize( payable(address(rolesContract)), string(abi.encodePacked("Foundation Collection Template v", version.toString())), string(abi.encodePacked("FCTv", version.toString())) ); emit ImplementationUpdated(_implementation, version); } function _updateProxyCallContract(address _proxyCallContract) private { require(_proxyCallContract.isContract(), "FNDCollectionFactory: Proxy call address is not a contract"); proxyCallContract = IProxyCall(_proxyCallContract); emit ProxyCallContractUpdated(_proxyCallContract); } function _getSalt(address creator, uint256 nonce) private pure returns (bytes32) { return keccak256(abi.encodePacked(creator, nonce)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address 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 != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // 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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface ICollectionContractInitializer { function initialize( address payable _creator, string memory _name, string memory _symbol ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; /** * @notice Interface for a contract which implements admin roles. */ interface IRoles { function isAdmin(address account) external view returns (bool); function isOperator(address account) external view returns (bool); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "./IRoles.sol"; import "./IProxyCall.sol"; interface ICollectionFactory { function rolesContract() external returns (IRoles); function proxyCallContract() external returns (IProxyCall); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface IProxyCall { function proxyCallAndReturnAddress(address externalContract, bytes calldata callData) external returns (address payable result); }
* @notice Allows Foundation to change the collection implementation used for future collections. This call will auto-increment the version. Existing collections are not impacted./
function adminUpdateImplementation(address _implementation) external onlyAdmin { _updateImplementation(_implementation); }
7,293,476
[ 1, 19132, 31289, 358, 2549, 326, 1849, 4471, 1399, 364, 3563, 6980, 18, 1220, 745, 903, 3656, 17, 15016, 326, 1177, 18, 28257, 6980, 854, 486, 15800, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 3981, 1891, 13621, 12, 2867, 389, 30810, 13, 3903, 1338, 4446, 288, 203, 565, 389, 2725, 13621, 24899, 30810, 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, -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-04-26 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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: ERC721A.sol // Creator: Chiru Labs error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: Bitchez.sol // Bitchez.sol contract Bitchez is ERC721A, Ownable { uint256 public maxSupply = 10000; uint256 public tokensForSale = 3000; bool public whitelistStatus = false; uint256 public whitelistPrice = 0.06 ether; mapping (address => uint256) public whitelists; bool public saleStatus = false; uint256 public currentPrice = 0.069 ether; uint256 public mintLimit = 7; address public blingyAddress; string public baseUri = ""; string public contractURI = "https://cryptobitchez.mypinata.cloud/ipfs/QmPm2kqYErH9D1mLhJyyHSThahxFxMbL8mLUmYs3VJwMVe"; constructor() ERC721A("CryptoBitchez", "BITCH") {} function _baseURI() internal view override returns (string memory) { return baseUri; } function _currentBlingyCost(uint256 tokenId) internal view returns (uint256) { if (tokenId <= tokensForSale) return 0; else if (tokenId > tokensForSale && tokenId <= 5000) return 50 * 10 ** 18; else if (tokenId > 5000 && tokenId <= 7000) return 100 * 10 ** 18; else if (tokenId > 7000 && tokenId <= 8500) return 150 * 10 ** 18; else if (tokenId > 8500 && tokenId <= 10000) return 200 * 10 ** 18; revert(); } function getTokenPrice(uint256 tokenId) public view returns(uint256) { if (tokenId <= tokensForSale) return currentPrice; else return _currentBlingyCost(tokenId); } function _mintToken(address to, uint256 numOfToken) internal { require(saleStatus, "not_sale"); require(numOfToken > 0, "invalid_mint_amount"); require(numOfToken <= mintLimit, "exceed_tx_limit"); require((totalSupply() + numOfToken) <= maxSupply, "exceed_max_supply"); require(to != address(0), "invalid_to_address"); _safeMint(to, numOfToken); } function getBuyPriceInBlingy(uint256 numOfToken) public view returns (uint256) { uint256 blingyCost = 0; for (uint256 i=1; i<=numOfToken; i++) { blingyCost = blingyCost + _currentBlingyCost(totalSupply() + i); } return blingyCost; } function buyByBlingy(uint256 numOfToken) external { require(totalSupply() >= tokensForSale, "eth_sale"); uint256 blingyCost = getBuyPriceInBlingy(numOfToken); require(ERC20Burnable(blingyAddress).balanceOf(msg.sender) >= blingyCost, "insuf_blingy_balance"); ERC20Burnable(blingyAddress).burnFrom(msg.sender, blingyCost); _mintToken(msg.sender, numOfToken); } function buyByEth(uint256 numOfToken) external payable { require((totalSupply() + numOfToken) <= tokensForSale, "exceed_eth_sale_limit"); require(currentPrice * numOfToken <= msg.value, "insuf_price"); _mintToken(msg.sender, numOfToken); } function airdrop(address to, uint256 numOfToken) external onlyOwner { require((totalSupply() + numOfToken) <= maxSupply, "exceed_max_supply"); _safeMint(to, numOfToken); } function whitelistSale(uint256 numOfToken) external payable { require(whitelistStatus, "not_whitelist_sale"); require(numOfToken > 0, "invalid_mint_amount"); require(whitelists[msg.sender] > 0, "not_whitelister"); require(numOfToken <= whitelists[msg.sender], "exceed_whitelist_limit"); require((totalSupply() + numOfToken) <= tokensForSale, "exceed_eth_sale_limit"); require(whitelistPrice * numOfToken <= msg.value, "insuf_price"); _safeMint(msg.sender, numOfToken); whitelists[msg.sender] = whitelists[msg.sender] - numOfToken; } function setBaseURI(string memory newUri) external onlyOwner { baseUri = newUri; } function setSaleState(bool status) external onlyOwner { saleStatus = status; } function setCurrentPrice(uint256 newPrice) public onlyOwner { currentPrice = newPrice; } function setWhitelistState(bool status) external onlyOwner { whitelistStatus = status; } function setWhitelistPrice(uint256 newPrice) public onlyOwner { whitelistPrice = newPrice; } function setWhitelist(address[] calldata whitelisters, uint256[] calldata numOfTokens) external onlyOwner { require (whitelisters.length < 1000, "too_much_inputs"); require (whitelisters.length == numOfTokens.length, "dismatch_input_length"); for (uint256 i=0; i < whitelisters.length; i++) { whitelists[whitelisters[i]] = numOfTokens[i]; } } function setBlingyAddress(address newAddress) public onlyOwner { blingyAddress = newAddress; } function setMintLimit(uint256 newLimit) external onlyOwner { mintLimit = newLimit; } function withdraw() external onlyOwner { require(address(this).balance > 0, "no_balance"); bool success = false; (success, ) = (payable(msg.sender)).call{value: address(this).balance}(""); require(success, "withdraw_failed"); } }
* @dev Spend `amount` form the allowance of `owner` toward `spender`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } }
10,913,371
[ 1, 27223, 1375, 8949, 68, 646, 326, 1699, 1359, 434, 1375, 8443, 68, 358, 2913, 1375, 87, 1302, 264, 8338, 9637, 486, 1089, 326, 1699, 1359, 3844, 316, 648, 434, 14853, 1699, 1359, 18, 868, 1097, 309, 486, 7304, 1699, 1359, 353, 2319, 18, 490, 750, 3626, 392, 288, 23461, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 389, 87, 1302, 7009, 1359, 12, 203, 565, 1758, 3410, 16, 203, 565, 1758, 17571, 264, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 2713, 5024, 288, 203, 565, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 8443, 16, 17571, 264, 1769, 203, 565, 309, 261, 2972, 7009, 1359, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 1377, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 2763, 11339, 1699, 1359, 8863, 203, 1377, 22893, 288, 203, 3639, 389, 12908, 537, 12, 8443, 16, 17571, 264, 16, 783, 7009, 1359, 300, 3844, 1769, 203, 1377, 289, 203, 565, 289, 203, 225, 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 ]
// File: contracts/assets/TokenBankInterface.sol pragma solidity >=0.4.21 <0.6.0; contract TokenBankInterface{ function issue(address token_addr, address payable _to, uint _amount) public returns (bool success); } // File: contracts/utils/Ownable.sol pragma solidity >=0.4.21 <0.6.0; contract Ownable { address private _contract_owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = msg.sender; _contract_owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _contract_owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_contract_owner == msg.sender, "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 transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_contract_owner, newOwner); _contract_owner = newOwner; } } // File: contracts/erc20/IERC20.sol pragma solidity >=0.4.21 <0.6.0; 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); } // File: contracts/utils/SafeMath.sol pragma solidity >=0.4.21 <0.6.0; library SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a, "add"); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a, "sub"); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "mul"); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0, "div"); c = a / b; } } // File: contracts/utils/Address.sol pragma solidity >=0.4.21 <0.6.0; library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/erc20/SafeERC20.sol pragma solidity >=0.4.21 <0.6.0; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).safeAdd(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).safeSub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/utils/AddressArray.sol pragma solidity >=0.4.21 <0.6.0; library AddressArray{ function exists(address[] memory self, address addr) public pure returns(bool){ for (uint i = 0; i< self.length;i++){ if (self[i]==addr){ return true; } } return false; } function index_of(address[] memory self, address addr) public pure returns(uint){ for (uint i = 0; i< self.length;i++){ if (self[i]==addr){ return i; } } require(false, "AddressArray:index_of, not exist"); } function remove(address[] storage self, address addr) public returns(bool){ uint index = index_of(self, addr); self[index] = self[self.length - 1]; delete self[self.length-1]; self.length--; return true; } } // File: contracts/erc20/ERC20Impl.sol pragma solidity >=0.4.21 <0.6.0; contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes memory _data ) public; } contract TransferEventCallBack{ function onTransfer(address _from, address _to, uint256 _amount) public; } contract ERC20Base { string public name; //The Token's name: e.g. GTToken uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "AET_0.1"; //An arbitrary versioning scheme using AddressArray for address[]; address[] public transferListeners; //////////////// // Events //////////////// event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); event NewTransferListener(address _addr); event RemoveTransferListener(address _addr); /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned ERC20Base public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) public balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] public totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; //////////////// // Constructor //////////////// /// @notice Constructor to create a ERC20Base /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( ERC20Base _parentToken, uint _parentSnapShotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public { name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false uint256 previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes memory _extraData) public returns (bool success) { require(approve(address(_spender), _amount)); _spender.receiveApproval( msg.sender, _amount, address(this), _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public view returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function _generateTokens(address _owner, uint _amount) internal returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(address(0), _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function _destroyTokens(address _owner, uint _amount) internal returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, address(0), _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function _enableTransfers(bool _transfersEnabled) internal { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; }function getCheckPointAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return min; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } function onTransferDone(address _from, address _to, uint256 _amount) internal { for(uint i = 0; i < transferListeners.length; i++){ TransferEventCallBack t = TransferEventCallBack(transferListeners[i]); t.onTransfer(_from, _to, _amount); } } function _addTransferListener(address _addr) internal { transferListeners.push(_addr); emit NewTransferListener(_addr); } function _removeTransferListener(address _addr) internal{ transferListeners.remove(_addr); emit RemoveTransferListener(_addr); } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } //function () external payable { //require(false, "cannot transfer ether to this contract"); //} } // File: contracts/utils/TokenClaimer.sol pragma solidity >=0.4.21 <0.6.0; contract TokenClaimer{ event ClaimedTokens(address indexed _token, address indexed _to, uint _amount); /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function _claimStdTokens(address _token, address payable to) internal { if (_token == address(0x0)) { to.transfer(address(this).balance); return; } uint balance = IERC20(_token).balanceOf(address(this)); (bool status,) = _token.call(abi.encodeWithSignature("transfer(address,uint256)", to, balance)); require(status, "call failed"); emit ClaimedTokens(_token, to, balance); } } // File: contracts/plugins/TokenAuction.sol pragma solidity >=0.4.21 <0.6.0; contract TokenAuction is Ownable, TokenClaimer{ using SafeERC20 for IERC20; using SafeMath for uint256; address public bank; address public target_token; address public recv_token; address public yield_pool; uint256 public start_price; uint256 public last_duration_in_blocknum; uint256 public minimal_bumpup; uint256 public minimal_amount; uint256 public ratio_base; bool public paused; struct round_info{ uint256 last_auction_block; uint256 highest_price; uint256 highest_amount; address payable highest_sender; bool settled; } round_info[] public all_rounds; constructor(address _bank, address _target_token, address _recv_token, address _yield_pool, uint256 _start_price, uint256 _last_duration_in_blocknum, uint256 _minimal_bumpup, uint256 _minimal_amount) public{ bank = _bank; target_token = _target_token; recv_token = _recv_token; start_price = _start_price; last_duration_in_blocknum = _last_duration_in_blocknum; minimal_bumpup = _minimal_bumpup; minimal_amount = _minimal_amount; yield_pool = _yield_pool; ratio_base = 10000; paused = false; } event PlaceAuction(address newAuctioner, uint256 newAmount, uint256 newPrice, address oldAuctioner, uint256 oldAmount, uint256 oldPrice); function auction(uint256 amount, uint256 price) public returns(bool){ require(!paused, "auction already paused"); require(amount >= minimal_amount, "less than minimal amount"); require(price >= start_price, "less than start price"); if(all_rounds.length == 0){ round_info memory ri; ri.last_auction_block == block.number; all_rounds.push(ri); } round_info storage ri = all_rounds[all_rounds.length - 1]; if(block.number > ri.last_auction_block.safeAdd(last_duration_in_blocknum)){ if(!ri.settled){ _end_current_auction(); } round_info memory ti; ti.last_auction_block == block.number; all_rounds.push(ti); ri = all_rounds[all_rounds.length - 1]; } //require(price >= ri.highest_price.safeMul(ratio_base + minimal_bumpup).safeDiv(ratio_base), "price bump up too small"); uint256 t = amount.safeMul(price).safeDiv(uint256(10)**ERC20Base(target_token).decimals()); uint256 h = ri.highest_amount.safeMul(ri.highest_price).safeDiv(uint256(10)**ERC20Base(target_token).decimals()); require(t >= h.safeMul(ratio_base + minimal_bumpup).safeDiv(ratio_base), "total payment bump up too small"); require(amount <= IERC20(target_token).balanceOf(bank), "bank doesn't have enough token"); if(ri.highest_sender != address(0x0)){ IERC20(recv_token).safeTransfer(ri.highest_sender, h); } emit PlaceAuction(msg.sender, amount, price, ri.highest_sender, ri.highest_amount, ri.highest_price); IERC20(recv_token).safeTransferFrom(msg.sender, address(this), t); ri.last_auction_block = block.number; ri.highest_price = price; ri.highest_amount = amount; ri.highest_sender = msg.sender; ri.settled = false; return true; } event AuctionDone(address bidder, uint256 price, uint256 amount); function _end_current_auction() internal{ round_info storage ri = all_rounds[all_rounds.length - 1]; if(ri.settled) return; //require(ri.settled == false, "already settled"); ri.settled = true; TokenBankInterface(bank).issue(target_token, ri.highest_sender, ri.highest_amount); IERC20(recv_token).safeTransfer(yield_pool, ri.highest_price.safeMul(ri.highest_amount).safeDiv(uint256(10)**ERC20Base(target_token).decimals())); emit AuctionDone(ri.highest_sender, ri.highest_price, ri.highest_amount); } function end_current_auction() public { if(all_rounds.length == 0){ return ; } round_info storage ri = all_rounds[all_rounds.length - 1]; if(ri.settled){ return ; } require(block.number > ri.last_auction_block.safeAdd(last_duration_in_blocknum), "not ready to end"); _end_current_auction(); } function pause_auction() public onlyOwner{ _end_current_auction(); paused = true; } function resume_auction() public onlyOwner{ paused = false; } function claimStdTokens(address _token, address payable to) public onlyOwner{ _claimStdTokens(_token, to); } event SetStartPrice(uint256 start_price); function set_start_price(uint256 _start_price) public onlyOwner{ start_price = _start_price; emit SetStartPrice(start_price); } event SetMinimalAmount(uint256 minimal_amount); function set_minimal_amount(uint256 _minimal_amount) public onlyOwner{ minimal_amount = _minimal_amount; emit SetMinimalAmount(minimal_amount); } event SetMinimalBumpup(uint256 minimal_bumpup); function set_minimal_bumpup(uint256 _minimal_bumpup) public onlyOwner{ minimal_bumpup = _minimal_bumpup; emit SetMinimalBumpup(minimal_bumpup); } event SetDuration(uint256 last_duration_in_blocknum); function set_duration(uint256 _last_duration_in_blocknum) public onlyOwner{ last_duration_in_blocknum = _last_duration_in_blocknum; emit SetDuration(last_duration_in_blocknum); } event ChangeYieldPool(address yield_pool); function change_yield_pool(address _yield_pool) public onlyOwner{ yield_pool = _yield_pool; emit ChangeYieldPool(yield_pool); } event ChangeBank(address bank); function change_bank(address _bank) public onlyOwner{ bank = _bank; emit ChangeBank(bank); } function get_current_auction_round() public view returns(uint256){ return all_rounds.length; } function get_current_auction_info() public view returns(uint256 last_auction_block, uint256 highest_price, uint256 highest_amount, address payable highest_sender){ return get_auction_info(get_current_auction_round() - 1); } function get_auction_info(uint256 index) public view returns(uint256 last_auction_block, uint256 highest_price, uint256 highest_amount, address payable highest_sender){ round_info storage ri = all_rounds[index]; last_auction_block = ri.last_auction_block; highest_price = ri.highest_price; highest_amount = ri.highest_amount; highest_sender = ri.highest_sender; } } contract TokenAuctionFactory{ event NewTokenAuction(address addr); function createTokenAuction(address bank, address target_token, address recv_token, address yield_pool, uint256 start_price, uint256 last_duration_in_blocknum, uint256 minimal_bumpup, uint256 minimal_amount) public returns(address){ TokenAuction newAuction = new TokenAuction(bank, target_token, recv_token, yield_pool, start_price, last_duration_in_blocknum, minimal_bumpup, minimal_amount); emit NewTokenAuction(address(newAuction)); newAuction.transferOwnership(msg.sender); return address(newAuction); } }
First update the balance array with the new value for the address sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
204,567
[ 1, 3759, 1089, 326, 11013, 526, 598, 326, 394, 460, 364, 326, 1758, 225, 5431, 326, 2430, 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, 1089, 620, 861, 8674, 12, 70, 26488, 63, 67, 2080, 6487, 2416, 13937, 1265, 300, 389, 8949, 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 ]
// SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./ERC20.sol"; import "./SafeERC20.sol"; import "./Curve.sol"; import "./console.sol"; contract Zap { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); struct ZapData { address curve; address base; uint256 zapAmount; uint256 curveBaseBal; uint8 curveBaseDecimals; uint256 curveQuoteBal; } struct DepositData { uint256 curBaseAmount; uint256 curQuoteAmount; uint256 maxBaseAmount; uint256 maxQuoteAmount; } struct DepositAmountsData { uint256 curveRatio; uint256 depositAmount1; uint256 depositAmount2; uint256 lp1; uint256[] outs1; uint256 lp2; uint256[] outs2; } /// @notice Zaps from a quote token (non-USDC) into the LP pool /// @param _curve The address of the curve /// @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing /// @param _deadline Deadline for this zap to be completed by /// @param _minLPAmount Min LP amount to get /// @return uint256 - The amount of LP tokens received function zapFromBase( address _curve, uint256 _zapAmount, uint256 _deadline, uint256 _minLPAmount ) public returns (uint256) { return zap(_curve, _zapAmount, _deadline, _minLPAmount, true); } /// @notice Zaps from a quote token (USDC) into the LP pool /// @param _curve The address of the curve /// @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing /// @param _deadline Deadline for this zap to be completed by /// @param _minLPAmount Min LP amount to get /// @return uint256 - The amount of LP tokens received function zapFromQuote( address _curve, uint256 _zapAmount, uint256 _deadline, uint256 _minLPAmount ) public returns (uint256) { return zap(_curve, _zapAmount, _deadline, _minLPAmount, false); } /// @notice Zaps from a single token into the LP pool /// @param _curve The address of the curve /// @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing /// @param _deadline Deadline for this zap to be completed by /// @param _minLPAmount Min LP amount to get /// @param isFromBase Is the zap originating from the base? (if base, then not USDC) /// @return uint256 - The amount of LP tokens received function zap( address _curve, uint256 _zapAmount, uint256 _deadline, uint256 _minLPAmount, bool isFromBase ) public returns (uint256) { (address base, uint256 swapAmount) = calcSwapAmountForZap(_curve, _zapAmount, isFromBase); // Swap on curve if (isFromBase) { IERC20(base).safeTransferFrom(msg.sender, address(this), _zapAmount); IERC20(base).safeApprove(_curve, 0); IERC20(base).safeApprove(_curve, swapAmount); Curve(_curve).originSwap(base, address(USDC), swapAmount, 0, _deadline); } else { USDC.safeTransferFrom(msg.sender, address(this), _zapAmount); USDC.safeApprove(_curve, 0); USDC.safeApprove(_curve, swapAmount); Curve(_curve).originSwap(address(USDC), base, swapAmount, 0, _deadline); } // Calculate deposit amount (uint256 depositAmount, uint256 baseAmount, uint256 quoteAmount) = _calcDepositAmount(_curve, base); // Can only deposit the smaller amount as we won't have enough of the // token to deposit IERC20(base).safeApprove(_curve, 0); IERC20(base).safeApprove(_curve, baseAmount); USDC.safeApprove(_curve, 0); USDC.safeApprove(_curve, quoteAmount); (uint256 lpAmount, ) = Curve(_curve).deposit(depositAmount, _deadline); require(lpAmount >= _minLPAmount, "!Zap/not-enough-lp-amount"); // Transfer all remaining balances back to user IERC20(_curve).transfer(msg.sender, IERC20(_curve).balanceOf(address(this))); IERC20(base).transfer(msg.sender, IERC20(base).balanceOf(address(this))); USDC.transfer(msg.sender, USDC.balanceOf(address(this))); return lpAmount; } // **** View only functions **** // /// @notice Iteratively calculates how much base to swap /// @param _curve The address of the curve /// @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing /// @return uint256 - The amount to swap function calcSwapAmountForZapFromBase(address _curve, uint256 _zapAmount) public view returns (uint256) { (, uint256 ret) = calcSwapAmountForZap(_curve, _zapAmount, true); return ret; } /// @notice Iteratively calculates how much quote to swap /// @param _curve The address of the curve /// @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing /// @return uint256 - The amount to swap function calcSwapAmountForZapFromQuote(address _curve, uint256 _zapAmount) public view returns (uint256) { (, uint256 ret) = calcSwapAmountForZap(_curve, _zapAmount, false); return ret; } /// @notice Iteratively calculates how much to swap /// @param _curve The address of the curve /// @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing /// @param isFromBase Is the swap originating from the base? /// @return address - The address of the base /// @return uint256 - The amount to swap function calcSwapAmountForZap( address _curve, uint256 _zapAmount, bool isFromBase ) public view returns (address, uint256) { // Base will always be index 0 address base = Curve(_curve).reserves(0); // Ratio of base quote in 18 decimals uint256 curveBaseBal = IERC20(base).balanceOf(_curve); uint8 curveBaseDecimals = ERC20(base).decimals(); uint256 curveQuoteBal = USDC.balanceOf(_curve); uint256 curveRatio = curveBaseBal.mul(10**(36 - uint256(curveBaseDecimals))).div(curveQuoteBal.mul(1e12)); // How much user wants to swap uint256 initialSwapAmount = _zapAmount.sub( curveRatio <= 1e18 ? _zapAmount.mul(curveRatio).div(1e18) : _zapAmount.mul(1e18).div(curveRatio) ); // Calc Base Swap Amount if (isFromBase) { return ( base, _calcBaseSwapAmount( initialSwapAmount, ZapData({ curve: _curve, base: base, zapAmount: _zapAmount, curveBaseBal: curveBaseBal, curveBaseDecimals: curveBaseDecimals, curveQuoteBal: curveQuoteBal }) ) ); } // Calc quote swap amount return ( base, _calcQuoteSwapAmount( initialSwapAmount, ZapData({ curve: _curve, base: base, zapAmount: _zapAmount, curveBaseBal: curveBaseBal, curveBaseDecimals: curveBaseDecimals, curveQuoteBal: curveQuoteBal }) ) ); } // **** Helper functions **** /// @notice Given a base amount, and a quote amount, calculate the deposit amount, /// the number of LP tokens that will be generated, along with the maximized /// base/quote amounts /// @param _curve The address of the curve /// @param _baseAmount The amount of base tokens /// @param _quoteAmount The amount of base tokens /// @return uint256 - The deposit amount /// @return uint256 - The LPTs received /// @return uint256[] memory - The baseAmount and quoteAmount function calcMaxDepositAmount( address _curve, uint256 _baseAmount, uint256 _quoteAmount ) public view returns ( uint256, uint256, uint256[] memory ) { return _calcMaxDepositAmount( _curve, DepositData({ curBaseAmount: _baseAmount, curQuoteAmount: _quoteAmount, maxBaseAmount: _baseAmount, maxQuoteAmount: _quoteAmount }) ); } /// @notice Given a base amount, calculate the max base amount to be deposited /// @param _curve The address of the curve /// @param _quoteAmount The amount of base tokens /// @return uint256 - The max quote amount function calcMaxBaseForDeposit(address _curve, uint256 _quoteAmount) public view returns (uint256) { (, uint256[] memory outs) = Curve(_curve).viewDeposit(2e18); uint256 baseAmount = outs[0].mul(_quoteAmount).div(1e6); return baseAmount; } /// @notice Given a base amount, calculate the max quote amount to be deposited /// @param _curve The address of the curve /// @param _baseAmount The amount of quote tokens /// @return uint256 - The max quote amount function calcMaxQuoteForDeposit(address _curve, uint256 _baseAmount) public view returns (uint256) { uint8 curveBaseDecimals = ERC20(Curve(_curve).reserves(0)).decimals(); (, uint256[] memory outs) = Curve(_curve).viewDeposit(2e18); uint256 ratio = outs[0].mul(10**(36 - curveBaseDecimals)).div(outs[1].mul(1e12)); uint256 quoteAmount = _baseAmount.mul(10**(36 - curveBaseDecimals)).div(ratio).div(1e12); return quoteAmount; } // **** Internal function **** // Stack too deep resulted in this function function _ratio(uint256 ratio, uint256 a) internal pure returns (uint256) { if (ratio > 1e18) { return a.mul(1e18).div(ratio); } return a.mul(ratio).div(1e18); } // Stack too deep function _getCurveRatioAndBaseDecimals(address _curve) internal view returns (uint8, uint256) { address base = Curve(_curve).reserves(0); uint8 curveBaseDecimals = ERC20(base).decimals(); uint256 curveRatio = IERC20(base).balanceOf(_curve).mul(10**(36 - uint256(curveBaseDecimals))).div( USDC.balanceOf(_curve).mul(1e12) ); return (curveBaseDecimals, curveRatio); } function _getDepositAmountsData(address _curve, DepositData memory dd) internal view returns (DepositAmountsData memory) { uint256 maxBaseAmount = calcMaxBaseForDeposit(_curve, dd.curQuoteAmount); uint256 maxQuoteAmount = calcMaxQuoteForDeposit(_curve, dd.curBaseAmount); (uint8 curveBaseDecimals, uint256 curveRatio) = _getCurveRatioAndBaseDecimals(_curve); uint256 depositAmount1; uint256 depositAmount2; uint256 lp1; uint256[] memory outs1; uint256 lp2; uint256[] memory outs2; // Stack too deep { uint256 usdcDepositAmount = dd.curQuoteAmount.mul(1e12); uint256 baseDepositAmount = maxBaseAmount.mul(10**(18 - curveBaseDecimals)); depositAmount1 = usdcDepositAmount.add(baseDepositAmount.mul(1e18).div(curveRatio)); // Prune amounts to get best possible result // Due to loss in precision in floating point math depositAmount1 = depositAmount1.mul(9995).div(10000); (lp1, outs1) = Curve(_curve).viewDeposit(depositAmount1); // Re-using variables usdcDepositAmount = maxQuoteAmount.div(1e4).mul(1e16); baseDepositAmount = dd.curBaseAmount.mul(10**(18 - curveBaseDecimals)); depositAmount2 = usdcDepositAmount.add(baseDepositAmount.mul(1e18).div(curveRatio)); // Prune amounts to get best possible result // Due to loss in precision in floating point math depositAmount2 = depositAmount2.mul(9995).div(10000); // EURS 2 decimals screws things up for small amounts // Need to give 2% slippage if (curveBaseDecimals == 2) { depositAmount2 = depositAmount2.mul(98).div(100); } (lp2, outs2) = Curve(_curve).viewDeposit(depositAmount2); } return DepositAmountsData({ curveRatio: curveRatio, depositAmount1: depositAmount1, depositAmount2: depositAmount2, lp1: lp1, outs1: outs1, lp2: lp2, outs2: outs2 }); } function _calcMaxDepositAmount(address _curve, DepositData memory dd) internal view returns ( uint256, uint256, uint256[] memory ) { DepositAmountsData memory dad = _getDepositAmountsData(_curve, dd); // Both invalid, can't use max // Use smaller value if ( (dad.outs1[0] > dd.maxBaseAmount || dad.outs1[1] > dd.maxQuoteAmount) && (dad.outs2[0] > dd.maxBaseAmount || dad.outs2[1] > dd.maxQuoteAmount) ) { return _calcMaxDepositAmount( _curve, DepositData({ curBaseAmount: _ratio(dad.curveRatio, dd.curBaseAmount), curQuoteAmount: _ratio(dad.curveRatio, dd.curQuoteAmount), maxBaseAmount: dd.maxBaseAmount, maxQuoteAmount: dd.maxQuoteAmount }) ); } // Only deposit 1 is valid if ( dad.outs1[0] <= dd.maxBaseAmount && dad.outs1[1] <= dd.maxQuoteAmount && (dad.outs2[0] > dd.maxBaseAmount || dad.outs2[1] > dd.maxQuoteAmount) ) { return (dad.depositAmount1, dad.lp1, dad.outs1); } // Only deposit 2 is valid if ( dad.outs2[0] <= dd.maxBaseAmount && dad.outs2[1] <= dd.maxQuoteAmount && (dad.outs1[0] > dd.maxBaseAmount || dad.outs1[1] > dd.maxQuoteAmount) ) { return (dad.depositAmount2, dad.lp2, dad.outs2); } // Both valid however, just return the largest if (dad.lp1 > dad.lp2) { return (dad.depositAmount1, dad.lp1, dad.outs1); } return (dad.depositAmount2, dad.lp2, dad.outs2); } function _calcQuoteSwapAmount(uint256 initialSwapAmount, ZapData memory zapData) internal view returns (uint256) { uint256 swapAmount = initialSwapAmount; uint256 delta = swapAmount.div(2); uint256 recvAmount; uint256 curveRatio; uint256 userRatio; // Computer bring me magic number for (uint256 i = 0; i < 32; i++) { // How much will we receive in return recvAmount = Curve(zapData.curve).viewOriginSwap(address(USDC), zapData.base, swapAmount); // Update user's ratio userRatio = recvAmount.mul(10**(36 - uint256(zapData.curveBaseDecimals))).div( zapData.zapAmount.sub(swapAmount).mul(1e12) ); curveRatio = zapData.curveBaseBal.sub(recvAmount).mul(10**(36 - uint256(zapData.curveBaseDecimals))).div( zapData.curveQuoteBal.add(swapAmount).mul(1e12) ); // If user's ratio is approx curve ratio, then just swap // I.e. ratio converges if (userRatio.div(1e12) == curveRatio.div(1e12)) { return swapAmount; } // Otherwise, we keep iterating else if (userRatio > curveRatio) { // We swapping too much swapAmount = swapAmount.sub(delta); } else if (userRatio < curveRatio) { // We swapping too little swapAmount = swapAmount.add(delta); } // Cannot swap more than zapAmount if (swapAmount > zapData.zapAmount) { swapAmount = zapData.zapAmount - 1; } // Keep halving delta = delta.div(2); } return swapAmount; } function _calcBaseSwapAmount(uint256 initialSwapAmount, ZapData memory zapData) internal view returns (uint256) { uint256 swapAmount = initialSwapAmount; uint256 delta = swapAmount.div(2); uint256 recvAmount; uint256 curveRatio; uint256 userRatio; // Computer bring me magic number for (uint256 i = 0; i < 32; i++) { // How much will we receive in return recvAmount = Curve(zapData.curve).viewOriginSwap(zapData.base, address(USDC), swapAmount); // Update user's ratio userRatio = zapData.zapAmount.sub(swapAmount).mul(10**(36 - uint256(zapData.curveBaseDecimals))).div( recvAmount.mul(1e12) ); curveRatio = zapData.curveBaseBal.add(swapAmount).mul(10**(36 - uint256(zapData.curveBaseDecimals))).div( zapData.curveQuoteBal.sub(recvAmount).mul(1e12) ); // If user's ratio is approx curve ratio, then just swap // I.e. ratio converges if (userRatio.div(1e12) == curveRatio.div(1e12)) { return swapAmount; } // Otherwise, we keep iterating else if (userRatio > curveRatio) { // We swapping too little swapAmount = swapAmount.add(delta); } else if (userRatio < curveRatio) { // We swapping too much swapAmount = swapAmount.sub(delta); } // Cannot swap more than zap if (swapAmount > zapData.zapAmount) { swapAmount = zapData.zapAmount - 1; } // Keep halving delta = delta.div(2); } return swapAmount; } function _calcDepositAmount(address _curve, address _base) internal view returns ( uint256, uint256, uint256 ) { // Calculate _depositAmount uint8 curveBaseDecimals = ERC20(_base).decimals(); uint256 curveRatio = IERC20(_base).balanceOf(_curve).mul(10**(36 - uint256(curveBaseDecimals))).div( USDC.balanceOf(_curve).mul(1e12) ); // Deposit amount is denomiated in USD value (based on pool LP ratio) // Things are 1:1 on USDC side on deposit uint256 usdcAmount = USDC.balanceOf(address(this)); uint256 usdcDepositAmount = usdcAmount.mul(1e12); // Things will be based on ratio on deposit uint256 baseAmount = IERC20(_base).balanceOf(address(this)); uint256 baseDepositAmount = baseAmount.mul(10**(18 - uint256(curveBaseDecimals))); // Trim out decimal values uint256 depositAmount = usdcDepositAmount.add(baseDepositAmount.mul(1e18).div(curveRatio)); // Good morning fuck EURS if (curveBaseDecimals == 2) { depositAmount = depositAmount.mul(98).div(100); } // // Make sure we have enough of our inputs (, uint256[] memory outs) = Curve(_curve).viewDeposit(1e18); (, outs) = Curve(_curve).viewDeposit(depositAmount); uint256 baseDelta = outs[0] > baseAmount ? outs[0].sub(baseAmount) : 0; uint256 usdcDelta = outs[1] > usdcAmount ? outs[1].sub(usdcAmount) : 0; uint256 ratio; // Make sure we can deposit if (baseDelta > 0) { ratio = baseDelta.mul(10**curveBaseDecimals).div(baseAmount); depositAmount = depositAmount.sub(depositAmount.mul(ratio).div(10**curveBaseDecimals)); } if (usdcDelta > 0) { ratio = usdcDelta.mul(1e6).div(usdcAmount); depositAmount = depositAmount.sub(depositAmount.mul(ratio).div(1e6)); } // Truncate for rounding errors depositAmount = depositAmount.div(1e16).mul(1e16); return (depositAmount, baseAmount, usdcAmount); } }
@notice Zaps from a quote token (USDC) into the LP pool @param _curve The address of the curve @param _zapAmount The amount to zap, denominated in the ERC20's decimal placing @param _deadline Deadline for this zap to be completed by @param _minLPAmount Min LP amount to get @return uint256 - The amount of LP tokens received
function zapFromQuote( address _curve, uint256 _zapAmount, uint256 _deadline, uint256 _minLPAmount ) public returns (uint256) { return zap(_curve, _zapAmount, _deadline, _minLPAmount, false); }
1,135,658
[ 1, 62, 6679, 628, 279, 3862, 1147, 261, 3378, 5528, 13, 1368, 326, 511, 52, 2845, 225, 389, 16683, 1021, 1758, 434, 326, 8882, 225, 389, 94, 438, 6275, 1021, 3844, 358, 11419, 16, 10716, 7458, 316, 326, 4232, 39, 3462, 1807, 6970, 886, 5330, 225, 389, 22097, 1369, 23967, 1369, 364, 333, 11419, 358, 506, 5951, 635, 225, 389, 1154, 48, 4066, 4778, 5444, 511, 52, 3844, 358, 336, 327, 2254, 5034, 300, 1021, 3844, 434, 511, 52, 2430, 5079, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11419, 1265, 10257, 12, 203, 3639, 1758, 389, 16683, 16, 203, 3639, 2254, 5034, 389, 94, 438, 6275, 16, 203, 3639, 2254, 5034, 389, 22097, 1369, 16, 203, 3639, 2254, 5034, 389, 1154, 48, 4066, 4778, 203, 565, 262, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 11419, 24899, 16683, 16, 389, 94, 438, 6275, 16, 389, 22097, 1369, 16, 389, 1154, 48, 4066, 4778, 16, 629, 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 ]
./full_match/84531/0x7dB0eEE2870618c4743908Bd8519464F5a78dDA7/sources/contracts/seed/Seed.sol
* @dev Set contributor class. @param _address Address of the contributor. @param _class Class of the contributor./
function setClass( address _address, uint8 _class ) onlyAdmin public { require(_class < classes.length, "Seed: incorrect class chosen"); require(!closed, "Seed: should not be closed"); require(block.timestamp < startTime, "Seed: vesting is already started" ); funders[_address].class = _class; }
11,497,279
[ 1, 694, 31123, 667, 18, 225, 389, 2867, 5411, 5267, 434, 326, 31123, 18, 225, 389, 1106, 2868, 1659, 434, 326, 31123, 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 ]
[ 1, 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, 24580, 12, 203, 3639, 1758, 389, 2867, 16, 203, 3639, 2254, 28, 389, 1106, 203, 565, 262, 1338, 4446, 1071, 288, 203, 3639, 2583, 24899, 1106, 411, 3318, 18, 2469, 16, 315, 12702, 30, 11332, 667, 10447, 8863, 203, 3639, 2583, 12, 5, 12204, 16, 315, 12702, 30, 1410, 486, 506, 4375, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 411, 8657, 16, 203, 5411, 315, 12702, 30, 331, 10100, 353, 1818, 5746, 6, 203, 3639, 11272, 203, 3639, 284, 26843, 63, 67, 2867, 8009, 1106, 273, 389, 1106, 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 ]
// SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IOutputReceiver.sol"; import "../interfaces/IRevest.sol"; import "../interfaces/IAddressRegistry.sol"; import "../interfaces/IRewardsHandler.sol"; import "../interfaces/IFNFTHandler.sol"; import "../interfaces/IAddressLock.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; contract Staking is Ownable, IOutputReceiver, ERC165, IAddressLock { using SafeERC20 for IERC20; address private revestAddress; address public lpAddress; address public rewardsHandlerAddress; address public addressRegistry; uint private constant ONE_DAY = 86400; uint private constant WINDOW_ONE = ONE_DAY; uint private constant WINDOW_THREE = ONE_DAY*5; uint private constant WINDOW_SIX = ONE_DAY*9; uint private constant WINDOW_TWELVE = ONE_DAY*14; address internal immutable WETH; uint[4] internal interestRates = [4, 13, 27, 56]; string public customMetadataUrl = "https://revest.mypinata.cloud/ipfs/QmeSaVihizntuDQL5BgsujK2nK6bkkwXXzHATGGjM2uyRr"; string public addressMetadataUrl = "https://revest.mypinata.cloud/ipfs/QmY3KUBToJBthPLvN1Knd7Y51Zxx7FenFhXYV8tPEMVAP3"; struct StakingConfig { uint allocPoints; uint timePeriod; } // fnftId -> allocPoints mapping(uint => StakingConfig) internal config; constructor( address revestAddress_, address rewardsHandlerAddress_, address addressRegistry_, address wrappedEth_ ) { revestAddress = revestAddress_; addressRegistry = addressRegistry_; rewardsHandlerAddress = rewardsHandlerAddress_; WETH = wrappedEth_; } function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return ( interfaceId == type(IOutputReceiver).interfaceId || interfaceId == type(IAddressLock).interfaceId || super.supportsInterface(interfaceId) ); } function stakeBasicTokens(uint amount, uint monthsMaturity) public returns (uint) { require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(revestAddress).safeTransferFrom(msg.sender, address(this), amount * 1); IERC20(revestAddress).approve(address(getRevest()), amount * 1); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = revestAddress; fnftConfig.depositAmount = amount; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); // FNFT quantity will always be singular quantities[0] = 1; uint fnftId = getRevest().mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; uint currentShares = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint newAllocPoint = currentShares + allocPoint; StakingConfig memory stakeConfig = StakingConfig(allocPoint, monthsMaturity); config[fnftId] = stakeConfig; IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, newAllocPoint); return fnftId; } function stakeLPTokens(uint amount, uint monthsMaturity) public returns (uint) { require(lpAddress != address(0x0), "E071"); require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(lpAddress).safeTransferFrom(msg.sender, address(this), amount * 1); IERC20(lpAddress).approve(address(getRevest()), amount * 1); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = lpAddress; fnftConfig.depositAmount = amount; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); quantities[0] = 1; uint fnftId = getRevest().mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; uint currentShares = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint newAllocPoint = currentShares + allocPoint; StakingConfig memory stakeConfig = StakingConfig(allocPoint, monthsMaturity); config[fnftId] = stakeConfig; IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, newAllocPoint); return fnftId; } function getInterestRate(uint months) public view returns (uint) { if (months <= 1) { return interestRates[0]; } else if (months <= 3) { return interestRates[1]; } else if (months <= 6) { return interestRates[2]; } else { return interestRates[3]; } } function updateInterestRates(uint[4] memory newRates) external onlyOwner { interestRates = newRates; } function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external override { require(_msgSender() == getRegistry().getTokenVault(), "E016"); uint totalQuantity = quantity * ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).depositAmount; if (asset == revestAddress) { unstakeBasicTokens(fnftId, owner); } else if (asset == lpAddress) { unstakeLPTokens(fnftId, owner); } else { require(false, "E072"); } IERC20(asset).safeTransfer(owner, totalQuantity); } function claimRewards(uint fnftId) external { // Check to make sure user owns the fnftId require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } function unstakeBasicTokens(uint fnftId, address user) internal { // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, user); // Remove allocation points uint allocPoint = config[fnftId].allocPoints; uint currentShares = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint newAllocPoint = currentShares - allocPoint; IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, newAllocPoint); } function unstakeLPTokens(uint fnftId, address user) internal { IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, user); // Remove allocation points uint allocPoint = config[fnftId].allocPoints; uint currentShares = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, lpAddress, true); uint newAllocPoint = currentShares - allocPoint; IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, newAllocPoint); } function updateLock(uint fnftId, uint lockId, bytes memory arguments) external override { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } function needsUpdate() external pure override returns (bool) { return true; } function setCustomMetadata(string memory _customMetadataUrl) external onlyOwner { customMetadataUrl = _customMetadataUrl; } function getCustomMetadata(uint fnftId) external view override returns (string memory) { return customMetadataUrl; } function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { bool isRevestToken; { // Will be zero if this is an LP stake uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); return abi.encode(revestRewards, wethRewards, config[fnftId].timePeriod, isRevestToken ? revestAddress : lpAddress); } function setLPAddress(address lpAddress_) external onlyOwner { lpAddress = lpAddress_; } function setAddressRegistry(address addressRegistry_) external override onlyOwner { addressRegistry = addressRegistry_; } function getAddressRegistry() external view override returns (address) { return addressRegistry; } function getRevest() private view returns (IRevest) { return IRevest(getRegistry().getRevest()); } function getRegistry() public view returns (IAddressRegistry) { return IAddressRegistry(addressRegistry); } function getValue(uint fnftId) external view override returns (uint) { uint revestStake = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); return revestStake > 0 ? revestStake : IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); } function getAsset(uint fnftId) external view override returns (address) { uint revestStake = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); return revestStake > 0 ? revestAddress : WETH; } function setMetadata(string memory _addressMetadataUrl) external onlyOwner { addressMetadataUrl = _addressMetadataUrl; } function getMetadata() external view override returns (string memory) { return addressMetadataUrl; } function getDisplayValues(uint fnftId, uint lockId) external view override returns (bytes memory) { StakingConfig memory lockDetails = config[fnftId]; return abi.encode(lockDetails.allocPoints, lockDetails.timePeriod); } function createLock(uint fnftId, uint lockID, bytes memory arguments) external pure override { return; } function isUnlockable(uint fnftId, uint lockId) external view override returns (bool) { uint window = getWindow(config[fnftId].timePeriod); uint depositTime = ILockManager(getRegistry().getLockManager()).fnftIdToLock(fnftId).creationTime; bool mature = block.timestamp - depositTime > window; bool window_open = (block.timestamp - depositTime) % (config[fnftId].timePeriod * 30 * ONE_DAY) < window; return mature && window_open; } function getWindow(uint timePeriod) private pure returns (uint) { if(timePeriod == 1) { return WINDOW_ONE; } if(timePeriod == 3) { return WINDOW_THREE; } if(timePeriod == 6) { return WINDOW_SIX; } if(timePeriod == 12) { return WINDOW_TWELVE; } // If none of these are true, bad call require(false, "Invalid time window"); } } // 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: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRegistryProvider.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs */ interface IOutputReceiver is IRegistryProvider, IERC165 { function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external; function getCustomMetadata(uint fnftId) external view returns (string memory); function getValue(uint fnftId) external view returns (uint); function getAsset(uint fnftId) external view returns (address); function getOutputDisplayValues(uint fnftId) external view returns (bytes memory); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IRevest { event FNFTTimeLockMinted( address indexed asset, address indexed from, uint indexed fnftId, uint endTime, uint[] quantities, FNFTConfig fnftConfig ); event FNFTValueLockMinted( address indexed primaryAsset, address indexed from, uint indexed fnftId, address compareTo, address oracleDispatch, uint[] quantities, FNFTConfig fnftConfig ); event FNFTAddressLockMinted( address indexed asset, address indexed from, uint indexed fnftId, address trigger, uint[] quantities, FNFTConfig fnftConfig ); event FNFTWithdrawn( address indexed from, uint indexed fnftId, uint indexed quantity ); event FNFTSplit( address indexed from, uint[] indexed newFNFTId, uint[] indexed proportions, uint quantity ); event FNFTUnlocked( address indexed from, uint indexed fnftId ); event FNFTMaturityExtended( address indexed from, uint indexed fnftId, uint indexed newExtendedTime ); event FNFTAddionalDeposited( address indexed from, uint indexed newFNFTId, uint indexed quantity, uint amount ); struct FNFTConfig { address asset; // The token being stored address pipeToContract; // Indicates if FNFT will pipe to another contract uint depositAmount; // How many tokens uint depositMul; // Deposit multiplier uint split; // Number of splits remaining uint depositStopTime; // bool maturityExtension; // Maturity extensions remaining bool isMulti; // bool nontransferrable; // False by default (transferrable) // } // Refers to the global balance for an ERC20, encompassing possibly many FNFTs struct TokenTracker { uint lastBalance; uint lastMul; } enum LockType { DoesNotExist, TimeLock, ValueLock, AddressLock } struct LockParam { address addressLock; uint timeLockExpiry; LockType lockType; ValueLock valueLock; } struct Lock { address addressLock; LockType lockType; ValueLock valueLock; uint timeLockExpiry; uint creationTime; bool unlocked; } struct ValueLock { address asset; address compareTo; address oracle; uint unlockValue; bool unlockRisingEdge; } function mintTimeLock( uint endTime, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function mintValueLock( address primaryAsset, address compareTo, uint unlockValue, bool unlockRisingEdge, address oracleDispatch, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function mintAddressLock( address trigger, bytes memory arguments, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function withdrawFNFT(uint tokenUID, uint quantity) external; function unlockFNFT(uint tokenUID) external; function splitFNFT( uint fnftId, uint[] memory proportions, uint quantity ) external returns (uint[] memory newFNFTIds); function depositAdditionalToFNFT( uint fnftId, uint amount, uint quantity ) external returns (uint); function setFlatWeiFee(uint wethFee) external; function setERC20Fee(uint erc20) external; function getFlatWeiFee() external returns (uint); function getERC20Fee() external returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; /** * @title Provider interface for Revest FNFTs * @dev * */ interface IAddressRegistry { function initialize( address lock_manager_, address liquidity_, address revest_token_, address token_vault_, address revest_, address fnft_, address metadata_, address admin_, address rewards_ ) external; function getAdmin() external view returns (address); function setAdmin(address admin) external; function getLockManager() external view returns (address); function setLockManager(address manager) external; function getTokenVault() external view returns (address); function setTokenVault(address vault) external; function getRevestFNFT() external view returns (address); function setRevestFNFT(address fnft) external; function getMetadataHandler() external view returns (address); function setMetadataHandler(address metadata) external; function getRevest() external view returns (address); function setRevest(address revest) external; function getDEX(uint index) external view returns (address); function setDex(address dex) external; function getRevestToken() external view returns (address); function setRevestToken(address token) external; function getRewardsHandler() external view returns(address); function setRewardsHandler(address esc) external; function getAddress(bytes32 id) external view returns (address); function getLPs() external view returns (address); function setLPs(address liquidToken) external; } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IRewardsHandler { struct UserBalance { uint allocPoint; // Allocation points uint lastMul; } function receiveFee(address token, uint amount) external; function updateLPShares(uint fnftId, uint newShares) external; function updateBasicShares(uint fnftId, uint newShares) external; function getAllocPoint(uint fnftId, address token, bool isBasic) external view returns (uint); function claimRewards(uint fnftId, address caller) external returns (uint); function setStakingContract(address stake) external; function getRewards(uint fnftId, address token) external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IFNFTHandler { function mint(address account, uint id, uint amount, bytes memory data) external; function mintBatchRec(address[] memory recipients, uint[] memory quantities, uint id, uint newSupply, bytes memory data) external; function mintBatch(address to, uint[] memory ids, uint[] memory amounts, bytes memory data) external; function setURI(string memory newuri) external; function burn(address account, uint id, uint amount) external; function burnBatch(address account, uint[] memory ids, uint[] memory amounts) external; function getBalance(address tokenHolder, uint id) external view returns (uint); function getSupply(uint fnftId) external view returns (uint); function getNextId() external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRegistryProvider.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs * @dev Address locks MUST be non-upgradeable to be considered for trusted status * @author Revest */ interface IAddressLock is IRegistryProvider, IERC165{ /// Creates a lock to the specified lockID /// @param fnftId the fnftId to map this lock to. Not recommended for typical locks, as it will break on splitting /// @param lockId the lockId to map this lock to. Recommended uint for storing references to lock configurations /// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters /// @dev creates a lock for the specified lockId. Will be called during the creation process for address locks when the address /// of a contract implementing this interface is passed in as the "trigger" address for minting an address lock. The bytes /// representing any parameters this lock requires are passed through to this method, where abi.decode must be call on them function createLock(uint fnftId, uint lockId, bytes memory arguments) external; /// Updates a lock at the specified lockId /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters /// @dev updates a lock for the specified lockId. Will be called by the frontend from the information section if an update is requested /// can further accept and decode parameters to use in modifying the lock's config or triggering other actions /// such as triggering an on-chain oracle to update function updateLock(uint fnftId, uint lockId, bytes memory arguments) external; /// Whether or not the lock can be unlocked /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @dev this method is called during the unlocking and withdrawal processes by the Revest contract - it is also used by the frontend /// if this method is returning true and someone attempts to unlock or withdraw from an FNFT attached to the requested lock, the request will succeed /// @return whether or not this lock may be unlocked function isUnlockable(uint fnftId, uint lockId) external view returns (bool); /// Provides an encoded bytes arary that represents values this lock wants to display on the info screen /// Info to decode these values is provided in the metadata file /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @dev used by the frontend to fetch on-chain data on the state of any given lock /// @return a bytes array that represents the result of calling abi.encode on values which the developer wants to appear on the frontend function getDisplayValues(uint fnftId, uint lockId) external view returns (bytes memory); /// Maps to a URL, typically IPFS-based, that contains information on how to encode and decode paramters sent to and from this lock /// Please see additional documentation for JSON config info /// @dev this method will be called by the frontend only but is crucial to properly implement for proper minting and information workflows /// @return a URL to the JSON file containing this lock's metadata schema function getMetadata() external view returns (string memory); /// Whether or not this lock will need updates and should display the option for them /// @dev this will be called by the frontend to determine if update inputs and buttons should be displayed /// @return whether or not the locks created by this contract will need updates function needsUpdate() external view returns (bool); } // 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; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev 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: GNU-GPL v3.0 or later pragma solidity ^0.8.0; import "../interfaces/IAddressRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/ILockManager.sol"; import "../interfaces/ITokenVault.sol"; import "../lib/uniswap/IUniswapV2Factory.sol"; interface IRegistryProvider { function setAddressRegistry(address revest) external; function getAddressRegistry() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRevest.sol"; interface ILockManager { function createLock(uint fnftId, IRevest.LockParam memory lock) external returns (uint); function getLock(uint lockId) external view returns (IRevest.Lock memory); function fnftIdToLockId(uint fnftId) external view returns (uint); function fnftIdToLock(uint fnftId) external view returns (IRevest.Lock memory); function pointFNFTToLock(uint fnftId, uint lockId) external; function lockTypes(uint tokenId) external view returns (IRevest.LockType); function unlockFNFT(uint fnftId, address sender) external returns (bool); function getLockMaturity(uint fnftId) external view returns (bool); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRevest.sol"; interface ITokenVault { function createFNFT( uint fnftId, IRevest.FNFTConfig memory fnftConfig, uint quantity, address from ) external; function withdrawToken( uint fnftId, uint quantity, address user ) external; function depositToken( uint fnftId, uint amount, uint quantity ) external; function cloneFNFTConfig(IRevest.FNFTConfig memory old) external returns (IRevest.FNFTConfig memory); function mapFNFTToToken( uint fnftId, IRevest.FNFTConfig memory fnftConfig ) external; function handleMultipleDeposits( uint fnftId, uint newFNFTId, uint amount ) external; function splitFNFT( uint fnftId, uint[] memory newFNFTIds, uint[] memory proportions, uint quantity ) external; function getFNFT(uint fnftId) external view returns (IRevest.FNFTConfig memory); function getFNFTCurrentValue(uint fnftId) external view returns (uint); function getNontransferable(uint fnftId) external view returns (bool); function getSplitsRemaining(uint fnftId) external view returns (uint); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Receive rewards Remove allocation points
function unstakeBasicTokens(uint fnftId, address user) internal { IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, user); uint allocPoint = config[fnftId].allocPoints; uint currentShares = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint newAllocPoint = currentShares - allocPoint; IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, newAllocPoint); }
13,385,575
[ 1, 11323, 283, 6397, 3581, 13481, 3143, 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, 640, 334, 911, 8252, 5157, 12, 11890, 2295, 1222, 548, 16, 1758, 729, 13, 2713, 288, 203, 3639, 15908, 359, 14727, 1503, 12, 266, 6397, 1503, 1887, 2934, 14784, 17631, 14727, 12, 4293, 1222, 548, 16, 729, 1769, 203, 203, 3639, 2254, 4767, 2148, 273, 642, 63, 4293, 1222, 548, 8009, 9853, 5636, 31, 203, 3639, 2254, 783, 24051, 273, 15908, 359, 14727, 1503, 12, 266, 6397, 1503, 1887, 2934, 588, 8763, 2148, 12, 4293, 1222, 548, 16, 5588, 395, 1887, 16, 638, 1769, 203, 3639, 2254, 394, 8763, 2148, 273, 783, 24051, 300, 4767, 2148, 31, 203, 3639, 15908, 359, 14727, 1503, 12, 266, 6397, 1503, 1887, 2934, 2725, 8252, 24051, 12, 4293, 1222, 548, 16, 394, 8763, 2148, 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 ]
pragma solidity 0.4.23; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 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&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/PausableCrowdsale.sol /** * @title PausableCrowdsale * @dev Extension of Crowdsale contract that can be paused and unpaused by owner */ contract PausableCrowdsale is Crowdsale, Pausable { /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts/interfaces/IDAVToken.sol contract IDAVToken is ERC20 { function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function increaseApproval(address _spender, uint _addedValue) public returns (bool success); function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success); function owner() public view returns (address) {} function transferOwnership(address newOwner) public; function burn(uint256 _value) public; function pauseCutoffTime() public view returns (uint256) {} function paused() public view returns (bool) {} function pause() public; function unpause() public; function setPauseCutoffTime(uint256 _pauseCutoffTime) public; } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts/DAVCrowdsale.sol /** * @title DAVCrowdsale * @dev DAV Crowdsale contract */ contract DAVCrowdsale is PausableCrowdsale, FinalizableCrowdsale { // Opening time for Whitelist B uint256 public openingTimeB; // Sum of contributions in Wei, per beneficiary mapping(address => uint256) public contributions; // List of beneficiaries whitelisted in group A mapping(address => bool) public whitelistA; // List of beneficiaries whitelisted in group B mapping(address => bool) public whitelistB; // Maximum number of Wei that can be raised uint256 public weiCap; // Maximum number of Vincis that can be sold in Crowdsale uint256 public vinciCap; // Minimal contribution amount in Wei per transaction uint256 public minimalContribution; // Maximal total contribution amount in Wei per beneficiary uint256 public maximalIndividualContribution; // Maximal acceptable gas price uint256 public gasPriceLimit = 50000000000 wei; // Wallet to transfer foundation tokens to address public tokenWallet; // Wallet to transfer locked tokens to (e.g., presale buyers) address public lockedTokensWallet; // DAV Token IDAVToken public davToken; // Amount of Vincis sold uint256 public vinciSold; // Address of account that can manage the whitelist address public whitelistManager; constructor(uint256 _rate, address _wallet, address _tokenWallet, address _lockedTokensWallet, IDAVToken _token, uint256 _weiCap, uint256 _vinciCap, uint256 _minimalContribution, uint256 _maximalIndividualContribution, uint256 _openingTime, uint256 _openingTimeB, uint256 _closingTime) public Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) { require(_openingTimeB >= _openingTime); require(_openingTimeB <= _closingTime); require(_weiCap > 0); require(_vinciCap > 0); require(_minimalContribution > 0); require(_maximalIndividualContribution > 0); require(_minimalContribution <= _maximalIndividualContribution); require(_tokenWallet != address(0)); require(_lockedTokensWallet != address(0)); weiCap = _weiCap; vinciCap = _vinciCap; minimalContribution = _minimalContribution; maximalIndividualContribution = _maximalIndividualContribution; openingTimeB = _openingTimeB; tokenWallet = _tokenWallet; lockedTokensWallet= _lockedTokensWallet; davToken = _token; whitelistManager = msg.sender; } /** * @dev Modifier to make a function callable only if user is in whitelist A, or in whitelist B and openingTimeB has passed */ modifier onlyWhitelisted(address _beneficiary) { require(whitelistA[_beneficiary] || (whitelistB[_beneficiary] && block.timestamp >= openingTimeB)); _; } /** * @dev Throws if called by any account other than the whitelist manager */ modifier onlyWhitelistManager() { require(msg.sender == whitelistManager); _; } /** * @dev Change the whitelist manager * * @param _whitelistManager Address of new whitelist manager */ function setWhitelistManager(address _whitelistManager) external onlyOwner { require(_whitelistManager != address(0)); whitelistManager= _whitelistManager; } /** * @dev Change the gas price limit * * @param _gasPriceLimit New gas price limit */ function setGasPriceLimit(uint256 _gasPriceLimit) external onlyOwner { gasPriceLimit = _gasPriceLimit; } /** * Add a group of users to whitelist A * * @param _beneficiaries List of addresses to be whitelisted */ function addUsersWhitelistA(address[] _beneficiaries) external onlyWhitelistManager { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelistA[_beneficiaries[i]] = true; } } /** * Add a group of users to whitelist B * * @param _beneficiaries List of addresses to be whitelisted */ function addUsersWhitelistB(address[] _beneficiaries) external onlyWhitelistManager { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelistB[_beneficiaries[i]] = true; } } /** * Remove a group of users from whitelist A * * @param _beneficiaries List of addresses to be removed from whitelist */ function removeUsersWhitelistA(address[] _beneficiaries) external onlyWhitelistManager { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelistA[_beneficiaries[i]] = false; } } /** * Remove a group of users from whitelist B * * @param _beneficiaries List of addresses to be removed from whitelist */ function removeUsersWhitelistB(address[] _beneficiaries) external onlyWhitelistManager { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelistB[_beneficiaries[i]] = false; } } /** * Allow adjustment of the closing time * * @param _closingTime Time to close the sale. If in the past will set to the present */ function closeEarly(uint256 _closingTime) external onlyOwner onlyWhileOpen { // Make sure the new closing time isn&#39;t after the old closing time require(_closingTime <= closingTime); // solium-disable-next-line security/no-block-members if (_closingTime < block.timestamp) { // If closing time is in the past, set closing time to right now closingTime = block.timestamp; } else { // Update the closing time closingTime = _closingTime; } } /** * Record a transaction that happened during the presale and transfer tokens to locked tokens wallet * * @param _weiAmount Value in wei involved in the purchase * @param _vinciAmount Amount of Vincis sold */ function recordSale(uint256 _weiAmount, uint256 _vinciAmount) external onlyOwner { // Verify that the amount won&#39;t put us over the wei cap require(weiRaised.add(_weiAmount) <= weiCap); // Verify that the amount won&#39;t put us over the vinci cap require(vinciSold.add(_vinciAmount) <= vinciCap); // Verify Crowdsale hasn&#39;t been finalized yet require(!isFinalized); // Update crowdsale totals weiRaised = weiRaised.add(_weiAmount); vinciSold = vinciSold.add(_vinciAmount); // Transfer tokens token.transfer(lockedTokensWallet, _vinciAmount); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); // Verify that the amount won&#39;t put us over the wei cap require(weiRaised.add(_weiAmount) <= weiCap); // Verify that the amount won&#39;t put us over the vinci cap require(vinciSold.add(_weiAmount.mul(rate)) <= vinciCap); // Verify amount is larger than or equal to minimal contribution require(_weiAmount >= minimalContribution); // Verify that the gas price is lower than 50 gwei require(tx.gasprice <= gasPriceLimit); // Verify that user hasn&#39;t contributed more than the individual hard cap require(contributions[_beneficiary].add(_weiAmount) <= maximalIndividualContribution); } function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); // Update user contribution total contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount); // Update total Vincis sold vinciSold = vinciSold.add(_weiAmount.mul(rate)); } function finalization() internal { super.finalization(); // transfer tokens to foundation uint256 foundationTokens = weiRaised.div(2).add(weiRaised); foundationTokens = foundationTokens.mul(rate); uint256 crowdsaleBalance = davToken.balanceOf(this); if (crowdsaleBalance < foundationTokens) { foundationTokens = crowdsaleBalance; } davToken.transfer(tokenWallet, foundationTokens); // Burn off remaining tokens crowdsaleBalance = davToken.balanceOf(this); davToken.burn(crowdsaleBalance); // Set token&#39;s pause cutoff time to 3 weeks from closing time davToken.setPauseCutoffTime(closingTime.add(1814400)); // transfer token Ownership back to original owner davToken.transferOwnership(owner); } }
* @dev Change the gas price limit @param _gasPriceLimit New gas price limit/
function setGasPriceLimit(uint256 _gasPriceLimit) external onlyOwner { gasPriceLimit = _gasPriceLimit; }
2,128,538
[ 1, 3043, 326, 16189, 6205, 1800, 225, 389, 31604, 5147, 3039, 1166, 16189, 6205, 1800, 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 ]
[ 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, 225, 445, 26770, 345, 5147, 3039, 12, 11890, 5034, 389, 31604, 5147, 3039, 13, 3903, 1338, 5541, 288, 203, 565, 16189, 5147, 3039, 273, 389, 31604, 5147, 3039, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; //This contract is deployed on the Rinkeby test net at 0x7c7d28633029e7f862282d2bfa1041c1b58944c2 contract EtherMed { mapping(address => bool) allowed; mapping(address => Doctor) doctors; mapping(address => Prescription) prescriptions; struct Doctor { string name; string work_address; string phone; bool registered; } struct Prescription { string description; bool isValid; } modifier onlyAllowed() { require(allowed[msg.sender]); _; } function EtherMed() public { allowed[msg.sender] = true; } function registerDoctor(address _doctorAddr, string _name, string _work_address, string _phone) onlyAllowed payable public { doctors[_doctorAddr] = Doctor(_name, _work_address, _phone, true); } function issuePrescription(string _description) public returns(uint) { require(doctors[msg.sender].registered); prescriptions[msg.sender] = Prescription(_description, true); } function payDoctor(uint price, address _doctorAddr) public payable { require(prescriptions[_doctorAddr].isValid); require(msg.value == price); _doctorAddr.transfer(price); prescriptions[msg.sender] = prescriptions[_doctorAddr]; delete prescriptions[_doctorAddr]; } function checkUserType(address _addr) view public returns(string) { if(allowed[_addr]) return "admin"; if(doctors[_addr].registered) return "doctor"; return "patient"; } function checkPrescription(address _addr) view public returns(string) { return prescriptions[_addr].description; } function consumePrescription(uint price, address _pharmacyAddr) public payable { require(prescriptions[msg.sender].isValid); require(msg.value == price); _pharmacyAddr.transfer(price); delete prescriptions[msg.sender]; } }
This contract is deployed on the Rinkeby test net at 0x7c7d28633029e7f862282d2bfa1041c1b58944c2
contract EtherMed { mapping(address => bool) allowed; mapping(address => Doctor) doctors; mapping(address => Prescription) prescriptions; struct Doctor { string name; string work_address; string phone; bool registered; } struct Prescription { string description; bool isValid; } modifier onlyAllowed() { require(allowed[msg.sender]); _; } function EtherMed() public { allowed[msg.sender] = true; } function registerDoctor(address _doctorAddr, string _name, string _work_address, string _phone) onlyAllowed payable public { doctors[_doctorAddr] = Doctor(_name, _work_address, _phone, true); } function issuePrescription(string _description) public returns(uint) { require(doctors[msg.sender].registered); prescriptions[msg.sender] = Prescription(_description, true); } function payDoctor(uint price, address _doctorAddr) public payable { require(prescriptions[_doctorAddr].isValid); require(msg.value == price); _doctorAddr.transfer(price); prescriptions[msg.sender] = prescriptions[_doctorAddr]; delete prescriptions[_doctorAddr]; } function checkUserType(address _addr) view public returns(string) { if(allowed[_addr]) return "admin"; if(doctors[_addr].registered) return "doctor"; return "patient"; } function checkPrescription(address _addr) view public returns(string) { return prescriptions[_addr].description; } function consumePrescription(uint price, address _pharmacyAddr) public payable { require(prescriptions[msg.sender].isValid); require(msg.value == price); _pharmacyAddr.transfer(price); delete prescriptions[msg.sender]; } }
12,647,996
[ 1, 2503, 6835, 353, 19357, 603, 326, 534, 754, 73, 1637, 1842, 2901, 622, 374, 92, 27, 71, 27, 72, 22, 5292, 3707, 3103, 29, 73, 27, 74, 5292, 3787, 11149, 72, 22, 70, 507, 2163, 9803, 71, 21, 70, 25, 6675, 6334, 71, 22, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 512, 1136, 13265, 288, 203, 565, 2874, 12, 2867, 516, 1426, 13, 2935, 31, 203, 565, 2874, 12, 2867, 516, 2256, 30206, 13, 31263, 1383, 31, 203, 565, 2874, 12, 2867, 516, 18346, 24136, 13, 4075, 22203, 573, 31, 203, 203, 565, 1958, 2256, 30206, 288, 203, 3639, 533, 508, 31, 203, 3639, 533, 1440, 67, 2867, 31, 203, 3639, 533, 7353, 31, 203, 3639, 1426, 4104, 31, 203, 565, 289, 203, 203, 565, 1958, 18346, 24136, 288, 203, 3639, 533, 2477, 31, 203, 3639, 1426, 4908, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5042, 1435, 288, 203, 3639, 2583, 12, 8151, 63, 3576, 18, 15330, 19226, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 512, 1136, 13265, 1435, 1071, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1744, 3244, 30206, 12, 2867, 389, 2896, 30206, 3178, 16, 533, 389, 529, 16, 533, 389, 1252, 67, 2867, 16, 533, 389, 10540, 13, 1338, 5042, 8843, 429, 1071, 288, 203, 3639, 31263, 1383, 63, 67, 2896, 30206, 3178, 65, 273, 2256, 30206, 24899, 529, 16, 389, 1252, 67, 2867, 16, 389, 10540, 16, 638, 1769, 203, 565, 289, 203, 203, 565, 445, 5672, 12236, 24136, 12, 1080, 389, 3384, 13, 1071, 1135, 12, 11890, 13, 288, 203, 3639, 2583, 12, 2896, 299, 1383, 63, 3576, 18, 15330, 8009, 14327, 1769, 203, 3639, 4075, 22203, 573, 63, 3576, 18, 15330, 65, 273, 18346, 24136, 24899, 3384, 16, 638, 1769, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract SingleToken is ERC721, Ownable { // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _baseUri; constructor(string memory name_, string memory symbol_, string memory baseUri_) ERC721(name_, symbol_) { _baseUri = baseUri_; } /** * @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 setBaseURI(string memory newuri) public onlyOwner { _baseUri = newuri; } /** * @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 override returns (string memory) { return _baseUri; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address tokenOwner, address operator) public view virtual override returns (bool) { return ERC721.isApprovedForAll(tokenOwner, operator) || (operator == owner()); } function mintToBatch( address[] memory recipients, uint256[][] memory ids, bytes memory data ) public virtual onlyOwner { require(recipients.length == ids.length, "ST: recipients and ids length mismatch"); for (uint256 i = 0; i < recipients.length; ++i) { for (uint256 k = 0; k < ids[i].length; ++k) { _safeMint(recipients[i], ids[i][k], data); } } } function mintToBatch(address[] memory recipients, uint256) public virtual onlyOwner { for (uint256 i = 0; i < recipients.length; ++i) _safeMint(recipients[i], i, ''); } function burn(uint256 id) public virtual { require(_isApprovedOrOwner(_msgSender(), id), "ST: caller is not owner nor approved"); _burn(id); } function burnFromBatch(uint256[] memory ids) public virtual onlyOwner { for (uint256 i = 0; i < ids.length; ++i) _burn(ids[i]); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* @dev See {IERC721-isApprovedForAll}./
function isApprovedForAll(address tokenOwner, address operator) public view virtual override returns (bool) { return ERC721.isApprovedForAll(tokenOwner, operator) || (operator == owner()); }
288,511
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 291, 31639, 1290, 1595, 5496, 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 ]
[ 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, 353, 31639, 1290, 1595, 12, 2867, 1147, 5541, 16, 1758, 3726, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 4232, 39, 27, 5340, 18, 291, 31639, 1290, 1595, 12, 2316, 5541, 16, 3726, 13, 747, 261, 9497, 422, 3410, 10663, 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 ]
pragma solidity ^0.5.0; /** * @title DSMath * @author MakerDAO * @notice Safe math contracts from Maker. */ contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint 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(uint x, uint n) internal pure returns (uint 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); } } } } /** * @title Owned * @author Gavin Wood? * @notice Primitive owner properties, modifiers and methods for a single * to own a particular contract. */ contract Owned { address public owner = msg.sender; modifier isOwner { assert(msg.sender == owner); _; } function changeOwner(address account) external isOwner { owner = account; } } /** * @title Pausable * @author MakerDAO? * @notice Primitive events, methods, properties for a contract which can be paused by a single owner. */ contract Pausable is Owned { event Pause(); event Unpause(); bool public paused; modifier pausable { assert(!paused); _; } function pause() external isOwner { paused = true; emit Pause(); } function unpause() external isOwner { paused = false; emit Unpause(); } } /** * @title BurnerAccount * @author UnityCoin Team * @notice Primitive events, methods, properties for a contract which has a special burner account that is Owned by a single account. */ contract BurnerAccount is Owned { address public burner; modifier isOwnerOrBurner { assert(msg.sender == burner || msg.sender == owner); _; } function changeBurner(address account) external isOwner { burner = account; } } /** * @title IntervalBased * @author UnityCoin Team * @notice Primitive events, methods, properties for a contract which has a * interval system, that can be changed in-flight. * * Here we create a system in which any valid unixtimestamp can reduce * down to a specific interval number, based on a start time, duration * and offset. * * Interval Derivation * number = offset + ((timestamp - start time) / intervalDuration) * * Note, when your changing the interval params in flight, we must * set the offset to the most current interval number, as to not * disrupt previously used interval numbers / mechanics */ contract IntervalBased is DSMath { // the start interval uint256 public intervalStartTimestamp; // interval duration (e.g. 1 days) uint256 public intervalDuration; // the max amount of intervals that can be processed for interest claim uint256 public intervalMaximum; // interval offset uint256 public intervalOffset; function changeDuration(uint256 duration) internal { // protect againt unecessary change of offset and starttimestamp if (duration == intervalDuration) { return; } // offset all previous intervals intervalOffset = intervalNumber(block.timestamp); // set new duration intervalDuration = duration; // restart timestamp to current intervalStartTimestamp = block.timestamp; } // get the interval number from start position // every timestamp should have an interval past the start timestamp.. function intervalNumber(uint256 timestamp) public view returns(uint256 number) { return add(intervalOffset, sub(timestamp, intervalStartTimestamp) / intervalDuration); } } /** * @title ERC20Events * @author EIP20 Authors * @notice Primitive events for the ERC20 event specification. */ contract ERC20Events { event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title ERC20 * @author EIP/ERC20 Authors * @author BokkyPooBah / Bok Consulting Pty Ltd 2018. * @notice The ERC20 standard contract interface. */ contract ERC20 is ERC20Events { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) public view returns (uint); function allowance(address tokenOwner, address spender) external view returns (uint); function approve(address spender, uint amount) public returns (bool); function transfer(address to, uint amount) external returns (bool); function transferFrom( address from, address to, uint amount ) public returns (bool); } /** * @title ERC20Token * @author BokkyPooBah / Bok Consulting Pty Ltd 2018. * @author UnityCoin Team * @author MakerDAO * @notice An ERC20 Token implimentation based roughly off of MakerDAO's * version DSToken. */ contract ERC20Token is DSMath, ERC20 { // Standard EIP20 Name, Symbol, Decimals string public symbol = "USDC"; string public name = "UnityCoinTest"; string public version = "1.0.0"; uint8 public decimals = 18; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) approvals; // Standard EIP20: BalanceOf, Transfer, TransferFrom, Allow, Allowance methods.. // Get the token balance for account `tokenOwner` function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // Transfer the balance from owner's account to another account function transfer(address to, uint256 tokens) external returns (bool success) { return transferFrom(msg.sender, to, tokens); } // Send `tokens` amount of tokens from address `from` to address `to` // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { if (from != msg.sender) { approvals[from][msg.sender] = sub(approvals[from][msg.sender], tokens); } balances[from] = sub(balances[from], tokens); balances[to] = add(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address spender, uint256 tokens) public returns (bool success) { approvals[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, 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) external view returns (uint remaining) { return approvals[tokenOwner][spender]; } } /** * @title InterestRateBased * @author UnityCoin Team * @notice A compount interest module which allows for the recording of balance * events and interest rate changes. * * Compound Interest Aglo: * compound interest owed = (principle * ( 1 + Rate / 100 ) * N) – principle; * * This module uses the interval system IntervalBased. * The module is time based and thus we accept that miners can manipulate * time. * * Rate's are specified (as per DSMath imp.) in 10 pow 27 always. * Rates are recorded in an array `interestRates` and thus are indexed. * * Everytime a balance is recorded, we also make sure to set an updatable * pointer to the most recent InterestRate index `intervalToInterestIndex`. * * This module provides a way to calculate compound interest owed, * given the interest rates and balance records are recoded properly. */ contract InterestRateBased is IntervalBased { // Interest Rate Record struct InterestRate { uint256 interval; uint256 rate; // >= 10 ** 27 } // Interval to interest rate InterestRate[] public interestRates; // uint256(interval) => uint256(interest index) mapping(uint256 => uint256) public intervalToInterestIndex; // Balance Records struct BalanceRecord { uint256 interval; uint256 intervalOffset; uint256 balance; } // address(token holder) => uint256(interval) => BalanceChange mapping(address => BalanceRecord[]) public balanceRecords; // address(tokenOwner) => uint256(balance index) mapping(address => uint256) public lastClaimedBalanceIndex; // include balance of method, is ERC20 compliant for tokens function balanceOf(address tokenOwner) public view returns (uint); // VIEW: get current interest rate function latestInterestRate() external view returns (uint256 rateAsRay, uint256 asOfInterval) { uint256 latestRateIndex = interestRates.length > 0 ? sub(interestRates.length, 1) : 0; return (interestRates[latestRateIndex].rate, interestRates[latestRateIndex].interval); } // getters function numInterestRates() public view returns (uint256) { return interestRates.length; } // getters function numBalanceRecords(address tokenOwner) public view returns (uint256) { return balanceRecords[tokenOwner].length; } // interest owed function interestOwed(address tokenOwner) public view returns (uint256 amountOwed, uint256 balanceIndex, uint256 interval) { // check for no balance records.. if (balanceRecords[tokenOwner].length == 0) { return (0, 0, 0); } // balance index amountOwed = 0; balanceIndex = lastClaimedBalanceIndex[tokenOwner]; interval = balanceRecords[tokenOwner][balanceIndex].intervalOffset; // current principle and interest rate uint256 principle = 0; // current principle value uint256 interestRate = 0; // current interest rate // interval markers and interval offset uint256 nextBalanceInterval = interval; // set to starting interval for setup uint256 nextInterestInterval = interval; // set to starting interval for setup // enforce interval maximum, last claim offset difference with max assert(sub(intervalNumber(block.timestamp), intervalOffset) < intervalMaximum); // this for loop should only hit either interest or balance change records, and in theory process only // what is required to calculate compound interest with general computaitonal efficiency // yes, maybe in the future adding a MIN here would be good.. while (interval < intervalNumber(block.timestamp)) { // set interest rates for given interval if (interval == nextInterestInterval) { uint256 interestIndex = intervalToInterestIndex[interval]; // set rate with current interval interestRate = interestRates[interestIndex].rate; // check if look ahead next index is greater than rates length, if so, go to max interval, otherwise next up nextInterestInterval = add(interestIndex, 1) >= interestRates.length ? intervalNumber(block.timestamp) : interestRates[add(interestIndex, 1)].interval; } // setup principle with whats on record at given interval if (interval == nextBalanceInterval) { // get current principle at current balance index, add with amount previously owed in interest principle = add(balanceRecords[tokenOwner][balanceIndex].balance, amountOwed); // increase balance index ahead now that we have the balance balanceIndex = add(balanceIndex, 1); // check if the new blance index exceeds, set next interval to limit or next interval on record nextBalanceInterval = balanceIndex >= balanceRecords[tokenOwner].length ? intervalNumber(block.timestamp) : balanceRecords[tokenOwner][balanceIndex].interval; } // apply compound interest to principle, subtract original principle, add to amount owed amountOwed = add(amountOwed, sub(wmul(principle, rpow(interestRate, sub(min(nextBalanceInterval, nextInterestInterval), interval)) / 10 ** 9), principle)); // set interval to next nearest major balance or interest (or both) change interval = min(nextBalanceInterval, nextInterestInterval); } // return amount owed, adjusted balance index, and the last interval set / used return (amountOwed, (balanceIndex > 0 ? sub(balanceIndex, 1) : 0), interval); } // record users balance (max 2 writes additional per person per transfer) function recordBalance(address tokenOwner) internal { // todays current interval id uint256 todaysInterval = intervalNumber(block.timestamp); // last balance index uint256 latestBalanceIndex = balanceRecords[tokenOwner].length > 0 ? sub(balanceRecords[tokenOwner].length, 1) : 0; // always update the current record (i.e. todays interval) // record balance record (if latest record is for today, add to it, otherwise add a record) if (balanceRecords[tokenOwner].length > 0 && balanceRecords[tokenOwner][latestBalanceIndex].interval == todaysInterval) { balanceRecords[tokenOwner][latestBalanceIndex].balance = balanceOf(tokenOwner); } else { balanceRecords[tokenOwner].push(BalanceRecord({ interval: todaysInterval, intervalOffset: todaysInterval, balance: balanceOf(tokenOwner) })); } // if no interval to interest mapping exists, map it (should always be at least a length of one) if (intervalToInterestIndex[todaysInterval] <= 0) { intervalToInterestIndex[todaysInterval] = sub(interestRates.length, 1); } } // record a new intrest rate change function recordInterestRate(uint256 rate) internal { // min number precision for rate.. might need to add a max here. assert(rate >= RAY); // todays current interval id uint256 todaysInterval = intervalNumber(block.timestamp); // last balance index uint256 latestRateIndex = interestRates.length > 0 ? sub(interestRates.length, 1) : 0; // always update todays interval // record balance record (if latest record is for today, add to it, otherwise add a record) if (interestRates.length > 0 && interestRates[latestRateIndex].interval == todaysInterval) { interestRates[latestRateIndex].rate = rate; } else { interestRates.push(InterestRate({ interval: todaysInterval, rate: rate })); } // map the interval to interest index always intervalToInterestIndex[todaysInterval] = sub(interestRates.length, 1); } } /** * @title PausableCompoundInterestERC20 * @author UnityCoin Team * @notice An implimentation of a mintable, pausable, burnable, compound interest based * ERC20 token. * * The token has a few *special* properties. * - a special burner account (which can burn tokens in its account) * - a special supply tracking pool account / mechanism * - a special interest pool account which interest payments are drawn from * - you cannot transfer from / to any pool (supply or interest) * - you cannot claim interest on the interest pool account * - by all accounts the interest and supply accounts dont really exist * and are used for internal accounting purposes. * * Minting / burning / pausing style is based roughly on DSToken from maker. * * Whenever we burn, mint, change rates we update the supply pool, * which intern updates the totalSupply return. * * The TotalSupply of this token should be as follows: * total supply = supply issued + total interest accued up to current interval * * The special `burner` account can only burn tokens sent to it's account. * You can think of it as a HOT burn account. * The provider can ultimatly burn any account. */ contract PausableCompoundInterestERC20 is Pausable, BurnerAccount, InterestRateBased, ERC20Token { // Non EIP20 Standard Constants, Variables and Events event Mint(address indexed to, uint256 tokens); event Burn(uint256 tokens); event InterestRateChange(uint256 intervalDuration, uint256 intervalExpiry, uint256 indexed interestRateIndex); event InterestClaimed(address indexed tokenOwner, uint256 amountOwed); // the interest pool account address, that wont be included in total supply // hex generated with linux system entropy + dice + keys (private key thrown out) address public constant interestPool = address(0xd365131390302b58A61E265744288097Bd53532e); // this is the based supply pool address, which is used to calculate total supply with interest accured // hex generated with linux system entropy + dice + keys (private key thrown out) address public constant supplyPool = address(0x85c05851ef3175aeFBC74EcA16F174E22b5acF28); // is not a pool account modifier isNotPool(address tokenOwner) { assert(tokenOwner != supplyPool && tokenOwner != interestPool); _; } // total supply with amount owed function totalSupply() external view returns (uint256 supplyWithAccruedInterest) { (uint256 amountOwed,,) = interestOwed(supplyPool); return add(balanceOf(supplyPool), amountOwed); } // Dai/Maker style minting function mint(address to, uint256 amount) public isOwner pausable isNotPool(to) { // any time the supply pool changes, we need to update it's interest owed claimInterestOwed(supplyPool); balances[supplyPool] = add(balances[supplyPool], amount); balances[to] = add(balances[to], amount); recordBalance(supplyPool); recordBalance(to); emit Mint(to, amount); } // the burner can only burn tokens in the burn account function burn(address account) external isOwnerOrBurner pausable isNotPool(account) { // target burn address address target = msg.sender == burner ? burner : account; // any time the supply pool changes, we need to update it's interest owed claimInterestOwed(supplyPool); emit Burn(balances[target]); balances[supplyPool] = sub(balances[supplyPool], balances[target]); balances[target] = 0; // technially the burner account can claim interest, not that it should matter recordBalance(supplyPool); recordBalance(target); } // change interest rates function changeInterestRate( uint256 duration, uint256 maximum, uint256 interestRate, uint256 increasePool, uint256 decreasePool) public isOwner pausable { // claim up supply pool amount if (interestRates.length > 0) { claimInterestOwed(supplyPool); } // set duration and maximum changeDuration(duration); // set interval maximum intervalMaximum = maximum; // record interest rate.. recordInterestRate(interestRate); // set interest pool, no balance needs to be recorded here as this is the interest pool balances[interestPool] = sub(add(balances[interestPool], increasePool), decreasePool); } // hard token set for interest pool function setInterestPool(uint256 tokens) external isOwner pausable { balances[interestPool] = tokens; // no need to record balance as this is the interest pool account.. } // claim interest owed function claimInterestOwed(address tokenOwner) public pausable { // cant claim interest on the interest pool assert(tokenOwner != interestPool); // calculate interest balances and new record indexes (uint256 amountOwed, uint256 balanceIndex, uint256 interval) = interestOwed(tokenOwner); // set last balance index used (it's always one ahead so subtract one) lastClaimedBalanceIndex[tokenOwner] = balanceIndex; // set interval offset if (balanceRecords[tokenOwner].length > 0) { balanceRecords[tokenOwner][balanceIndex].intervalOffset = interval; } // increase the balance of the account, reduce interest pool if (tokenOwner != supplyPool) { balances[interestPool] = sub(balances[interestPool], amountOwed); } // set new token owner balance, record balance event balances[tokenOwner] = add(balances[tokenOwner], amountOwed); recordBalance(tokenOwner); // fire the interest claimed event emit InterestClaimed(tokenOwner, amountOwed); } function transferFrom(address from, address to, uint256 tokens) public pausable isNotPool(from) isNotPool(to) returns (bool success) { super.transferFrom(from, to, tokens); recordBalance(from); recordBalance(to); return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address spender, uint256 tokens) public pausable isNotPool(spender) returns (bool success) { return super.approve(spender, tokens); } } /** * @title SignableCompoundInterestERC20 * @author UnityCoin Team * @notice A meta-transaction enabled version of the PausableCompoundInterestERC20 * this allows you to do a signed transfer or claim using EIP712 signature format. * * We also impliment a constructor here. * * A sender can essentially build EIP712 Claim to specific funds, whereby * someone else (the `feeRecipient`) can recieve a pre-specified fee for * sending the transaction on-behalf of the sender. * * At anytime the sender can invalide the transfer / claim release hash of * a claim / transfer they have signed. * * Written claims also have nonce's to make them unique, and expiries * to remove the change of holding attacks. */ contract SignableCompoundInterestERC20 is PausableCompoundInterestERC20 { // EIP712 Hashes and Seporators bytes32 constant public EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"); bytes32 constant public SIGNEDTRANSFER_TYPEHASH = keccak256("SignedTransfer(address to,uint256 tokens,address feeRecipient,uint256 fee,uint256 expiry,bytes32 nonce)"); bytes32 constant public SIGNEDINTERESTCLAIM_TYPEHASH = keccak256("SignedInterestClaim(address feeRecipient,uint256 fee,uint256 expiry,bytes32 nonce)"); bytes32 public DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, // EIP712 keccak256("UnityCoin"), // app name keccak256("1"), // app version uint256(1), // chain id address(this), // verifying contract bytes32(0x111857f4a3edcb7462eabc03bfe733db1e3f6cdc2b7971ee739626c98268ae12) // salt )); // address(tokenOwner signer) => bytes32(releaseHash) => bool(was release hash used) mapping(address => mapping(bytes32 => bool)) public releaseHashes; event SignedTransfer(address indexed from, address indexed to, uint256 tokens, bytes32 releaseHash); event SignedInterestClaim(address indexed from, bytes32 releaseHash); // constructor for the entire token constructor( address tokenOwner, // main token controller address tokenBurner, // burner account uint256 initialSupply, // total supply amount uint256 interestIntervalStartTimestamp, // start time uint256 interestIntervalDurationSeconds, // interval duration uint256 interestIntervalMaximum, // interest expiry uint256 interestPoolSize, // total interest pool size uint256 interestRate) public { // setup the burner account burner = tokenBurner; // setup the interest mechnics intervalStartTimestamp = interestIntervalStartTimestamp; // set duration intervalDuration = interestIntervalDurationSeconds; // set interest rates changeInterestRate(interestIntervalDurationSeconds, interestIntervalMaximum, interestRate, interestPoolSize, 0); // mint to the token owner the initial supply mint(tokenOwner, initialSupply); // set the provider owner = tokenOwner; } // allow someone else to pay the gas fee for this token, by taking a fee within the token itself. function signedTransfer(address to, uint256 tokens, address feeRecipient, uint256 fee, uint256 expiry, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external returns (bool success) { bytes32 releaseHash = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(SIGNEDTRANSFER_TYPEHASH, to, tokens, feeRecipient, fee, expiry, nonce)) )); address from = ecrecover(releaseHash, v, r, s); // check expiry, release hash and balances assert(block.timestamp < expiry); assert(releaseHashes[from][releaseHash] == false); // waste out release hash releaseHashes[from][releaseHash] = true; // allow funds to be transfered. approvals[from][msg.sender] = add(tokens, fee); // transfer funds transferFrom(from, to, tokens); transferFrom(from, feeRecipient, fee); emit SignedTransfer(from, to, tokens, releaseHash); return true; } // allow someone else to fire the claim interest owed method, and get paid a fee in the token to do so function signedInterestClaim( address feeRecipient, uint256 fee, uint256 expiry, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external returns (bool success) { bytes32 releaseHash = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(SIGNEDINTERESTCLAIM_TYPEHASH, feeRecipient, fee, expiry, nonce)) )); address from = ecrecover(releaseHash, v, r, s); // check expiry, release hash and balances assert(block.timestamp < expiry); assert(releaseHashes[from][releaseHash] == false); // waste out release hash releaseHashes[from][releaseHash] = true; // claim interest owed claimInterestOwed(from); // allow funds to be transfered. approvals[from][msg.sender] = fee; // transfer funds transferFrom(from, feeRecipient, fee); emit SignedInterestClaim(from, releaseHash); return true; } // this allows a token user to invalidate approved release hashes at anytime.. function invalidateHash(bytes32 releaseHash) external pausable { releaseHashes[msg.sender][releaseHash] = true; } }
set interval to next nearest major balance or interest (or both) change
interval = min(nextBalanceInterval, nextInterestInterval);
15,864,322
[ 1, 542, 3673, 358, 1024, 11431, 7888, 11013, 578, 16513, 261, 280, 3937, 13, 2549, 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, 5411, 3673, 273, 1131, 12, 4285, 13937, 4006, 16, 1024, 29281, 4006, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ 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/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ pragma solidity ^0.7.0; contract GeniculateBlue is ERC721, Ownable { constructor() ERC721("Geniculate Blue", "LGN") {} using SafeMath for uint256; uint256 public constant nftPrice = 550000000000000000; uint public constant MAX_PURCHASE = 11; uint256 public constant MAX_MAIN = 475; bool public saleIsActive = false; uint public teamReserve = 15; function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function reserve(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More."); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } teamReserve = teamReserve.sub(_reserveAmount); } function mint(uint _numberOfTokens) public payable { require(saleIsActive, "Not Active."); require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit."); require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted."); require(msg.value >= nftPrice, "More Ethereum."); for(uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MAIN) { _safeMint(msg.sender, mintIndex); } } } string public mintedCode; bool public isReconstructed = false; mapping (uint256 => string) public geniculateSeeds; mapping (uint256 => bool) public seedSet; mapping (uint => string) public mintedColors; event SeedWritten (uint256 indexed nameIndex, string newName); function setSeed(uint256 _tokenId, string calldata currName) public { address owner = ownerOf(_tokenId); require(msg.sender == owner, "Incorrect."); require(seedSet[_tokenId] == false, "Name given."); seedSet[_tokenId] = true; geniculateSeeds[_tokenId] = currName; emit SeedWritten(_tokenId, currName); } function viewSeed(uint _tokenId) public view returns(string memory){ return geniculateSeeds[_tokenId]; } function setCode(string calldata currName) public onlyOwner { mintedCode = currName; } function viewCode() public view returns(string memory) { return mintedCode; } function setColors(uint palette, string calldata palette_param) public onlyOwner { mintedColors[palette] = palette_param; } function viewColors(uint palette) public view returns(string memory) { return mintedColors[palette]; } }
* @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]; }
2,048,119
[ 1, 1356, 326, 460, 4041, 622, 1754, 1375, 1615, 68, 316, 326, 444, 18, 531, 12, 21, 2934, 3609, 716, 1915, 854, 1158, 28790, 603, 326, 9543, 434, 924, 4832, 326, 526, 16, 471, 518, 2026, 2549, 1347, 1898, 924, 854, 3096, 578, 3723, 18, 29076, 30, 300, 1375, 1615, 68, 1297, 506, 23457, 5242, 2353, 288, 2469, 5496, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 445, 389, 270, 12, 694, 2502, 444, 16, 2254, 5034, 770, 13, 3238, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 5411, 2583, 12, 542, 6315, 2372, 18, 2469, 405, 770, 16, 315, 3572, 25121, 694, 30, 770, 596, 434, 4972, 8863, 203, 5411, 327, 444, 6315, 2372, 63, 1615, 15533, 203, 3639, 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 ]
./partial_match/1/0x4B5216498B646AF3121840E7984d466878f2DbCF/sources/Dollar.sol
Chain */ Bootstrapping */ Oracle */ Bonding */ Epoch */
struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1609405200;
4,086,314
[ 1, 3893, 342, 11830, 1382, 342, 28544, 342, 605, 1434, 310, 342, 512, 6127, 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, 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, 1958, 512, 6127, 4525, 288, 203, 3639, 2254, 5034, 1384, 31, 203, 3639, 2254, 5034, 787, 31, 203, 3639, 2254, 5034, 3879, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 11271, 273, 374, 31, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 7570, 273, 2872, 5908, 24, 6260, 6976, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xd7782E2efFE9924Fb8B3C7973cf302cA54Da14DE/sources/MasterChef.sol
Accumulated Eagle per share, times 1e18. See below.
uint256 accEaglePerShare;
4,645,525
[ 1, 8973, 5283, 690, 512, 346, 298, 1534, 7433, 16, 4124, 404, 73, 2643, 18, 2164, 5712, 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 ]
[ 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, 3639, 2254, 5034, 4078, 41, 346, 298, 2173, 9535, 31, 565, 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 ]
pragma solidity ^0.4.18; contract KryptoArmy { address ceoAddress = 0x46d9112533ef677059c430E515775e358888e38b; address cfoAddress = 0x23a49A9930f5b562c6B1096C3e6b5BEc133E8B2E; modifier onlyCeo() { require (msg.sender == ceoAddress); _; } // Struct for Army struct Army { string name; // The name of the army (invented by the user) string idArmy; // The id of the army (USA for United States) uint experiencePoints; // The experience points of the army, we will use this to handle uint256 price; // The cost of the Army in Wei (1 ETH = 1000000000000000000 Wei) uint attackBonus; // The attack bonus for the soldiers (from 0 to 10) uint defenseBonus; // The defense bonus for the soldiers (from 0 to 10) bool isForSale; // User is selling this army, it can be purchase on the marketplace address ownerAddress; // The address of the owner uint soldiersCount; // The count of all the soldiers in this army } Army[] armies; // Struct for Battles struct Battle { uint idArmyAttacking; // The id of the army attacking uint idArmyDefensing; // The id of the army defensing uint idArmyVictorious; // The id of the winning army } Battle[] battles; // Mapping army mapping (address => uint) public ownerToArmy; // Which army does this address own mapping (address => uint) public ownerArmyCount; // How many armies own this address? // Mapping weapons to army mapping (uint => uint) public armyDronesCount; mapping (uint => uint) public armyPlanesCount; mapping (uint => uint) public armyHelicoptersCount; mapping (uint => uint) public armyTanksCount; mapping (uint => uint) public armyAircraftCarriersCount; mapping (uint => uint) public armySubmarinesCount; mapping (uint => uint) public armySatelitesCount; // Mapping battles mapping (uint => uint) public armyCountBattlesWon; mapping (uint => uint) public armyCountBattlesLost; // This function creates a new army and saves it in the array with its parameters function _createArmy(string _name, string _idArmy, uint _price, uint _attackBonus, uint _defenseBonus) public onlyCeo { // We add the new army to the list and save the id in a variable armies.push(Army(_name, _idArmy, 0, _price, _attackBonus, _defenseBonus, true, address(this), 0)); } // We use this function to purchase an army with Metamask function purchaseArmy(uint _armyId) public payable { // We verify that the value paid is equal to the cost of the army require(msg.value == armies[_armyId].price); require(msg.value > 0); // We check if this army is owned by another user if(armies[_armyId].ownerAddress != address(this)) { uint CommissionOwnerValue = msg.value - (msg.value / 10); armies[_armyId].ownerAddress.transfer(CommissionOwnerValue); } // We modify the ownership of the army _ownershipArmy(_armyId); } // Function to purchase a soldier function purchaseSoldiers(uint _armyId, uint _countSoldiers) public payable { // Check that message value > 0 require(msg.value > 0); uint256 msgValue = msg.value; if(msgValue == 1000000000000000 && _countSoldiers == 1) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 8000000000000000 && _countSoldiers == 10) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 65000000000000000 && _countSoldiers == 100) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 500000000000000000 && _countSoldiers == 1000) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } } // Payable function to purchase weapons function purchaseWeapons(uint _armyId, uint _weaponId, uint _bonusAttack, uint _bonusDefense ) public payable { // Check that message value > 0 uint isValid = 0; uint256 msgValue = msg.value; if(msgValue == 10000000000000000 && _weaponId == 0) { armyDronesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 1) { armyPlanesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 2) { armyHelicoptersCount[_armyId]++; isValid = 1; } else if(msgValue == 45000000000000000 && _weaponId == 3) { armyTanksCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 4) { armyAircraftCarriersCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 5) { armySubmarinesCount[_armyId]++; isValid = 1; } else if(msgValue == 120000000000000000 && _weaponId == 6) { armySatelitesCount[_armyId]++; isValid = 1; } // We check if the data has been verified as valid if(isValid == 1) { armies[_armyId].attackBonus = armies[_armyId].attackBonus + _bonusAttack; armies[_armyId].defenseBonus = armies[_armyId].defenseBonus + _bonusDefense; } } // We use this function to affect an army to an address (when someone purchase an army) function _ownershipArmy(uint armyId) private { // We check if the sender already own an army require (ownerArmyCount[msg.sender] == 0); // If this army has alreay been purchased we verify that the owner put it on sale require(armies[armyId].isForSale == true); // We check one more time that the price paid is the price of the army require(armies[armyId].price == msg.value); // We decrement the army count for the previous owner (in case a user is selling army on marketplace) ownerArmyCount[armies[armyId].ownerAddress]--; // We set the new army owner armies[armyId].ownerAddress = msg.sender; ownerToArmy[msg.sender] = armyId; // We increment the army count for this address ownerArmyCount[msg.sender]++; // Send event for new ownership armies[armyId].isForSale = false; } // We use this function to start a new battle function startNewBattle(uint _idArmyAttacking, uint _idArmyDefensing, uint _randomIndicatorAttack, uint _randomIndicatorDefense) public returns(uint) { // We verify that the army attacking is the army of msg.sender require (armies[_idArmyAttacking].ownerAddress == msg.sender); // Get details for army attacking uint ScoreAttack = armies[_idArmyAttacking].attackBonus * (armies[_idArmyAttacking].soldiersCount/3) + armies[_idArmyAttacking].soldiersCount + _randomIndicatorAttack; // Get details for army defending uint ScoreDefense = armies[_idArmyAttacking].defenseBonus * (armies[_idArmyDefensing].soldiersCount/2) + armies[_idArmyDefensing].soldiersCount + _randomIndicatorDefense; uint VictoriousArmy; uint ExperiencePointsGained; if(ScoreDefense >= ScoreAttack) { VictoriousArmy = _idArmyDefensing; ExperiencePointsGained = armies[_idArmyAttacking].attackBonus + 2; armies[_idArmyDefensing].experiencePoints = armies[_idArmyDefensing].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyDefensing]++; armyCountBattlesLost[_idArmyAttacking]++; } else { VictoriousArmy = _idArmyAttacking; ExperiencePointsGained = armies[_idArmyDefensing].defenseBonus + 2; armies[_idArmyAttacking].experiencePoints = armies[_idArmyAttacking].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyAttacking]++; armyCountBattlesLost[_idArmyDefensing]++; } // We add the new battle to the blockchain and save its id in a variable battles.push(Battle(_idArmyAttacking, _idArmyDefensing, VictoriousArmy)); // Send event return (VictoriousArmy); } // Owner can sell army function ownerSellArmy(uint _armyId, uint256 _amount) public { // We close the function if the user calling this function doesn't own the army require (armies[_armyId].ownerAddress == msg.sender); require (_amount > 0); require (armies[_armyId].isForSale == false); armies[_armyId].isForSale = true; armies[_armyId].price = _amount; } // Owner remove army from marketplace function ownerCancelArmyMarketplace(uint _armyId) public { require (armies[_armyId].ownerAddress == msg.sender); require (armies[_armyId].isForSale == true); armies[_armyId].isForSale = false; } // Function to return all the value of an army function getArmyFullData(uint armyId) public view returns(string, string, uint, uint256, uint, uint, bool) { string storage ArmyName = armies[armyId].name; string storage ArmyId = armies[armyId].idArmy; uint ArmyExperiencePoints = armies[armyId].experiencePoints; uint256 ArmyPrice = armies[armyId].price; uint ArmyAttack = armies[armyId].attackBonus; uint ArmyDefense = armies[armyId].defenseBonus; bool ArmyIsForSale = armies[armyId].isForSale; return (ArmyName, ArmyId, ArmyExperiencePoints, ArmyPrice, ArmyAttack, ArmyDefense, ArmyIsForSale); } // Function to return the owner of the army function getArmyOwner(uint armyId) public view returns(address, bool) { return (armies[armyId].ownerAddress, armies[armyId].isForSale); } // Function to return the owner of the army function getSenderArmyDetails() public view returns(uint, string) { uint ArmyId = ownerToArmy[msg.sender]; string storage ArmyName = armies[ArmyId].name; return (ArmyId, ArmyName); } // Function to return the owner army count function getSenderArmyCount() public view returns(uint) { uint ArmiesCount = ownerArmyCount[msg.sender]; return (ArmiesCount); } // Function to return the soldiers count of an army function getArmySoldiersCount(uint armyId) public view returns(uint) { uint SoldiersCount = armies[armyId].soldiersCount; return (SoldiersCount); } // Return an array with the weapons of the army function getWeaponsArmy1(uint armyId) public view returns(uint, uint, uint, uint) { uint CountDrones = armyDronesCount[armyId]; uint CountPlanes = armyPlanesCount[armyId]; uint CountHelicopters = armyHelicoptersCount[armyId]; uint CountTanks = armyTanksCount[armyId]; return (CountDrones, CountPlanes, CountHelicopters, CountTanks); } function getWeaponsArmy2(uint armyId) public view returns(uint, uint, uint) { uint CountAircraftCarriers = armyAircraftCarriersCount[armyId]; uint CountSubmarines = armySubmarinesCount[armyId]; uint CountSatelites = armySatelitesCount[armyId]; return (CountAircraftCarriers, CountSubmarines, CountSatelites); } // Retrieve count battles won function getArmyBattles(uint _armyId) public view returns(uint, uint) { return (armyCountBattlesWon[_armyId], armyCountBattlesLost[_armyId]); } // Retrieve the details of a battle function getDetailsBattles(uint battleId) public view returns(uint, uint, uint, string, string) { return (battles[battleId].idArmyAttacking, battles[battleId].idArmyDefensing, battles[battleId].idArmyVictorious, armies[battles[battleId].idArmyAttacking].idArmy, armies[battles[battleId].idArmyDefensing].idArmy); } // Get battles count function getBattlesCount() public view returns(uint) { return (battles.length); } // To withdraw fund from this contract function withdraw(uint amount, uint who) public onlyCeo returns(bool) { require(amount <= this.balance); if(who == 0) { ceoAddress.transfer(amount); } else { cfoAddress.transfer(amount); } return true; } // Initial function to create the 100 armies with their attributes function KryptoArmy() public onlyCeo { // 1. USA _createArmy("United States", "USA", 550000000000000000, 8, 9); // 2. North Korea _createArmy("North Korea", "NK", 500000000000000000, 10, 5); // 3. Russia _createArmy("Russia", "RUS", 450000000000000000, 8, 7); // 4. China _createArmy("China", "CHN", 450000000000000000, 7, 8); // 5. Japan _createArmy("Japan", "JPN", 420000000000000000, 7, 7); // 6. France _createArmy("France", "FRA", 400000000000000000, 6, 8); // 7. Germany _createArmy("Germany", "GER", 400000000000000000, 7, 6); // 8. India _createArmy("India", "IND", 400000000000000000, 7, 6); // 9. United Kingdom _createArmy("United Kingdom", "UK", 350000000000000000, 5, 7); // 10. South Korea _createArmy("South Korea", "SK", 350000000000000000, 6, 6); // 11. Turkey _createArmy("Turkey", "TUR", 300000000000000000, 7, 4); // 12. Italy //_createArmy("Italy", "ITA", 280000000000000000, 5, 5); } }
We use this function to purchase an army with Metamask We verify that the value paid is equal to the cost of the army We check if this army is owned by another user
function purchaseArmy(uint _armyId) public payable { require(msg.value == armies[_armyId].price); require(msg.value > 0); if(armies[_armyId].ownerAddress != address(this)) { uint CommissionOwnerValue = msg.value - (msg.value / 10); armies[_armyId].ownerAddress.transfer(CommissionOwnerValue); } }
13,131,583
[ 1, 3218, 999, 333, 445, 358, 23701, 392, 419, 4811, 598, 21604, 301, 835, 1660, 3929, 716, 326, 460, 30591, 353, 3959, 358, 326, 6991, 434, 326, 419, 4811, 1660, 866, 309, 333, 419, 4811, 353, 16199, 635, 4042, 729, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 23701, 686, 4811, 12, 11890, 389, 4610, 93, 548, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 23563, 606, 63, 67, 4610, 93, 548, 8009, 8694, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 1769, 203, 540, 203, 3639, 309, 12, 4610, 606, 63, 67, 4610, 93, 548, 8009, 8443, 1887, 480, 1758, 12, 2211, 3719, 288, 203, 5411, 2254, 1286, 3951, 5541, 620, 273, 1234, 18, 1132, 300, 261, 3576, 18, 1132, 342, 1728, 1769, 203, 5411, 23563, 606, 63, 67, 4610, 93, 548, 8009, 8443, 1887, 18, 13866, 12, 799, 3951, 5541, 620, 1769, 203, 3639, 289, 203, 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 ]
./full_match/8217/0xD5ad6D61Dd87EdabE2332607C328f5cc96aeCB95/sources/contracts/TreasuryRebalance.sol
* @dev resets all storage values to empty objects except targetBlockNumber/reset cannot be called at Finalized status or after target block.number`delete` keyword is used to set a storage variable or a dynamic array to its default value.
function reset() public onlyOwner { require( ((status != Status.Finalized) && (block.number < rebalanceBlockNumber)), "Contract is finalized, cannot reset values" ); delete retirees; delete newbies; delete memo; status = Status.Initialized; }
13,229,959
[ 1, 455, 2413, 777, 2502, 924, 358, 1008, 2184, 1335, 1018, 1768, 1854, 19, 6208, 2780, 506, 2566, 622, 16269, 1235, 1267, 578, 1839, 1018, 1203, 18, 2696, 68, 3733, 68, 4932, 353, 1399, 358, 444, 279, 2502, 2190, 578, 279, 5976, 526, 358, 2097, 805, 460, 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, 2715, 1435, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 14015, 2327, 480, 2685, 18, 7951, 1235, 13, 597, 203, 7734, 261, 2629, 18, 2696, 411, 283, 12296, 1768, 1854, 13, 3631, 203, 5411, 315, 8924, 353, 727, 1235, 16, 2780, 2715, 924, 6, 203, 3639, 11272, 203, 203, 3639, 1430, 325, 577, 281, 31, 203, 3639, 1430, 394, 70, 606, 31, 203, 3639, 1430, 11063, 31, 203, 3639, 1267, 273, 2685, 18, 11459, 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 ]
pragma solidity ^0.4.24; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } 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 Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract PostDeliveryCrowdsale is TimedCrowdsale, FinalizableCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; uint256 public totalTokensSold = 0; uint256 private hardCap; /** * @param _hardCap hard cap in tokens */ constructor (uint256 _hardCap) public { hardCap = _hardCap; } function balanceOf (address _address) public view returns (uint256) { return balances[_address]; } /** * @dev Withdraw tokens only after crowdsale ends and crowdsale is finalized. */ function withdrawTokens() public { require(hasClosed()); require(isFinalized); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { require(totalTokensSold.add(_tokenAmount) <= hardCap); totalTokensSold.add(_tokenAmount); balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } contract RefundableBeforeSoftCapCrowdsale is Ownable, FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running // AfterSoftCapEscrow private escrow; AfterSoftCapEscrow private escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); escrow = new AfterSoftCapEscrow(wallet, rate); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks escrow wallet balance */ function escrowBalance() public view returns (uint256) { return address(escrow).balance; } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } function updateEscrowGoalReached() onlyOwner public { require(!isFinalized); require(goalReached()); escrow.reachGoal(); } function beneficiaryWithdraw() onlyOwner public { require(goalReached()); escrow.beneficiaryWithdraw(); } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.reachGoal(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } } contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } contract AfterSoftCapEscrow is Ownable, Escrow { enum State { Active, Refunding, Reached } event Reached(); event WithdrawalsEnabled(); event RefundsEnabled(); State public state; address public beneficiary; uint256 public minimalValue; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary, uint256 _minimalValue) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; minimalValue = _minimalValue; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state != State.Refunding); require(msg.value >= 0.0011 ether); // minimal token price (TODO: update for ICO) super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function reachGoal() public onlyOwner { require(state == State.Active); state = State.Reached; emit Reached(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public onlyOwner { require(state == State.Reached); beneficiary.transfer(address(this).balance); } function withdraw(address _payee) public { require(state == State.Refunding); super.withdraw(_payee); } } 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 StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract BitfexToken is MintableToken { string public name = "BitFex Token"; string public symbol = "BITFEX"; uint8 public decimals = 2; uint256 public PRE_ICO_TOKENS_AMOUNT = 2000000; uint256 public ICO_TOKENS_AMOUNT = 3000000; uint256 public OWNERS_TOKENS_AMOUNT = 4000000; uint256 public BOUNTY_TOKENS_AMOUNT = 1000000; uint256 public TOTAL_SUPPLY = PRE_ICO_TOKENS_AMOUNT + ICO_TOKENS_AMOUNT + OWNERS_TOKENS_AMOUNT + BOUNTY_TOKENS_AMOUNT; bool public mintingFinished = false; function preallocate(address _preICO, address _ICO, address _ownersWallet, address _bountyWallet) onlyOwner canMint public returns (bool) { assert(TOTAL_SUPPLY == 10000000); // check that total tokens amount is 100 000.00 tokens mint(_preICO, PRE_ICO_TOKENS_AMOUNT); mint(_ICO, ICO_TOKENS_AMOUNT); mint(_ownersWallet, OWNERS_TOKENS_AMOUNT); mint(_bountyWallet, BOUNTY_TOKENS_AMOUNT); mintingFinished = true; emit MintFinished(); return true; } } contract PreICOCrowdsale is TimedCrowdsale, PostDeliveryCrowdsale, RefundableBeforeSoftCapCrowdsale { constructor ( uint256 _openingTime, uint256 _closingTime, uint256 _rate, uint256 _goal, uint256 _hardCap, address _wallet, BitfexToken _token ) public Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) RefundableBeforeSoftCapCrowdsale(_goal) PostDeliveryCrowdsale(_hardCap) { } /** * @dev Convert wei to tokens * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(10**2).div(rate); } }
minimal token price (TODO: update for ICO)
require(msg.value >= 0.0011 ether);
6,427,988
[ 1, 1154, 2840, 1147, 6205, 261, 6241, 30, 1089, 364, 467, 3865, 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 ]
[ 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, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 713, 2499, 225, 2437, 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 ]
./full_match/1/0x8a0F72aABfeE510e9D88bCc6D426Fd47b8694176/sources/contracts/libraries/Proxy.sol
* @notice Performs the proxy call via a delegatecall./ Copy calldata into memory at 0x0....calldatasize. Perform the delegatecall, make sure to pass all available gas. Copy returndata into memory at 0x0....returndatasize. Note that this *will* overwrite the calldata that we just copied into memory but that doesn't really matter because we'll be returning in a second anyway. Success == 0 means a revert. We'll revert too and pass the data up.
function _doProxyCall() internal { address impl = _getImplementation(); require(impl != address(0), "Proxy: implementation not initialized"); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0) returndatacopy(0x0, 0x0, returndatasize()) if iszero(success) { revert(0x0, returndatasize()) } } }
3,111,045
[ 1, 9409, 326, 2889, 745, 3970, 279, 7152, 1991, 18, 19, 5631, 745, 892, 1368, 3778, 622, 374, 92, 20, 6265, 1991, 13178, 554, 18, 11217, 326, 7152, 1991, 16, 1221, 3071, 358, 1342, 777, 2319, 16189, 18, 5631, 327, 892, 1368, 3778, 622, 374, 92, 20, 6265, 2463, 13178, 554, 18, 3609, 716, 333, 903, 6156, 326, 745, 892, 716, 732, 2537, 9268, 1368, 3778, 1496, 716, 3302, 1404, 8654, 15177, 2724, 732, 5614, 506, 5785, 316, 279, 2205, 13466, 18, 11958, 422, 374, 4696, 279, 15226, 18, 1660, 5614, 15226, 4885, 471, 1342, 326, 501, 731, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 2896, 3886, 1477, 1435, 2713, 288, 203, 3639, 1758, 9380, 273, 389, 588, 13621, 5621, 203, 3639, 2583, 12, 11299, 480, 1758, 12, 20, 3631, 315, 3886, 30, 4471, 486, 6454, 8863, 203, 203, 3639, 19931, 288, 203, 5411, 745, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 745, 13178, 554, 10756, 203, 203, 5411, 2231, 2216, 519, 7152, 1991, 12, 31604, 9334, 9380, 16, 374, 92, 20, 16, 745, 13178, 554, 9334, 374, 92, 20, 16, 374, 92, 20, 13, 203, 203, 5411, 327, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 327, 13178, 554, 10756, 203, 203, 5411, 309, 353, 7124, 12, 4768, 13, 288, 203, 7734, 15226, 12, 20, 92, 20, 16, 327, 13178, 554, 10756, 203, 5411, 289, 203, 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 ]
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. /// @title Validator Manager library pragma solidity ^0.8.0; import {Result} from "../interfaces/IValidatorManager.sol"; import {LibClaimsMask, ClaimsMask} from "../libraries/LibClaimsMask.sol"; import {LibFeeManager} from "../libraries/LibFeeManager.sol"; library LibValidatorManager { using LibClaimsMask for ClaimsMask; using LibFeeManager for LibFeeManager.DiamondStorage; bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("ValidatorManager.diamond.storage"); struct DiamondStorage { bytes32 currentClaim; // current claim - first claim of this epoch address payable[] validators; // up to 8 validators uint256 maxNumValidators; // the maximum number of validators, set in the constructor // A bit set used for up to 8 validators. // The first 8 bits are used to indicate whom supports the current claim // The second 8 bits are used to indicate those should have claimed in order to reach consensus // The following every 30 bits are used to indicate the number of total claims each validator has made // | agreement mask | consensus mask | #claims_validator7 | #claims_validator6 | ... | #claims_validator0 | // | 8 bits | 8 bits | 30 bits | 30 bits | ... | 30 bits | ClaimsMask claimsMask; } /// @notice emitted on Claim received event ClaimReceived( Result result, bytes32[2] claims, address payable[2] validators ); /// @notice emitted on Dispute end event DisputeEnded( Result result, bytes32[2] claims, address payable[2] validators ); /// @notice emitted on new Epoch event NewEpoch(bytes32 claim); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } /// @notice called when a dispute ends in rollups /// @param ds diamond storage pointer /// @param winner address of dispute winner /// @param loser address of dispute loser /// @param winningClaim the winnning claim /// @return result of dispute being finished function onDisputeEnd( DiamondStorage storage ds, address payable winner, address payable loser, bytes32 winningClaim ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { removeValidator(ds, loser); if (winningClaim == ds.currentClaim) { // first claim stood, dont need to update the bitmask return isConsensus(ds) ? emitDisputeEndedAndReturn( Result.Consensus, [winningClaim, bytes32(0)], [winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [winningClaim, bytes32(0)], [winner, payable(0)] ); } // if first claim lost, and other validators have agreed with it // there is a new dispute to be played if (ds.claimsMask.getAgreementMask() != 0) { return emitDisputeEndedAndReturn( Result.Conflict, [ds.currentClaim, winningClaim], [getClaimerOfCurrentClaim(ds), winner] ); } // else there are no valdiators that agree with losing claim // we can update current claim and check for consensus in case // the winner is the only validator left ds.currentClaim = winningClaim; updateClaimAgreementMask(ds, winner); return isConsensus(ds) ? emitDisputeEndedAndReturn( Result.Consensus, [winningClaim, bytes32(0)], [winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [winningClaim, bytes32(0)], [winner, payable(0)] ); } /// @notice called when a new epoch starts /// @param ds diamond storage pointer /// @return current claim function onNewEpoch(DiamondStorage storage ds) internal returns (bytes32) { // reward validators who has made the correct claim by increasing their #claims claimFinalizedIncreaseCounts(ds); bytes32 tmpClaim = ds.currentClaim; // clear current claim ds.currentClaim = bytes32(0); // clear validator agreement bit mask ds.claimsMask = ds.claimsMask.clearAgreementMask(); emit NewEpoch(tmpClaim); return tmpClaim; } /// @notice called when a claim is received by rollups /// @param ds diamond storage pointer /// @param sender address of sender of that claim /// @param claim claim received by rollups /// @return result of claim, Consensus | NoConflict | Conflict /// @return [currentClaim, conflicting claim] if there is Conflict /// [currentClaim, bytes32(0)] if there is Consensus or NoConflcit /// @return [claimer1, claimer2] if there is Conflcit /// [claimer1, address(0)] if there is Consensus or NoConflcit function onClaim( DiamondStorage storage ds, address payable sender, bytes32 claim ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { require(claim != bytes32(0), "empty claim"); require(isValidator(ds, sender), "sender not allowed"); // require the validator hasn't claimed in the same epoch before uint256 index = getValidatorIndex(ds, sender); require( !ds.claimsMask.alreadyClaimed(index), "sender had claimed in this epoch before" ); // cant return because a single claim might mean consensus if (ds.currentClaim == bytes32(0)) { ds.currentClaim = claim; } else if (claim != ds.currentClaim) { return emitClaimReceivedAndReturn( Result.Conflict, [ds.currentClaim, claim], [getClaimerOfCurrentClaim(ds), sender] ); } updateClaimAgreementMask(ds, sender); return isConsensus(ds) ? emitClaimReceivedAndReturn( Result.Consensus, [claim, bytes32(0)], [sender, payable(0)] ) : emitClaimReceivedAndReturn( Result.NoConflict, [claim, bytes32(0)], [sender, payable(0)] ); } /// @notice emits dispute ended event and then return /// @param result to be emitted and returned /// @param claims to be emitted and returned /// @param validators to be emitted and returned /// @dev this function existis to make code more clear/concise function emitDisputeEndedAndReturn( Result result, bytes32[2] memory claims, address payable[2] memory validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { emit DisputeEnded(result, claims, validators); return (result, claims, validators); } /// @notice emits claim received event and then return /// @param result to be emitted and returned /// @param claims to be emitted and returned /// @param validators to be emitted and returned /// @dev this function existis to make code more clear/concise function emitClaimReceivedAndReturn( Result result, bytes32[2] memory claims, address payable[2] memory validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { emit ClaimReceived(result, claims, validators); return (result, claims, validators); } /// @notice only call this function when a claim has been finalized /// Either a consensus has been reached or challenge period has past /// @param ds pointer to diamond storage function claimFinalizedIncreaseCounts(DiamondStorage storage ds) internal { uint256 agreementMask = ds.claimsMask.getAgreementMask(); for (uint256 i; i < ds.validators.length; i++) { // if a validator agrees with the current claim if ((agreementMask & (1 << i)) != 0) { // increase #claims by 1 ds.claimsMask = ds.claimsMask.increaseNumClaims(i, 1); } } } /// @notice removes a validator /// @param ds diamond storage pointer /// @param validator address of validator to be removed function removeValidator(DiamondStorage storage ds, address validator) internal { LibFeeManager.DiamondStorage storage feeManagerDS = LibFeeManager .diamondStorage(); for (uint256 i; i < ds.validators.length; i++) { if (validator == ds.validators[i]) { // put address(0) in validators position ds.validators[i] = payable(0); // remove the validator from ValidatorManager's claimsMask ds.claimsMask = ds.claimsMask.removeValidator(i); // remove the validator from FeeManager's claimsMask (#redeems) feeManagerDS.removeValidator(i); break; } } } /// @notice check if consensus has been reached /// @param ds pointer to diamond storage function isConsensus(DiamondStorage storage ds) internal view returns (bool) { ClaimsMask claimsMask = ds.claimsMask; return claimsMask.getAgreementMask() == claimsMask.getConsensusGoalMask(); } /// @notice get one of the validators that agreed with current claim /// @param ds diamond storage pointer /// @return validator that agreed with current claim function getClaimerOfCurrentClaim(DiamondStorage storage ds) internal view returns (address payable) { // TODO: we are always getting the first validator // on the array that agrees with the current claim to enter a dispute // should this be random? uint256 agreementMask = ds.claimsMask.getAgreementMask(); for (uint256 i; i < ds.validators.length; i++) { if (agreementMask & (1 << i) != 0) { return ds.validators[i]; } } revert("Agreeing validator not found"); } /// @notice updates mask of validators that agreed with current claim /// @param ds diamond storage pointer /// @param sender address of validator that will be included in mask function updateClaimAgreementMask( DiamondStorage storage ds, address payable sender ) internal { uint256 validatorIndex = getValidatorIndex(ds, sender); ds.claimsMask = ds.claimsMask.setAgreementMask(validatorIndex); } /// @notice check if the sender is a validator /// @param ds pointer to diamond storage /// @param sender sender address function isValidator(DiamondStorage storage ds, address sender) internal view returns (bool) { require(sender != address(0), "address 0"); for (uint256 i; i < ds.validators.length; i++) { if (sender == ds.validators[i]) return true; } return false; } /// @notice find the validator and return the index or revert /// @param ds pointer to diamond storage /// @param sender validator address /// @return validator index or revert function getValidatorIndex(DiamondStorage storage ds, address sender) internal view returns (uint256) { require(sender != address(0), "address 0"); for (uint256 i; i < ds.validators.length; i++) { if (sender == ds.validators[i]) return i; } revert("validator not found"); } /// @notice get number of claims the sender has made /// @param ds pointer to diamond storage /// @param _sender validator address /// @return #claims function getNumberOfClaimsByAddress( DiamondStorage storage ds, address payable _sender ) internal view returns (uint256) { for (uint256 i; i < ds.validators.length; i++) { if (_sender == ds.validators[i]) { return getNumberOfClaimsByIndex(ds, i); } } // if validator not found return 0; } /// @notice get number of claims by the index in the validator set /// @param ds pointer to diamond storage /// @param index the index in validator set /// @return #claims function getNumberOfClaimsByIndex(DiamondStorage storage ds, uint256 index) internal view returns (uint256) { return ds.claimsMask.getNumClaims(index); } /// @notice get the maximum number of validators defined in validator manager /// @param ds pointer to diamond storage /// @return the maximum number of validators function getMaxNumValidators(DiamondStorage storage ds) internal view returns (uint256) { return ds.maxNumValidators; } }
@notice check if consensus has been reached @param ds pointer to diamond storage
function isConsensus(DiamondStorage storage ds) internal view returns (bool) { ClaimsMask claimsMask = ds.claimsMask; return claimsMask.getAgreementMask() == claimsMask.getConsensusGoalMask(); }
13,005,449
[ 1, 1893, 309, 18318, 711, 2118, 8675, 225, 3780, 4407, 358, 4314, 301, 1434, 2502, 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, 353, 9054, 9781, 12, 14521, 301, 1434, 3245, 2502, 3780, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 28895, 5796, 11955, 5796, 273, 3780, 18, 28979, 5796, 31, 203, 3639, 327, 203, 5411, 11955, 5796, 18, 588, 17420, 5796, 1435, 422, 11955, 5796, 18, 588, 9054, 9781, 27716, 5796, 5621, 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 ]
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy 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 stable rate and 2 for variable 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); 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); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; 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); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; 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); function getReserveTotalBorrowsStable(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 ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ 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); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; 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"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.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"); } 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); } } } } pragma solidity ^0.6.0; 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; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. 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); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; 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; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; 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( DFSExchangeData.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( DFSExchangeData.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); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, 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 getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.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(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; 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(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; 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 wrapper; 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)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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"); } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; 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); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; 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 burnGas(20) { 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs 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 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; 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, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _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(managerAddr, _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, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _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(managerAddr, _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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).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 _managerAddr Address of the CDP Manager /// @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(address _managerAddr, 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(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, 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(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).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 /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).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(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _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); } 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); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; 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}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; 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; } pragma solidity ^0.6.0; import "./Gem.sol"; 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; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @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(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; 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_NOT_ZEROX_EXCHANGE = "Zerox exchange 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(EXCHANGE_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; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } 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(EXCHANGE_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; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } 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 (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @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); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; 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); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; 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; } } pragma solidity ^0.6.0; 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); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 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; } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, 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; } 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 ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).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, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).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, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; 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); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; 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)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; 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); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; 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); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; 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; } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, 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)", market, ETH_ADDR, ethAmount)); // 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(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @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)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet 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; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @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(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { 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(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ 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); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); 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; ManagerType managerType; } 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 burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).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(managerAddr).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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); 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(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _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(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _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 ); } } } pragma solidity ^0.6.0; 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); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; 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, (_collAmount + collSwaped)); 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 {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @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 getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring 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); } } } pragma solidity ^0.6.0; /// @title Implements enum Method 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; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; 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)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } 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); } } } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay 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 = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; 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( DFSExchangeData.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.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (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( DFSExchangeData.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.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (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; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; 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); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @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 onlyOwner { 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 onlyOwner { 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 onlyOwner { 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 onlyOwner { 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 onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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 } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, 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]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _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 _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } 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); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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 } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { 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; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _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) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} 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 sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( 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( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _proxy.transfer(address(this).balance); } } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // 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) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); 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) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); 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); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage 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, DFSExchangeData.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); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; 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: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; 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; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // 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 { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; 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] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost 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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; 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; ManagerType managerType; } 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, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); 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 managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).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(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).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 managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _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(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; 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; 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; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _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 + _closeData.flFee); (, 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(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_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 {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy 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); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy 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); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; 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 DSProxy 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) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); 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)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { (address cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow 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 function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // 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, _market, _rateMode, _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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; 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 DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @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 _market, 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(_market, _collateralToken, _borrowToken, _ethAmount, 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; 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 DSProxy 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, 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)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; 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); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; 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 (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 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); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 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); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; 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 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.user = msg.sender; 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: _amount}(); // 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)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy 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)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy 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)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions 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; uint borrowCap; } 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]), borrowCap: comp.borrowCaps(_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(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system 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 = 1500000; uint public BOOST_GAS_COST = 1000000; 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 As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @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); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; 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; exData.user = _user; // 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; exData.user = _user; // 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.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(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions 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(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; 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(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet 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)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, 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) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(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.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin 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, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(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, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @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)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 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 = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_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( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) 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,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (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, "AutomaticAaveRepayV2", 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( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) 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,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (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, "AutomaticAaveBoostV2", 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); AaveSubscriptionsV2.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(AAVE_MARKET_ADDRESS, _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) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _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 As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @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; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @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 Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is 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 onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { 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 onlyOwner { 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 onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; 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); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } 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); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); 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].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, 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(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); 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 (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, 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(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // 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 coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, 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)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; 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 As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @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; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; 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; uint256 borrowRate; 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].borrowRate,,,,,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]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_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]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); 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 { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; 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); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract 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(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @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(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract 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(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; 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); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; 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; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges 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); }
@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; }
381,062
[ 1, 67, 22585, 7187, 3886, 7659, 20092, 716, 6013, 353, 10799, 358, 745, 8678, 3886, 225, 389, 19964, 2592, 7562, 6835, 364, 21327, 6865, 225, 389, 22585, 11353, 1504, 304, 56, 6388, 13456, 716, 6013, 11199, 868, 10239, 19, 26653, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 2867, 389, 22585, 7187, 3886, 16, 1758, 389, 19964, 16, 1758, 389, 22585, 11353, 1504, 304, 56, 6388, 13, 1071, 288, 203, 3639, 11360, 7187, 3886, 273, 21327, 7187, 3886, 24899, 22585, 7187, 3886, 1769, 203, 3639, 11912, 8924, 273, 21327, 15440, 24899, 19964, 1769, 203, 3639, 11360, 11353, 1504, 304, 56, 6388, 1887, 273, 389, 22585, 11353, 1504, 304, 56, 6388, 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 ]
./partial_match/1/0xce346aD7046222Fd119F6B715B6F60C0FDBFe796/sources/home/david/repc-v1.1.0/contracts/RariFundManager.sol
* @dev Throws if fund is disabled./
modifier fundEnabled() { require(!_fundDisabled, "This fund manager contract is disabled. This may be due to an upgrade."); _; }
3,567,795
[ 1, 21845, 309, 284, 1074, 353, 5673, 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 ]
[ 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, 9606, 284, 1074, 1526, 1435, 288, 203, 3639, 2583, 12, 5, 67, 74, 1074, 8853, 16, 315, 2503, 284, 1074, 3301, 6835, 353, 5673, 18, 1220, 2026, 506, 6541, 358, 392, 8400, 1199, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; pragma experimental ABIEncoderV2; import "./Include.sol"; // Inheritancea interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewards(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } abstract contract RewardsDistributionRecipient { address public rewardsDistribution; function notifyRewardAmount(uint256 reward) virtual external; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } } contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; // obsoleted uint256 public rewardsDuration = 60 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) override public rewards; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; /* ========== CONSTRUCTOR ========== */ //constructor( function __StakingRewards_init( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) public virtual initializer { __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); } function __StakingRewards_init_unchained( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) public virtual initializer { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; } /* ========== VIEWS ========== */ function totalSupply() virtual override public view returns (uint256) { return _totalSupply; } function balanceOf(address account) virtual override public view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() override public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() virtual override public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) virtual override public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() virtual override external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) virtual public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // permit IPermit(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function stake(uint256 amount) virtual override public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) virtual override public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() virtual override public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() virtual override public { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) override external onlyRewardsDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) virtual { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } interface IPermit { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } contract StakingPool is Configurable, StakingRewards { using Address for address payable; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; bytes32 internal constant _rewards2Token_ = 'rewards2Token'; bytes32 internal constant _rewards2Ratio_ = 'rewards2Ratio'; //bytes32 internal constant _rewards2Span_ = 'rewards2Span'; bytes32 internal constant _rewards2Begin_ = 'rewards2Begin'; uint public lep; // 1: linear, 2: exponential, 3: power //uint public period; // obsolete uint public begin; mapping (address => uint256) public paid; address swapFactory; address[] pathTVL; address[] pathAPY; function __StakingPool_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr ) public virtual initializer { __ReentrancyGuard_init_unchained(); __Governable_init_unchained(_governor); //__StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken, _ecoAddr); } function __StakingPool_init_unchained(address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr) public virtual governance { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; config[_ecoAddr_] = uint(_ecoAddr); config[_ecoRatio_] = 0.1 ether; } function notifyRewardBegin(uint _lep, /*uint _period,*/ uint _span, uint _begin) virtual public governance updateReward(address(0)) { lep = _lep; // 1: linear, 2: exponential, 3: power //period = _period; rewardsDuration = _span; begin = _begin; periodFinish = _begin.add(_span); } function notifyReward2(address _rewards2Token, uint _ratio, /*uint _span,*/ uint _begin) virtual external governance updateReward(address(0)) { config[_rewards2Token_] = uint(_rewards2Token); config[_rewards2Ratio_] = _ratio; //config[_rewards2Span_] = _span; config[_rewards2Begin_] = _begin; } function rewardDelta() public view returns (uint amt) { if(begin == 0 || begin >= now || lastUpdateTime >= now) return 0; amt = Math.min(rewardsToken.allowance(rewardsDistribution, address(this)), rewardsToken.balanceOf(rewardsDistribution)).sub0(rewards[address(0)]); // calc rewardDelta in period if(lep == 3) { // power //uint y = period.mul(1 ether).div(lastUpdateTime.add(rewardsDuration).sub(begin)); //uint amt1 = amt.mul(1 ether).div(y); //uint amt2 = amt1.mul(period).div(now.add(rewardsDuration).sub(begin)); uint amt2 = amt.mul(lastUpdateTime.add(rewardsDuration).sub(begin)).div(now.add(rewardsDuration).sub(begin)); amt = amt.sub(amt2); } else if(lep == 2) { // exponential if(now.sub(lastUpdateTime) < rewardsDuration) amt = amt.mul(now.sub(lastUpdateTime)).div(rewardsDuration); }else if(now < periodFinish) // linear amt = amt.mul(now.sub(lastUpdateTime)).div(periodFinish.sub(lastUpdateTime)); else if(lastUpdateTime >= periodFinish) amt = 0; if(config[_ecoAddr_] != 0) amt = amt.mul(uint(1e18).sub(config[_ecoRatio_])).div(1 ether); } function rewardPerToken() virtual override public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( rewardDelta().mul(1e18).div(_totalSupply) ); } function earned(address account) virtual override public view returns (uint256) { return Math.min(Math.min(super.earned(account), rewardsToken.allowance(rewardsDistribution, address(this))), rewardsToken.balanceOf(rewardsDistribution)); } modifier updateReward(address account) override { rewardPerTokenStored = rewardPerToken(); uint delta = rewardDelta(); { address addr = address(config[_ecoAddr_]); uint ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) { uint d = delta.mul(ratio).div(uint(1e18).sub(ratio)); rewards[addr] = rewards[addr].add(d); delta = delta.add(d); } } rewards[address(0)] = rewards[address(0)].add(delta); lastUpdateTime = now; if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function getReward() virtual override public { getRewardA(msg.sender); } function getRewardA(address payable acct) virtual public nonReentrant updateReward(acct) { require(getConfigA(_blocklist_, acct) == 0, 'In blocklist'); bool isContract = acct.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, acct) != 0, 'No allowContract'); uint256 reward = rewards[acct]; if (reward > 0) { rewards[acct] = 0; rewards[address(0)] = rewards[address(0)].sub0(reward); rewardsToken.safeTransferFrom(rewardsDistribution, acct, reward); emit RewardPaid(acct, reward); if(config[_rewards2Token_] != 0 && config[_rewards2Begin_] <= now) { uint reward2 = Math.min(reward.mul(config[_rewards2Ratio_]).div(1e18), IERC20(config[_rewards2Token_]).balanceOf(address(this))); IERC20(config[_rewards2Token_]).safeTransfer(acct, reward2); emit RewardPaid2(acct, reward2); } } } event RewardPaid2(address indexed user, uint256 reward2); //function compound() virtual public nonReentrant updateReward(msg.sender) { // only for pool3 // require(getConfigA(_blocklist_, msg.sender) == 0, 'In blocklist'); // bool isContract = msg.sender.isContract(); // require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, msg.sender) != 0, 'No allowContract'); // require(stakingToken == rewardsToken, 'not pool3'); // // uint reward = rewards[msg.sender]; // if (reward > 0) { // rewards[msg.sender] = 0; // rewards[address(0)] = rewards[address(0)].sub0(reward); // rewardsToken.safeTransferFrom(rewardsDistribution, address(this), reward); // emit RewardPaid(msg.sender, reward); // // _totalSupply = _totalSupply.add(reward); // _balances[msg.sender] = _balances[msg.sender].add(reward); // emit Staked(msg.sender, reward); // } //} function getRewardForDuration() override external view returns (uint256) { return rewardsToken.allowance(rewardsDistribution, address(this)).sub0(rewards[address(0)]); } function rewards2Token() virtual external view returns (address) { return address(config[_rewards2Token_]); } function rewards2Ratio() virtual external view returns (uint) { return config[_rewards2Ratio_]; } function setPath(address swapFactory_, address[] memory pathTVL_, address[] memory pathAPY_) virtual external governance { uint m = pathTVL_.length; uint n = pathAPY_.length; require(m > 0 && n > 0 && pathTVL_[m-1] == pathAPY_[n-1]); for(uint i=0; i<m-1; i++) require(address(0) != IUniswapV2Factory(swapFactory_).getPair(pathTVL_[i], pathTVL_[i+1])); for(uint i=0; i<n-1; i++) require(address(0) != IUniswapV2Factory(swapFactory_).getPair(pathAPY_[i], pathAPY_[i+1])); swapFactory = swapFactory_; pathTVL = pathTVL_; pathAPY = pathAPY_; } function lptValueTotal() virtual public view returns (uint) { require(pathTVL.length > 0 && pathTVL[0] != address(stakingToken)); return IERC20(pathTVL[0]).balanceOf(address(stakingToken)).mul(2); } function lptValue(uint vol) virtual public view returns (uint) { return lptValueTotal().mul(vol).div(IERC20(stakingToken).totalSupply()); } function swapValue(uint vol, address[] memory path) virtual public view returns (uint v) { v = vol; for(uint i=0; i<path.length-1; i++) { (uint reserve0, uint reserve1,) = IUniswapV2Pair(IUniswapV2Factory(swapFactory).getPair(path[i], path[i+1])).getReserves(); v = path[i+1] < path[i] ? v.mul(reserve0) / reserve1 : v.mul(reserve1) / reserve0; } } function TVL() virtual public view returns (uint tvl) { if(pathTVL[0] != address(stakingToken)) tvl = lptValueTotal(); else tvl = totalSupply(); tvl = swapValue(tvl, pathTVL); } function APY() virtual public view returns (uint) { uint amt = rewardsToken.allowance(rewardsDistribution, address(this)).sub0(rewards[address(0)]); if(lep == 3) { // power uint amt2 = amt.mul(365 days).mul(now.add(rewardsDuration).sub(begin)).div(now.add(1).add(rewardsDuration).sub(begin)); amt = amt.sub(amt2); } else if(lep == 2) { // exponential amt = amt.mul(365 days).div(rewardsDuration); }else if(now < periodFinish) // linear amt = amt.mul(365 days).div(periodFinish.sub(lastUpdateTime)); else if(lastUpdateTime >= periodFinish) amt = 0; require(address(rewardsToken) == pathAPY[0]); amt = swapValue(amt, pathAPY); return amt.mul(1e18).div(TVL()); } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint) external; } contract EthPool is StakingPool { bytes32 internal constant _WETH_ = 'WETH'; function __EthPool_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr, address _WETH ) public virtual initializer { __ReentrancyGuard_init_unchained(); __Governable_init_unchained(_governor); //__StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken, _ecoAddr); __EthPool_init_unchained(_WETH); } function __EthPool_init_unchained(address _WETH) public virtual governance { config[_WETH_] = uint(_WETH); } function stakeEth() virtual public payable nonReentrant updateReward(msg.sender) { require(address(stakingToken) == address(config[_WETH_]), 'stakingToken is not WETH'); uint amount = msg.value; require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); IWETH(address(stakingToken)).deposit{value: amount}(); //stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdrawEth(uint256 amount) virtual public nonReentrant updateReward(msg.sender) { require(address(stakingToken) == address(config[_WETH_]), 'stakingToken is not WETH'); require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); IWETH(address(stakingToken)).withdraw(amount); //stakingToken.safeTransfer(msg.sender, amount); msg.sender.transfer(amount); emit Withdrawn(msg.sender, amount); } function exitEth() virtual public { withdrawEth(_balances[msg.sender]); getReward(); } receive () payable external { stakeEth(); } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract DoublePool is StakingPool { IStakingRewards public stakingPool2; IERC20 public rewardsToken2; //uint256 public lastUpdateTime2; // obsoleted //uint256 public rewardPerTokenStored2; // obsoleted mapping(address => uint256) public userRewardPerTokenPaid2; mapping(address => uint256) public rewards2; function __DoublePool_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr, address _stakingPool2, address _rewardsToken2) public initializer { __ReentrancyGuard_init_unchained(); __Governable_init_unchained(_governor); //__StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken, _ecoAddr); __DoublePool_init_unchained(_stakingPool2, _rewardsToken2); } function __DoublePool_init_unchained(address _stakingPool2, address _rewardsToken2) public governance { stakingPool2 = IStakingRewards(_stakingPool2); rewardsToken2 = IERC20(_rewardsToken2); } function notifyRewardBegin(uint _lep, /*uint _period,*/ uint _span, uint _begin) virtual override public governance updateReward2(address(0)) { super.notifyRewardBegin(_lep, /*_period,*/ _span, _begin); } function stake(uint amount) virtual override public updateReward2(msg.sender) { super.stake(amount); stakingToken.safeApprove(address(stakingPool2), amount); stakingPool2.stake(amount); } function withdraw(uint amount) virtual override public updateReward2(msg.sender) { stakingPool2.withdraw(amount); super.withdraw(amount); } function getReward2() virtual public nonReentrant updateReward2(msg.sender) { uint256 reward2 = rewards2[msg.sender]; if (reward2 > 0) { rewards2[msg.sender] = 0; stakingPool2.getReward(); rewardsToken2.safeTransfer(msg.sender, reward2); emit RewardPaid2(msg.sender, reward2); } } event RewardPaid2(address indexed user, uint256 reward2); function getDoubleReward() virtual public { getReward(); getReward2(); } function exit() override public { super.exit(); getReward2(); } function rewardPerToken2() virtual public view returns (uint256) { return stakingPool2.rewardPerToken(); } function earned2(address account) virtual public view returns (uint256) { return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]); } modifier updateReward2(address account) virtual { if (account != address(0)) { rewards2[account] = earned2(account); userRewardPerTokenPaid2[account] = rewardPerToken2(); } _; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } interface IMasterChef { function poolInfo(uint pid) external view returns (address lpToken, uint allocPoint, uint lastRewardBlock, uint accCakePerShare); function userInfo(uint pid, address user) external view returns (uint amount, uint rewardDebt); function pending(uint pid, address user) external view returns (uint); function pendingCake(uint pid, address user) external view returns (uint); function deposit(uint pid, uint amount) external; function withdraw(uint pid, uint amount) external; } contract NestMasterChef is StakingPool { IERC20 internal constant Cake = IERC20(0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82); IMasterChef public stakingPool2; IERC20 public rewardsToken2; mapping(address => uint256) public userRewardPerTokenPaid2; mapping(address => uint256) public rewards2; uint public pid2; uint internal _rewardPerToken2; function __NestMasterChef_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr, address _stakingPool2, address _rewardsToken2, uint _pid2) public initializer { __Governable_init_unchained(_governor); __ReentrancyGuard_init_unchained(); //__StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken, _ecoAddr); __NestMasterChef_init_unchained(_stakingPool2, _rewardsToken2, _pid2); } function __NestMasterChef_init_unchained(address _stakingPool2, address _rewardsToken2, uint _pid2) public governance { stakingPool2 = IMasterChef(_stakingPool2); rewardsToken2 = IERC20(_rewardsToken2); pid2 = _pid2; } function notifyRewardBegin(uint _lep, /*uint _period,*/ uint _span, uint _begin) virtual override public governance updateReward2(address(0)) { super.notifyRewardBegin(_lep, /*_period,*/ _span, _begin); } function migrate() virtual public governance updateReward2(address(0)) { uint total = stakingToken.balanceOf(address(this)); stakingToken.approve(address(stakingPool2), total); stakingPool2.deposit(pid2, total); } function stake(uint amount) virtual override public updateReward2(msg.sender) { super.stake(amount); stakingToken.approve(address(stakingPool2), amount); stakingPool2.deposit(pid2, amount); } function withdraw(uint amount) virtual override public updateReward2(msg.sender) { stakingPool2.withdraw(pid2, amount); super.withdraw(amount); } function getReward2() virtual public nonReentrant updateReward2(msg.sender) { uint256 reward2 = rewards2[msg.sender]; if (reward2 > 0) { rewards2[msg.sender] = 0; rewardsToken2.safeTransfer(msg.sender, reward2); emit RewardPaid2(msg.sender, reward2); } } event RewardPaid2(address indexed user, uint256 reward2); function getDoubleReward() virtual public { getReward(); getReward2(); } function exit() virtual override public { super.exit(); getReward2(); } function rewardPerToken2() virtual public view returns (uint256) { if(_totalSupply == 0) return _rewardPerToken2; else if(rewardsToken2 == Cake) return stakingPool2.pendingCake(pid2, address(this)).mul(1e18).div(_totalSupply).add(_rewardPerToken2); else return stakingPool2.pending(pid2, address(this)).mul(1e18).div(_totalSupply).add(_rewardPerToken2); } function earned2(address account) virtual public view returns (uint256) { return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]); } modifier updateReward2(address account) virtual { if(_totalSupply > 0) { uint delta = rewardsToken2.balanceOf(address(this)); stakingPool2.deposit(pid2, 0); delta = rewardsToken2.balanceOf(address(this)).sub(delta); _rewardPerToken2 = delta.mul(1e18).div(_totalSupply).add(_rewardPerToken2); } if (account != address(0)) { rewards2[account] = earned2(account); userRewardPerTokenPaid2[account] = _rewardPerToken2; } _; } uint256[50] private __gap; } contract IioPoolV2 is StakingPool { // support multi IIO at the same time //address internal constant HelmetAddress = 0x948d2a81086A075b3130BAc19e4c6DEe1D2E3fE8; address internal constant BurnAddress = 0x000000000000000000000000000000000000dEaD; uint private __lastUpdateTime3; // obsolete IERC20 private __rewardsToken3; // obsolete mapping(IERC20 => uint) public totalSupply3; // rewardsToken3 => totalSupply3 mapping(IERC20 => uint) internal _rewardPerToken3; // rewardsToken3 => _rewardPerToken3 mapping(IERC20 => uint) public begin3; // rewardsToken3 => begin3 mapping(IERC20 => uint) public end3; // rewardsToken3 => end3 mapping(IERC20 => uint) public claimTime3; // rewardsToken3 => claimTime3 mapping(IERC20 => uint) public ticketVol3; // rewardsToken3 => ticketVol3 mapping(IERC20 => IERC20) public ticketToken3; // rewardsToken3 => ticketToken3 mapping(IERC20 => address) public ticketRecipient3; // rewardsToken3 => ticketRecipient3 mapping(IERC20 => mapping(address => bool)) public applied3; // rewardsToken3 => acct => applied3 mapping(IERC20 => mapping(address => uint)) public userRewardPerTokenPaid3; // rewardsToken3 => acct => paid3 mapping(IERC20 => mapping(address => uint)) public rewards3; // rewardsToken3 => acct => rewards3 mapping(IERC20 => uint) public lastUpdateTime3; // rewardsToken3 => lastUpdateTime3 IERC20[] public all; // all rewardsToken3 IERC20[] public active; // active rewardsToken3 //function setReward3BurnHelmet(IERC20 rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_) virtual external { // setReward3(rewardsToken3_, begin3_, end3_, claimTime3_, ticketVol3_, IERC20(HelmetAddress), BurnAddress); //} function setReward3(IERC20 rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_, IERC20 ticketToken3_, address ticketRecipient3_) virtual public governance { lastUpdateTime3 [rewardsToken3_]= begin3_; //rewardsToken3 = rewardsToken3_; begin3 [rewardsToken3_] = begin3_; end3 [rewardsToken3_] = end3_; claimTime3 [rewardsToken3_] = claimTime3_; ticketVol3 [rewardsToken3_] = ticketVol3_; ticketToken3 [rewardsToken3_] = ticketToken3_; ticketRecipient3 [rewardsToken3_] = ticketRecipient3_; uint i=0; for(; i<all.length; i++) if(all[i] == rewardsToken3_) break; if(i>=all.length) all.push(rewardsToken3_); i=0; for(; i<active.length; i++) if(active[i] == rewardsToken3_) break; if(i>=active.length) active.push(rewardsToken3_); emit SetReward3(rewardsToken3_, begin3_, end3_, claimTime3_, ticketVol3_, ticketToken3_, ticketRecipient3_); } event SetReward3(IERC20 indexed rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_, IERC20 indexed ticketToken3_, address indexed ticketRecipient3_); //function deactive(IERC20 rewardsToken3_) virtual public governance { // for(uint i=0; i<active.length; i++) // if(active[i] == rewardsToken3_) { // active[i] = active[active.length-1]; // active.pop(); // emit Deactive(rewardsToken3_); // return; // } // revert('not found active rewardsToken3_'); //} //event Deactive(IERC20 indexed rewardsToken3_); function applyReward3(IERC20 rewardsToken3_) virtual public updateReward3(rewardsToken3_, msg.sender) { //IERC20 rewardsToken3_ = rewardsToken3; // save gas require(!applied3[rewardsToken3_][msg.sender], 'applied already'); require(now < end3[rewardsToken3_], 'expired'); IERC20 ticketToken3_ = ticketToken3[rewardsToken3_]; // save gas if(address(ticketToken3_) != address(0)) ticketToken3_.safeTransferFrom(msg.sender, ticketRecipient3[rewardsToken3_], ticketVol3[rewardsToken3_]); applied3[rewardsToken3_][msg.sender] = true; userRewardPerTokenPaid3[rewardsToken3_][msg.sender] = _rewardPerToken3[rewardsToken3_]; totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].add(_balances[msg.sender]); emit ApplyReward3(msg.sender, rewardsToken3_); } event ApplyReward3(address indexed acct, IERC20 indexed rewardsToken3); function rewardDelta3(IERC20 rewardsToken3_) virtual public view returns (uint amt) { //IERC20 rewardsToken3_ = rewardsToken3; // save gas uint lastUpdateTime3_ = lastUpdateTime3[rewardsToken3_]; // save gas if(begin3[rewardsToken3_] == 0 || begin3[rewardsToken3_] >= now || lastUpdateTime3_ >= now) return 0; amt = Math.min(rewardsToken3_.allowance(rewardsDistribution, address(this)), rewardsToken3_.balanceOf(rewardsDistribution)).sub0(rewards3[rewardsToken3_][address(0)]); uint end3_ = end3[rewardsToken3_]; // save gas if(now < end3_) amt = amt.mul(now.sub(lastUpdateTime3_)).div(end3_.sub(lastUpdateTime3_)); else if(lastUpdateTime3_ >= end3_) amt = 0; if(config[_ecoAddr_] != 0) amt = amt.mul(uint(1e18).sub(config[_ecoRatio_])).div(1 ether); } function rewardPerToken3(IERC20 rewardsToken3_) virtual public view returns (uint) { if (totalSupply3[rewardsToken3_] == 0) { return _rewardPerToken3[rewardsToken3_]; } return _rewardPerToken3[rewardsToken3_].add( rewardDelta3(rewardsToken3_).mul(1e18).div(totalSupply3[rewardsToken3_]) ); } function earned3(IERC20 rewardsToken3_, address account) virtual public view returns (uint) { if(!applied3[rewardsToken3_][account]) return 0; return Math.min(rewardsToken3_.balanceOf(rewardsDistribution), _balances[account].mul(rewardPerToken3(rewardsToken3_).sub(userRewardPerTokenPaid3[rewardsToken3_][account])).div(1e18).add(rewards3[rewardsToken3_][account])); } function _updateReward3(IERC20 rewardsToken3_, address account) virtual internal { bool applied3_ = applied3[rewardsToken3_][account]; // save gas if(account == address(0) || applied3_) { _rewardPerToken3[rewardsToken3_] = rewardPerToken3(rewardsToken3_); uint delta = rewardDelta3(rewardsToken3_); { address addr = address(config[_ecoAddr_]); uint ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) { uint d = delta.mul(ratio).div(uint(1e18).sub(ratio)); rewards3[rewardsToken3_][addr] = rewards3[rewardsToken3_][addr].add(d); delta = delta.add(d); } } rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].add(delta); lastUpdateTime3[rewardsToken3_] = Math.max(begin3[rewardsToken3_], Math.min(now, end3[rewardsToken3_])); } if (account != address(0) && applied3_) { rewards3[rewardsToken3_][account] = earned3(rewardsToken3_, account); userRewardPerTokenPaid3[rewardsToken3_][account] = _rewardPerToken3[rewardsToken3_]; } } modifier updateReward3(IERC20 rewardsToken3_, address account) virtual { _updateReward3(rewardsToken3_, account); _; } function stake(uint amount) virtual override public { super.stake(amount); for(uint i=0; i<active.length; i++) { IERC20 rewardsToken3_ = active[i]; // save gas _updateReward3(rewardsToken3_, msg.sender); if(applied3[rewardsToken3_][msg.sender]) totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].add(amount); } } function withdraw(uint amount) virtual override public { for(uint i=0; i<active.length; i++) { IERC20 rewardsToken3_ = active[i]; // save gas _updateReward3(rewardsToken3_, msg.sender); if(applied3[rewardsToken3_][msg.sender]) totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].sub(amount); } super.withdraw(amount); } function getReward3(IERC20 rewardsToken3_) virtual public nonReentrant updateReward3(rewardsToken3_, msg.sender) { require(getConfigA(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, msg.sender) != 0, 'No allowContract'); //IERC20 rewardsToken3_ = rewardsToken3; // save gas require(now >= claimTime3[rewardsToken3_], "it's not time yet"); uint256 reward3 = rewards3[rewardsToken3_][msg.sender]; if (reward3 > 0) { rewards3[rewardsToken3_][msg.sender] = 0; rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].sub0(reward3); rewardsToken3_.safeTransferFrom(rewardsDistribution, msg.sender, reward3); emit RewardPaid3(msg.sender, rewardsToken3_, reward3); } } event RewardPaid3(address indexed user, IERC20 indexed rewardsToken3_, uint256 reward3); uint[47] private __gap; } contract NestMasterChefIioV2 is NestMasterChef, IioPoolV2 { function notifyRewardBegin(uint _lep, /*uint _period,*/ uint _span, uint _begin) virtual override(StakingPool, NestMasterChef) public { NestMasterChef.notifyRewardBegin(_lep, /*_period,*/ _span, _begin); } function stake(uint amount) virtual override(NestMasterChef, IioPoolV2) public { super.stake(amount); } function withdraw(uint amount) virtual override(NestMasterChef, IioPoolV2) public { super.withdraw(amount); } function exit() virtual override(StakingRewards, NestMasterChef) public { NestMasterChef.exit(); } uint[50] private __gap; } contract BurningPool is StakingPool { address internal constant BurnAddress = 0x000000000000000000000000000000000000dEaD; function stake(uint256 amount) virtual override public { super.stake(amount); stakingToken.safeTransfer(BurnAddress, stakingToken.balanceOf(address(this))); } function withdraw(uint256) virtual override public { revert('Burned already, none to withdraw'); } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract Mine is Governable { using SafeERC20 for IERC20; address public reward; function __Mine_init(address governor, address reward_) public initializer { __Governable_init_unchained(governor); __Mine_init_unchained(reward_); } function __Mine_init_unchained(address reward_) public governance { reward = reward_; } function approvePool(address pool, uint amount) public governance { IERC20(reward).approve(pool, amount); } function approveToken(address token, address pool, uint amount) public governance { IERC20(token).approve(pool, amount); } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
Inheritancea Views Mutative
interface IStakingRewards { function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewards(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; }
7,017,655
[ 1, 28255, 69, 31117, 14138, 1535, 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, 5831, 467, 510, 6159, 17631, 14727, 288, 203, 565, 445, 31323, 17631, 1060, 27873, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 19890, 2173, 1345, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 283, 6397, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 425, 1303, 329, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4170, 359, 1060, 1290, 5326, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 565, 445, 384, 911, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 4170, 359, 1060, 1435, 3903, 31, 203, 203, 565, 445, 2427, 1435, 3903, 31, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-01-07 */ // the azimuth logic contract // https://azimuth.network pragma solidity 0.4.24; //////////////////////////////////////////////////////////////////////////////// // Imports //////////////////////////////////////////////////////////////////////////////// // OpenZeppelin's Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // Azimuth's SafeMath8.sol /** * @title SafeMath8 * @dev Math operations for uint8 with safety checks that throw on error */ library SafeMath8 { function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } // Azimuth's SafeMath16.sol /** * @title SafeMath16 * @dev Math operations for uint16 with safety checks that throw on error */ library SafeMath16 { function mul(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } // OpenZeppelin's SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // OpenZeppelin's ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // OpenZeppelin's SupportsInterfaceWithLookup.sol /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // OpenZeppelin's ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // OpenZeppelin's ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // OpenZeppelin's ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // OpenZeppelin's AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // Azimuth's Azimuth.sol // Azimuth: point state data contract // // This contract is used for storing all data related to Azimuth points // and their ownership. Consider this contract the Azimuth ledger. // // It also contains permissions data, which ties in to ERC721 // functionality. Operators of an address are allowed to transfer // ownership of all points owned by their associated address // (ERC721's approveAll()). A transfer proxy is allowed to transfer // ownership of a single point (ERC721's approve()). // Separate from ERC721 are managers, assigned per point. They are // allowed to perform "low-impact" operations on the owner's points, // like configuring public keys and making escape requests. // // Since data stores are difficult to upgrade, this contract contains // as little actual business logic as possible. Instead, the data stored // herein can only be modified by this contract's owner, which can be // changed and is thus upgradable/replaceable. // // This contract will be owned by the Ecliptic contract. // contract Azimuth is Ownable { // // Events // // OwnerChanged: :point is now owned by :owner // event OwnerChanged(uint32 indexed point, address indexed owner); // Activated: :point is now active // event Activated(uint32 indexed point); // Spawned: :prefix has spawned :child // event Spawned(uint32 indexed prefix, uint32 indexed child); // EscapeRequested: :point has requested a new :sponsor // event EscapeRequested(uint32 indexed point, uint32 indexed sponsor); // EscapeCanceled: :point's :sponsor request was canceled or rejected // event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor); // EscapeAccepted: :point confirmed with a new :sponsor // event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor); // LostSponsor: :point's :sponsor is now refusing it service // event LostSponsor(uint32 indexed point, uint32 indexed sponsor); // ChangedKeys: :point has new network public keys // event ChangedKeys( uint32 indexed point, bytes32 encryptionKey, bytes32 authenticationKey, uint32 cryptoSuiteVersion, uint32 keyRevisionNumber ); // BrokeContinuity: :point has a new continuity number, :number // event BrokeContinuity(uint32 indexed point, uint32 number); // ChangedSpawnProxy: :spawnProxy can now spawn using :point // event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy); // ChangedTransferProxy: :transferProxy can now transfer ownership of :point // event ChangedTransferProxy( uint32 indexed point, address indexed transferProxy ); // ChangedManagementProxy: :managementProxy can now manage :point // event ChangedManagementProxy( uint32 indexed point, address indexed managementProxy ); // ChangedVotingProxy: :votingProxy can now vote using :point // event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy); // ChangedDns: dnsDomains have been updated // event ChangedDns(string primary, string secondary, string tertiary); // // Structures // // Size: kinds of points registered on-chain // // NOTE: the order matters, because of Solidity enum numbering // enum Size { Galaxy, // = 0 Star, // = 1 Planet // = 2 } // Point: state of a point // // While the ordering of the struct members is semantically chaotic, // they are ordered to tightly pack them into Ethereum's 32-byte storage // slots, which reduces gas costs for some function calls. // The comment ticks indicate assumed slot boundaries. // struct Point { // encryptionKey: (curve25519) encryption public key, or 0 for none // bytes32 encryptionKey; // // authenticationKey: (ed25519) authentication public key, or 0 for none // bytes32 authenticationKey; // // spawned: for stars and galaxies, all :active children // uint32[] spawned; // // hasSponsor: true if the sponsor still supports the point // bool hasSponsor; // active: whether point can be linked // // false: point belongs to prefix, cannot be configured or linked // true: point no longer belongs to prefix, can be configured and linked // bool active; // escapeRequested: true if the point has requested to change sponsors // bool escapeRequested; // sponsor: the point that supports this one on the network, or, // if :hasSponsor is false, the last point that supported it. // (by default, the point's half-width prefix) // uint32 sponsor; // escapeRequestedTo: if :escapeRequested is true, new sponsor requested // uint32 escapeRequestedTo; // cryptoSuiteVersion: version of the crypto suite used for the pubkeys // uint32 cryptoSuiteVersion; // keyRevisionNumber: incremented every time the public keys change // uint32 keyRevisionNumber; // continuityNumber: incremented to indicate network-side state loss // uint32 continuityNumber; } // Deed: permissions for a point // struct Deed { // owner: address that owns this point // address owner; // managementProxy: 0, or another address with the right to perform // low-impact, managerial operations on this point // address managementProxy; // spawnProxy: 0, or another address with the right to spawn children // of this point // address spawnProxy; // votingProxy: 0, or another address with the right to vote as this point // address votingProxy; // transferProxy: 0, or another address with the right to transfer // ownership of this point // address transferProxy; } // // General state // // points: per point, general network-relevant point state // mapping(uint32 => Point) public points; // rights: per point, on-chain ownership and permissions // mapping(uint32 => Deed) public rights; // operators: per owner, per address, has the right to transfer ownership // of all the owner's points (ERC721) // mapping(address => mapping(address => bool)) public operators; // dnsDomains: base domains for contacting galaxies // // dnsDomains[0] is primary, the others are used as fallbacks // string[3] public dnsDomains; // // Lookups // // sponsoring: per point, the points they are sponsoring // mapping(uint32 => uint32[]) public sponsoring; // sponsoringIndexes: per point, per point, (index + 1) in // the sponsoring array // mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes; // escapeRequests: per point, the points they have open escape requests from // mapping(uint32 => uint32[]) public escapeRequests; // escapeRequestsIndexes: per point, per point, (index + 1) in // the escapeRequests array // mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes; // pointsOwnedBy: per address, the points they own // mapping(address => uint32[]) public pointsOwnedBy; // pointOwnerIndexes: per owner, per point, (index + 1) in // the pointsOwnedBy array // // We delete owners by moving the last entry in the array to the // newly emptied slot, which is (n - 1) where n is the value of // pointOwnerIndexes[owner][point]. // mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes; // managerFor: per address, the points they are the management proxy for // mapping(address => uint32[]) public managerFor; // managerForIndexes: per address, per point, (index + 1) in // the managerFor array // mapping(address => mapping(uint32 => uint256)) public managerForIndexes; // spawningFor: per address, the points they can spawn with // mapping(address => uint32[]) public spawningFor; // spawningForIndexes: per address, per point, (index + 1) in // the spawningFor array // mapping(address => mapping(uint32 => uint256)) public spawningForIndexes; // votingFor: per address, the points they can vote with // mapping(address => uint32[]) public votingFor; // votingForIndexes: per address, per point, (index + 1) in // the votingFor array // mapping(address => mapping(uint32 => uint256)) public votingForIndexes; // transferringFor: per address, the points they can transfer // mapping(address => uint32[]) public transferringFor; // transferringForIndexes: per address, per point, (index + 1) in // the transferringFor array // mapping(address => mapping(uint32 => uint256)) public transferringForIndexes; // // Logic // // constructor(): configure default dns domains // constructor() public { setDnsDomains("example.com", "example.com", "example.com"); } // setDnsDomains(): set the base domains used for contacting galaxies // // Note: since a string is really just a byte[], and Solidity can't // work with two-dimensional arrays yet, we pass in the three // domains as individual strings. // function setDnsDomains(string _primary, string _secondary, string _tertiary) onlyOwner public { dnsDomains[0] = _primary; dnsDomains[1] = _secondary; dnsDomains[2] = _tertiary; emit ChangedDns(_primary, _secondary, _tertiary); } // // Point reading // // isActive(): return true if _point is active // function isActive(uint32 _point) view external returns (bool equals) { return points[_point].active; } // getKeys(): returns the public keys and their details, as currently // registered for _point // function getKeys(uint32 _point) view external returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision) { Point storage point = points[_point]; return (point.encryptionKey, point.authenticationKey, point.cryptoSuiteVersion, point.keyRevisionNumber); } // getKeyRevisionNumber(): gets the revision number of _point's current // public keys // function getKeyRevisionNumber(uint32 _point) view external returns (uint32 revision) { return points[_point].keyRevisionNumber; } // hasBeenLinked(): returns true if the point has ever been assigned keys // function hasBeenLinked(uint32 _point) view external returns (bool result) { return ( points[_point].keyRevisionNumber > 0 ); } // isLive(): returns true if _point currently has keys properly configured // function isLive(uint32 _point) view external returns (bool result) { Point storage point = points[_point]; return ( point.encryptionKey != 0 && point.authenticationKey != 0 && point.cryptoSuiteVersion != 0 ); } // getContinuityNumber(): returns _point's current continuity number // function getContinuityNumber(uint32 _point) view external returns (uint32 continuityNumber) { return points[_point].continuityNumber; } // getSpawnCount(): return the number of children spawned by _point // function getSpawnCount(uint32 _point) view external returns (uint32 spawnCount) { uint256 len = points[_point].spawned.length; assert(len < 2**32); return uint32(len); } // getSpawned(): return array of points created under _point // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawned(uint32 _point) view external returns (uint32[] spawned) { return points[_point].spawned; } // hasSponsor(): returns true if _point's sponsor is providing it service // function hasSponsor(uint32 _point) view external returns (bool has) { return points[_point].hasSponsor; } // getSponsor(): returns _point's current (or most recent) sponsor // function getSponsor(uint32 _point) view external returns (uint32 sponsor) { return points[_point].sponsor; } // isSponsor(): returns true if _sponsor is currently providing service // to _point // function isSponsor(uint32 _point, uint32 _sponsor) view external returns (bool result) { Point storage point = points[_point]; return ( point.hasSponsor && (point.sponsor == _sponsor) ); } // getSponsoringCount(): returns the number of points _sponsor is // providing service to // function getSponsoringCount(uint32 _sponsor) view external returns (uint256 count) { return sponsoring[_sponsor].length; } // getSponsoring(): returns a list of points _sponsor is providing // service to // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSponsoring(uint32 _sponsor) view external returns (uint32[] sponsees) { return sponsoring[_sponsor]; } // escaping // isEscaping(): returns true if _point has an outstanding escape request // function isEscaping(uint32 _point) view external returns (bool escaping) { return points[_point].escapeRequested; } // getEscapeRequest(): returns _point's current escape request // // the returned escape request is only valid as long as isEscaping() // returns true // function getEscapeRequest(uint32 _point) view external returns (uint32 escape) { return points[_point].escapeRequestedTo; } // isRequestingEscapeTo(): returns true if _point has an outstanding // escape request targetting _sponsor // function isRequestingEscapeTo(uint32 _point, uint32 _sponsor) view public returns (bool equals) { Point storage point = points[_point]; return (point.escapeRequested && (point.escapeRequestedTo == _sponsor)); } // getEscapeRequestsCount(): returns the number of points _sponsor // is providing service to // function getEscapeRequestsCount(uint32 _sponsor) view external returns (uint256 count) { return escapeRequests[_sponsor].length; } // getEscapeRequests(): get the points _sponsor has received escape // requests from // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getEscapeRequests(uint32 _sponsor) view external returns (uint32[] requests) { return escapeRequests[_sponsor]; } // // Point writing // // activatePoint(): activate a point, register it as spawned by its prefix // function activatePoint(uint32 _point) onlyOwner external { // make a point active, setting its sponsor to its prefix // Point storage point = points[_point]; require(!point.active); point.active = true; registerSponsor(_point, true, getPrefix(_point)); emit Activated(_point); } // setKeys(): set network public keys of _point to _encryptionKey and // _authenticationKey, with the specified _cryptoSuiteVersion // function setKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion) onlyOwner external { Point storage point = points[_point]; if ( point.encryptionKey == _encryptionKey && point.authenticationKey == _authenticationKey && point.cryptoSuiteVersion == _cryptoSuiteVersion ) { return; } point.encryptionKey = _encryptionKey; point.authenticationKey = _authenticationKey; point.cryptoSuiteVersion = _cryptoSuiteVersion; point.keyRevisionNumber++; emit ChangedKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion, point.keyRevisionNumber); } // incrementContinuityNumber(): break continuity for _point // function incrementContinuityNumber(uint32 _point) onlyOwner external { Point storage point = points[_point]; point.continuityNumber++; emit BrokeContinuity(_point, point.continuityNumber); } // registerSpawn(): add a point to its prefix's list of spawned points // function registerSpawned(uint32 _point) onlyOwner external { // if a point is its own prefix (a galaxy) then don't register it // uint32 prefix = getPrefix(_point); if (prefix == _point) { return; } // register a new spawned point for the prefix // points[prefix].spawned.push(_point); emit Spawned(prefix, _point); } // loseSponsor(): indicates that _point's sponsor is no longer providing // it service // function loseSponsor(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.hasSponsor) { return; } registerSponsor(_point, false, point.sponsor); emit LostSponsor(_point, point.sponsor); } // setEscapeRequest(): for _point, start an escape request to _sponsor // function setEscapeRequest(uint32 _point, uint32 _sponsor) onlyOwner external { if (isRequestingEscapeTo(_point, _sponsor)) { return; } registerEscapeRequest(_point, true, _sponsor); emit EscapeRequested(_point, _sponsor); } // cancelEscape(): for _point, stop the current escape request, if any // function cancelEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.escapeRequested) { return; } uint32 request = point.escapeRequestedTo; registerEscapeRequest(_point, false, 0); emit EscapeCanceled(_point, request); } // doEscape(): perform the requested escape // function doEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; require(point.escapeRequested); registerSponsor(_point, true, point.escapeRequestedTo); registerEscapeRequest(_point, false, 0); emit EscapeAccepted(_point, point.sponsor); } // // Point utils // // getPrefix(): compute prefix ("parent") of _point // function getPrefix(uint32 _point) pure public returns (uint16 prefix) { if (_point < 0x10000) { return uint16(_point % 0x100); } return uint16(_point % 0x10000); } // getPointSize(): return the size of _point // function getPointSize(uint32 _point) external pure returns (Size _size) { if (_point < 0x100) return Size.Galaxy; if (_point < 0x10000) return Size.Star; return Size.Planet; } // internal use // registerSponsor(): set the sponsorship state of _point and update the // reverse lookup for sponsors // function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor) internal { Point storage point = points[_point]; bool had = point.hasSponsor; uint32 prev = point.sponsor; // if we didn't have a sponsor, and won't get one, // or if we get the sponsor we already have, // nothing will change, so jump out early. // if ( (!had && !_hasSponsor) || (had && _hasSponsor && prev == _sponsor) ) { return; } // if the point used to have a different sponsor, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (had) { // i: current index in previous sponsor's list of sponsored points // uint256 i = sponsoringIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :sponsoringIndexes reference // uint32[] storage prevSponsoring = sponsoring[prev]; uint256 last = prevSponsoring.length - 1; uint32 moved = prevSponsoring[last]; prevSponsoring[i] = moved; sponsoringIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSponsoring[last]); prevSponsoring.length = last; sponsoringIndexes[prev][_point] = 0; } if (_hasSponsor) { uint32[] storage newSponsoring = sponsoring[_sponsor]; newSponsoring.push(_point); sponsoringIndexes[_sponsor][_point] = newSponsoring.length; } point.sponsor = _sponsor; point.hasSponsor = _hasSponsor; } // registerEscapeRequest(): set the escape state of _point and update the // reverse lookup for sponsors // function registerEscapeRequest( uint32 _point, bool _isEscaping, uint32 _sponsor ) internal { Point storage point = points[_point]; bool was = point.escapeRequested; uint32 prev = point.escapeRequestedTo; // if we weren't escaping, and won't be, // or if we were escaping, and the new target is the same, // nothing will change, so jump out early. // if ( (!was && !_isEscaping) || (was && _isEscaping && prev == _sponsor) ) { return; } // if the point used to have a different request, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (was) { // i: current index in previous sponsor's list of sponsored points // uint256 i = escapeRequestsIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :escapeRequestsIndexes reference // uint32[] storage prevRequests = escapeRequests[prev]; uint256 last = prevRequests.length - 1; uint32 moved = prevRequests[last]; prevRequests[i] = moved; escapeRequestsIndexes[prev][moved] = i + 1; // delete the last item // delete(prevRequests[last]); prevRequests.length = last; escapeRequestsIndexes[prev][_point] = 0; } if (_isEscaping) { uint32[] storage newRequests = escapeRequests[_sponsor]; newRequests.push(_point); escapeRequestsIndexes[_sponsor][_point] = newRequests.length; } point.escapeRequestedTo = _sponsor; point.escapeRequested = _isEscaping; } // // Deed reading // // owner // getOwner(): return owner of _point // function getOwner(uint32 _point) view external returns (address owner) { return rights[_point].owner; } // isOwner(): true if _point is owned by _address // function isOwner(uint32 _point, address _address) view external returns (bool result) { return (rights[_point].owner == _address); } // getOwnedPointCount(): return length of array of points that _whose owns // function getOwnedPointCount(address _whose) view external returns (uint256 count) { return pointsOwnedBy[_whose].length; } // getOwnedPoints(): return array of points that _whose owns // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getOwnedPoints(address _whose) view external returns (uint32[] ownedPoints) { return pointsOwnedBy[_whose]; } // getOwnedPointAtIndex(): get point at _index from array of points that // _whose owns // function getOwnedPointAtIndex(address _whose, uint256 _index) view external returns (uint32 point) { uint32[] storage owned = pointsOwnedBy[_whose]; require(_index < owned.length); return owned[_index]; } // management proxy // getManagementProxy(): returns _point's current management proxy // function getManagementProxy(uint32 _point) view external returns (address manager) { return rights[_point].managementProxy; } // isManagementProxy(): returns true if _proxy is _point's management proxy // function isManagementProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].managementProxy == _proxy); } // canManage(): true if _who is the owner or manager of _point // function canManage(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.managementProxy) ) ); } // getManagerForCount(): returns the amount of points _proxy can manage // function getManagerForCount(address _proxy) view external returns (uint256 count) { return managerFor[_proxy].length; } // getManagerFor(): returns the points _proxy can manage // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getManagerFor(address _proxy) view external returns (uint32[] mfor) { return managerFor[_proxy]; } // spawn proxy // getSpawnProxy(): returns _point's current spawn proxy // function getSpawnProxy(uint32 _point) view external returns (address spawnProxy) { return rights[_point].spawnProxy; } // isSpawnProxy(): returns true if _proxy is _point's spawn proxy // function isSpawnProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].spawnProxy == _proxy); } // canSpawnAs(): true if _who is the owner or spawn proxy of _point // function canSpawnAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.spawnProxy) ) ); } // getSpawningForCount(): returns the amount of points _proxy // can spawn with // function getSpawningForCount(address _proxy) view external returns (uint256 count) { return spawningFor[_proxy].length; } // getSpawningFor(): get the points _proxy can spawn with // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawningFor(address _proxy) view external returns (uint32[] sfor) { return spawningFor[_proxy]; } // voting proxy // getVotingProxy(): returns _point's current voting proxy // function getVotingProxy(uint32 _point) view external returns (address voter) { return rights[_point].votingProxy; } // isVotingProxy(): returns true if _proxy is _point's voting proxy // function isVotingProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].votingProxy == _proxy); } // canVoteAs(): true if _who is the owner of _point, // or the voting proxy of _point's owner // function canVoteAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.votingProxy) ) ); } // getVotingForCount(): returns the amount of points _proxy can vote as // function getVotingForCount(address _proxy) view external returns (uint256 count) { return votingFor[_proxy].length; } // getVotingFor(): returns the points _proxy can vote as // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getVotingFor(address _proxy) view external returns (uint32[] vfor) { return votingFor[_proxy]; } // transfer proxy // getTransferProxy(): returns _point's current transfer proxy // function getTransferProxy(uint32 _point) view external returns (address transferProxy) { return rights[_point].transferProxy; } // isTransferProxy(): returns true if _proxy is _point's transfer proxy // function isTransferProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].transferProxy == _proxy); } // canTransfer(): true if _who is the owner or transfer proxy of _point, // or is an operator for _point's current owner // function canTransfer(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.transferProxy) || operators[deed.owner][_who] ) ); } // getTransferringForCount(): returns the amount of points _proxy // can transfer // function getTransferringForCount(address _proxy) view external returns (uint256 count) { return transferringFor[_proxy].length; } // getTransferringFor(): get the points _proxy can transfer // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getTransferringFor(address _proxy) view external returns (uint32[] tfor) { return transferringFor[_proxy]; } // isOperator(): returns true if _operator is allowed to transfer // ownership of _owner's points // function isOperator(address _owner, address _operator) view external returns (bool result) { return operators[_owner][_operator]; } // // Deed writing // // setOwner(): set owner of _point to _owner // // Note: setOwner() only implements the minimal data storage // logic for a transfer; the full transfer is implemented in // Ecliptic. // // Note: _owner must not be the zero address. // function setOwner(uint32 _point, address _owner) onlyOwner external { // prevent burning of points by making zero the owner // require(0x0 != _owner); // prev: previous owner, if any // address prev = rights[_point].owner; if (prev == _owner) { return; } // if the point used to have a different owner, do some gymnastics to // keep the list of owned points gapless. delete this point from the // list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous owner's list of owned points // uint256 i = pointOwnerIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :pointOwnerIndexes reference // uint32[] storage owner = pointsOwnedBy[prev]; uint256 last = owner.length - 1; uint32 moved = owner[last]; owner[i] = moved; pointOwnerIndexes[prev][moved] = i + 1; // delete the last item // delete(owner[last]); owner.length = last; pointOwnerIndexes[prev][_point] = 0; } // update the owner list and the owner's index list // rights[_point].owner = _owner; pointsOwnedBy[_owner].push(_point); pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length; emit OwnerChanged(_point, _owner); } // setManagementProxy(): makes _proxy _point's management proxy // function setManagementProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.managementProxy; if (prev == _proxy) { return; } // if the point used to have a different manager, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old manager's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous manager's list of managed points // uint256 i = managerForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :managerForIndexes reference // uint32[] storage prevMfor = managerFor[prev]; uint256 last = prevMfor.length - 1; uint32 moved = prevMfor[last]; prevMfor[i] = moved; managerForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevMfor[last]); prevMfor.length = last; managerForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage mfor = managerFor[_proxy]; mfor.push(_point); managerForIndexes[_proxy][_point] = mfor.length; } deed.managementProxy = _proxy; emit ChangedManagementProxy(_point, _proxy); } // setSpawnProxy(): makes _proxy _point's spawn proxy // function setSpawnProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.spawnProxy; if (prev == _proxy) { return; } // if the point used to have a different spawn proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of spawning points // uint256 i = spawningForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :spawningForIndexes reference // uint32[] storage prevSfor = spawningFor[prev]; uint256 last = prevSfor.length - 1; uint32 moved = prevSfor[last]; prevSfor[i] = moved; spawningForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSfor[last]); prevSfor.length = last; spawningForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage sfor = spawningFor[_proxy]; sfor.push(_point); spawningForIndexes[_proxy][_point] = sfor.length; } deed.spawnProxy = _proxy; emit ChangedSpawnProxy(_point, _proxy); } // setVotingProxy(): makes _proxy _point's voting proxy // function setVotingProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.votingProxy; if (prev == _proxy) { return; } // if the point used to have a different voter, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old voter's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous voter's list of points it was // voting for // uint256 i = votingForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :votingForIndexes reference // uint32[] storage prevVfor = votingFor[prev]; uint256 last = prevVfor.length - 1; uint32 moved = prevVfor[last]; prevVfor[i] = moved; votingForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevVfor[last]); prevVfor.length = last; votingForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage vfor = votingFor[_proxy]; vfor.push(_point); votingForIndexes[_proxy][_point] = vfor.length; } deed.votingProxy = _proxy; emit ChangedVotingProxy(_point, _proxy); } // setManagementProxy(): makes _proxy _point's transfer proxy // function setTransferProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.transferProxy; if (prev == _proxy) { return; } // if the point used to have a different transfer proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of transferable points // uint256 i = transferringForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :transferringForIndexes reference // uint32[] storage prevTfor = transferringFor[prev]; uint256 last = prevTfor.length - 1; uint32 moved = prevTfor[last]; prevTfor[i] = moved; transferringForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevTfor[last]); prevTfor.length = last; transferringForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage tfor = transferringFor[_proxy]; tfor.push(_point); transferringForIndexes[_proxy][_point] = tfor.length; } deed.transferProxy = _proxy; emit ChangedTransferProxy(_point, _proxy); } // setOperator(): dis/allow _operator to transfer ownership of all points // owned by _owner // // operators are part of the ERC721 standard // function setOperator(address _owner, address _operator, bool _approved) onlyOwner external { operators[_owner][_operator] = _approved; } } // Azimuth's ReadsAzimuth.sol // ReadsAzimuth: referring to and testing against the Azimuth // data contract // // To avoid needless repetition, this contract provides common // checks and operations using the Azimuth contract. // contract ReadsAzimuth { // azimuth: points data storage contract. // Azimuth public azimuth; // constructor(): set the Azimuth data contract's address // constructor(Azimuth _azimuth) public { azimuth = _azimuth; } // activePointOwner(): require that :msg.sender is the owner of _point, // and that _point is active // modifier activePointOwner(uint32 _point) { require( azimuth.isOwner(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointManager(): require that :msg.sender can manage _point, // and that _point is active // modifier activePointManager(uint32 _point) { require( azimuth.canManage(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointSpawner(): require that :msg.sender can spawn as _point, // and that _point is active // modifier activePointSpawner(uint32 _point) { require( azimuth.canSpawnAs(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointVoter(): require that :msg.sender can vote as _point, // and that _point is active // modifier activePointVoter(uint32 _point) { require( azimuth.canVoteAs(_point, msg.sender) && azimuth.isActive(_point) ); _; } } // Azimuth's Polls.sol // Polls: proposals & votes data contract // // This contract is used for storing all data related to the proposals // of the senate (galaxy owners) and their votes on those proposals. // It keeps track of votes and uses them to calculate whether a majority // is in favor of a proposal. // // Every galaxy can only vote on a proposal exactly once. Votes cannot // be changed. If a proposal fails to achieve majority within its // duration, it can be restarted after its cooldown period has passed. // // The requirements for a proposal to achieve majority are as follows: // - At least 1/4 of the currently active voters (rounded down) must have // voted in favor of the proposal, // - More than half of the votes cast must be in favor of the proposal, // and this can no longer change, either because // - the poll duration has passed, or // - not enough voters remain to take away the in-favor majority. // As soon as these conditions are met, no further interaction with // the proposal is possible. Achieving majority is permanent. // // Since data stores are difficult to upgrade, all of the logic unrelated // to the voting itself (that is, determining who is eligible to vote) // is expected to be implemented by this contract's owner. // // This contract will be owned by the Ecliptic contract. // contract Polls is Ownable { using SafeMath for uint256; using SafeMath16 for uint16; using SafeMath8 for uint8; // UpgradePollStarted: a poll on :proposal has opened // event UpgradePollStarted(address proposal); // DocumentPollStarted: a poll on :proposal has opened // event DocumentPollStarted(bytes32 proposal); // UpgradeMajority: :proposal has achieved majority // event UpgradeMajority(address proposal); // DocumentMajority: :proposal has achieved majority // event DocumentMajority(bytes32 proposal); // Poll: full poll state // struct Poll { // start: the timestamp at which the poll was started // uint256 start; // voted: per galaxy, whether they have voted on this poll // bool[256] voted; // yesVotes: amount of votes in favor of the proposal // uint16 yesVotes; // noVotes: amount of votes against the proposal // uint16 noVotes; // duration: amount of time during which the poll can be voted on // uint256 duration; // cooldown: amount of time before the (non-majority) poll can be reopened // uint256 cooldown; } // pollDuration: duration set for new polls. see also Poll.duration above // uint256 public pollDuration; // pollCooldown: cooldown set for new polls. see also Poll.cooldown above // uint256 public pollCooldown; // totalVoters: amount of active galaxies // uint16 public totalVoters; // upgradeProposals: list of all upgrades ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // address[] public upgradeProposals; // upgradePolls: per address, poll held to determine if that address // will become the new ecliptic // mapping(address => Poll) public upgradePolls; // upgradeHasAchievedMajority: per address, whether that address // has ever achieved majority // // If we did not store this, we would have to look at old poll data // to see whether or not a proposal has ever achieved majority. // Since the outcome of a poll is calculated based on :totalVoters, // which may not be consistent across time, we need to store outcomes // explicitly instead of re-calculating them. This allows us to always // tell with certainty whether or not a majority was achieved, // regardless of the current :totalVoters. // mapping(address => bool) public upgradeHasAchievedMajority; // documentProposals: list of all documents ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // bytes32[] public documentProposals; // documentPolls: per hash, poll held to determine if the corresponding // document is accepted by the galactic senate // mapping(bytes32 => Poll) public documentPolls; // documentHasAchievedMajority: per hash, whether that hash has ever // achieved majority // // the note for upgradeHasAchievedMajority above applies here as well // mapping(bytes32 => bool) public documentHasAchievedMajority; // documentMajorities: all hashes that have achieved majority // bytes32[] public documentMajorities; // constructor(): initial contract configuration // constructor(uint256 _pollDuration, uint256 _pollCooldown) public { reconfigure(_pollDuration, _pollCooldown); } // reconfigure(): change poll duration and cooldown // function reconfigure(uint256 _pollDuration, uint256 _pollCooldown) public onlyOwner { require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) && (5 days <= _pollCooldown) && (_pollCooldown <= 90 days) ); pollDuration = _pollDuration; pollCooldown = _pollCooldown; } // incrementTotalVoters(): increase the amount of registered voters // function incrementTotalVoters() external onlyOwner { require(totalVoters < 256); totalVoters = totalVoters.add(1); } // getAllUpgradeProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getUpgradeProposals() external view returns (address[] proposals) { return upgradeProposals; } // getUpgradeProposalCount(): get the number of unique proposed upgrades // function getUpgradeProposalCount() external view returns (uint256 count) { return upgradeProposals.length; } // getAllDocumentProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentProposals() external view returns (bytes32[] proposals) { return documentProposals; } // getDocumentProposalCount(): get the number of unique proposed upgrades // function getDocumentProposalCount() external view returns (uint256 count) { return documentProposals.length; } // getDocumentMajorities(): return array of all document majorities // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentMajorities() external view returns (bytes32[] majorities) { return documentMajorities; } // hasVotedOnUpgradePoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal) external view returns (bool result) { return upgradePolls[_proposal].voted[_galaxy]; } // hasVotedOnDocumentPoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal) external view returns (bool result) { return documentPolls[_proposal].voted[_galaxy]; } // startUpgradePoll(): open a poll on making _proposal the new ecliptic // function startUpgradePoll(address _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); Poll storage poll = upgradePolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { upgradeProposals.push(_proposal); } startPoll(poll); emit UpgradePollStarted(_proposal); } // startDocumentPoll(): open a poll on accepting the document // whose hash is _proposal // function startDocumentPoll(bytes32 _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); Poll storage poll = documentPolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { documentProposals.push(_proposal); } startPoll(poll); emit DocumentPollStarted(_proposal); } // startPoll(): open a new poll, or re-open an old one // function startPoll(Poll storage _poll) internal { // check that the poll has cooled down enough to be started again // // for completely new polls, the values used will be zero // require( block.timestamp > ( _poll.start.add( _poll.duration.add( _poll.cooldown )) ) ); // set started poll state // _poll.start = block.timestamp; delete _poll.voted; _poll.yesVotes = 0; _poll.noVotes = 0; _poll.duration = pollDuration; _poll.cooldown = pollCooldown; } // castUpgradeVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castUpgradeVote(uint8 _as, address _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = upgradePolls[_proposal]; processVote(poll, _as, _vote); return updateUpgradePoll(_proposal); } // castDocumentVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = documentPolls[_proposal]; processVote(poll, _as, _vote); return updateDocumentPoll(_proposal); } // processVote(): record a vote from _as on the _poll // function processVote(Poll storage _poll, uint8 _as, bool _vote) internal { // assist symbolic execution tools // assert(block.timestamp >= _poll.start); require( // may only vote once // !_poll.voted[_as] && // // may only vote when the poll is open // (block.timestamp < _poll.start.add(_poll.duration)) ); // update poll state to account for the new vote // _poll.voted[_as] = true; if (_vote) { _poll.yesVotes = _poll.yesVotes.add(1); } else { _poll.noVotes = _poll.noVotes.add(1); } } // updateUpgradePoll(): check whether the _proposal has achieved // majority, updating state, sending an event, // and returning true if it has // function updateUpgradePoll(address _proposal) public onlyOwner returns (bool majority) { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = upgradePolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update the state and send an event // if (majority) { upgradeHasAchievedMajority[_proposal] = true; emit UpgradeMajority(_proposal); } return majority; } // updateDocumentPoll(): check whether the _proposal has achieved majority, // updating the state and sending an event if it has // // this can be called by anyone, because the ecliptic does not // need to be aware of the result // function updateDocumentPoll(bytes32 _proposal) public returns (bool majority) { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = documentPolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update state and send an event // if (majority) { documentHasAchievedMajority[_proposal] = true; documentMajorities.push(_proposal); emit DocumentMajority(_proposal); } return majority; } // checkPollMajority(): returns true if the majority is in favor of // the subject of the poll // function checkPollMajority(Poll _poll) internal view returns (bool majority) { return ( // poll must have at least the minimum required yes-votes // (_poll.yesVotes >= (totalVoters / 4)) && // // and have a majority... // (_poll.yesVotes > _poll.noVotes) && // // ...that is indisputable // ( // either because the poll has ended // (block.timestamp > _poll.start.add(_poll.duration)) || // // or there are more yes votes than there can be no votes // ( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) ); } } // Azimuth's Claims.sol // Claims: simple identity management // // This contract allows points to document claims about their owner. // Most commonly, these are about identity, with a claim's protocol // defining the context or platform of the claim, and its dossier // containing proof of its validity. // Points are limited to a maximum of 16 claims. // // For existing claims, the dossier can be updated, or the claim can // be removed entirely. It is recommended to remove any claims associated // with a point when it is about to be transferred to a new owner. // For convenience, the owner of the Azimuth contract (the Ecliptic) // is allowed to clear claims for any point, allowing it to do this for // you on-transfer. // contract Claims is ReadsAzimuth { // ClaimAdded: a claim was added by :by // event ClaimAdded( uint32 indexed by, string _protocol, string _claim, bytes _dossier ); // ClaimRemoved: a claim was removed by :by // event ClaimRemoved(uint32 indexed by, string _protocol, string _claim); // maxClaims: the amount of claims that can be registered per point // uint8 constant maxClaims = 16; // Claim: claim details // struct Claim { // protocol: context of the claim // string protocol; // claim: the claim itself // string claim; // dossier: data relating to the claim, as proof // bytes dossier; } // per point, list of claims // mapping(uint32 => Claim[maxClaims]) public claims; // constructor(): register the azimuth contract. // constructor(Azimuth _azimuth) ReadsAzimuth(_azimuth) public { // } // addClaim(): register a claim as _point // function addClaim(uint32 _point, string _protocol, string _claim, bytes _dossier) external activePointManager(_point) { // require non-empty protocol and claim fields // require( ( 0 < bytes(_protocol).length ) && ( 0 < bytes(_claim).length ) ); // cur: index + 1 of the claim if it already exists, 0 otherwise // uint8 cur = findClaim(_point, _protocol, _claim); // if the claim doesn't yet exist, store it in state // if (cur == 0) { // if there are no empty slots left, this throws // uint8 empty = findEmptySlot(_point); claims[_point][empty] = Claim(_protocol, _claim, _dossier); } // // if the claim has been made before, update the version in state // else { claims[_point][cur-1] = Claim(_protocol, _claim, _dossier); } emit ClaimAdded(_point, _protocol, _claim, _dossier); } // removeClaim(): unregister a claim as _point // function removeClaim(uint32 _point, string _protocol, string _claim) external activePointManager(_point) { // i: current index + 1 in _point's list of claims // uint256 i = findClaim(_point, _protocol, _claim); // we store index + 1, because 0 is the eth default value // can only delete an existing claim // require(i > 0); i--; // clear out the claim // delete claims[_point][i]; emit ClaimRemoved(_point, _protocol, _claim); } // clearClaims(): unregister all of _point's claims // // can also be called by the ecliptic during point transfer // function clearClaims(uint32 _point) external { // both point owner and ecliptic may do this // // We do not necessarily need to check for _point's active flag here, // since inactive points cannot have claims set. Doing the check // anyway would make this function slightly harder to think about due // to its relation to Ecliptic's transferPoint(). // require( azimuth.canManage(_point, msg.sender) || ( msg.sender == azimuth.owner() ) ); Claim[maxClaims] storage currClaims = claims[_point]; // clear out all claims // for (uint8 i = 0; i < maxClaims; i++) { // only emit the removed event if there was a claim here // if ( 0 < bytes(currClaims[i].claim).length ) { emit ClaimRemoved(_point, currClaims[i].protocol, currClaims[i].claim); } delete currClaims[i]; } } // findClaim(): find the index of the specified claim // // returns 0 if not found, index + 1 otherwise // function findClaim(uint32 _whose, string _protocol, string _claim) public view returns (uint8 index) { // we use hashes of the string because solidity can't do string // comparison yet // bytes32 protocolHash = keccak256(bytes(_protocol)); bytes32 claimHash = keccak256(bytes(_claim)); Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) && ( claimHash == keccak256(bytes(thisClaim.claim)) ) ) { return i+1; } } return 0; } // findEmptySlot(): find the index of the first empty claim slot // // returns the index of the slot, throws if there are no empty slots // function findEmptySlot(uint32 _whose) internal view returns (uint8 index) { Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( (0 == bytes(thisClaim.claim).length) ) { return i; } } revert(); } } // Azimuth's EclipticBase.sol // EclipticBase: upgradable ecliptic // // This contract implements the upgrade logic for the Ecliptic. // Newer versions of the Ecliptic are expected to provide at least // the onUpgrade() function. If they don't, upgrading to them will // fail. // // Note that even though this contract doesn't specify any required // interface members aside from upgrade() and onUpgrade(), contracts // and clients may still rely on the presence of certain functions // provided by the Ecliptic proper. Keep this in mind when writing // new versions of it. // contract EclipticBase is Ownable, ReadsAzimuth { // Upgraded: _to is the new canonical Ecliptic // event Upgraded(address to); // polls: senate voting contract // Polls public polls; // previousEcliptic: address of the previous ecliptic this // instance expects to upgrade from, stored and // checked for to prevent unexpected upgrade paths // address public previousEcliptic; constructor( address _previous, Azimuth _azimuth, Polls _polls ) ReadsAzimuth(_azimuth) internal { previousEcliptic = _previous; polls = _polls; } // onUpgrade(): called by previous ecliptic when upgrading // // in future ecliptics, this might perform more logic than // just simple checks and verifications. // when overriding this, make sure to call this original as well. // function onUpgrade() external { // make sure this is the expected upgrade path, // and that we have gotten the ownership we require // require( msg.sender == previousEcliptic && this == azimuth.owner() && this == polls.owner() ); } // upgrade(): transfer ownership of the ecliptic data to the new // ecliptic contract, notify it, then self-destruct. // // Note: any eth that have somehow ended up in this contract // are also sent to the new ecliptic. // function upgrade(EclipticBase _new) internal { // transfer ownership of the data contracts // azimuth.transferOwnership(_new); polls.transferOwnership(_new); // trigger upgrade logic on the target contract // _new.onUpgrade(); // emit event and destroy this contract // emit Upgraded(_new); selfdestruct(_new); } } //////////////////////////////////////////////////////////////////////////////// // Ecliptic //////////////////////////////////////////////////////////////////////////////// // Ecliptic: logic for interacting with the Azimuth ledger // // This contract is the point of entry for all operations on the Azimuth // ledger as stored in the Azimuth data contract. The functions herein // are responsible for performing all necessary business logic. // Examples of such logic include verifying permissions of the caller // and ensuring a requested change is actually valid. // Point owners can always operate on their own points. Ethereum addresses // can also perform specific operations if they've been given the // appropriate permissions. (For example, managers for general management, // spawn proxies for spawning child points, etc.) // // This contract uses external contracts (Azimuth, Polls) for data storage // so that it itself can easily be replaced in case its logic needs to // be changed. In other words, it can be upgraded. It does this by passing // ownership of the data contracts to a new Ecliptic contract. // // Because of this, it is advised for clients to not store this contract's // address directly, but rather ask the Azimuth contract for its owner // attribute to ensure transactions get sent to the latest Ecliptic. // Alternatively, the ENS name ecliptic.eth will resolve to the latest // Ecliptic as well. // // Upgrading happens based on polls held by the senate (galaxy owners). // Through this contract, the senate can submit proposals, opening polls // for the senate to cast votes on. These proposals can be either hashes // of documents or addresses of new Ecliptics. // If an ecliptic proposal gains majority, this contract will transfer // ownership of the data storage contracts to that address, so that it may // operate on the data they contain. This contract will selfdestruct at // the end of the upgrade process. // // This contract implements the ERC721 interface for non-fungible tokens, // allowing points to be managed using generic clients that support the // standard. It also implements ERC165 to allow this to be discovered. // contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata { using SafeMath for uint256; using AddressUtils for address; // Transfer: This emits when ownership of any NFT changes by any mechanism. // This event emits when NFTs are created (`from` == 0) and // destroyed (`to` == 0). At the time of any transfer, the // approved address for that NFT (if any) is reset to none. // event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); // Approval: This emits when the approved address for an NFT is changed or // reaffirmed. The zero address indicates there is no approved // address. When a Transfer event emits, this also indicates that // the approved address for that NFT (if any) is reset to none. // event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); // ApprovalForAll: This emits when an operator is enabled or disabled for an // owner. The operator can manage all NFTs of the owner. // event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // erc721Received: equal to: // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) // which can be also obtained as: // ERC721Receiver(0).onERC721Received.selector` bytes4 constant erc721Received = 0x150b7a02; // claims: contract reference, for clearing claims on-transfer // Claims public claims; // constructor(): set data contract addresses and signal interface support // // Note: during first deploy, ownership of these data contracts must // be manually transferred to this contract. // constructor(address _previous, Azimuth _azimuth, Polls _polls, Claims _claims) EclipticBase(_previous, _azimuth, _polls) public { claims = _claims; // register supported interfaces for ERC165 // _registerInterface(0x80ac58cd); // ERC721 _registerInterface(0x5b5e139f); // ERC721Metadata _registerInterface(0x7f5828d0); // ERC173 (ownership) } // // ERC721 interface // // balanceOf(): get the amount of points owned by _owner // function balanceOf(address _owner) public view returns (uint256 balance) { require(0x0 != _owner); return azimuth.getOwnedPointCount(_owner); } // ownerOf(): get the current owner of point _tokenId // function ownerOf(uint256 _tokenId) public view validPointId(_tokenId) returns (address owner) { uint32 id = uint32(_tokenId); // this will throw if the owner is the zero address, // active points always have a valid owner. // require(azimuth.isActive(id)); return azimuth.getOwner(id); } // exists(): returns true if point _tokenId is active // function exists(uint256 _tokenId) public view returns (bool doesExist) { return ( (_tokenId < 0x100000000) && azimuth.isActive(uint32(_tokenId)) ); } // safeTransferFrom(): transfer point _tokenId from _from to _to // function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { // transfer with empty data // safeTransferFrom(_from, _to, _tokenId, ""); } // safeTransferFrom(): transfer point _tokenId from _from to _to, // and call recipient if it's a contract // function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { // perform raw transfer // transferFrom(_from, _to, _tokenId); // do the callback last to avoid re-entrancy // if (_to.isContract()) { bytes4 retval = ERC721Receiver(_to) .onERC721Received(msg.sender, _from, _tokenId, _data); // // standard return idiom to confirm contract semantics // require(retval == erc721Received); } } // transferFrom(): transfer point _tokenId from _from to _to, // WITHOUT notifying recipient contract // function transferFrom(address _from, address _to, uint256 _tokenId) public validPointId(_tokenId) { uint32 id = uint32(_tokenId); require(azimuth.isOwner(id, _from)); // the ERC721 operator/approved address (if any) is // accounted for in transferPoint() // transferPoint(id, _to, true); } // approve(): allow _approved to transfer ownership of point // _tokenId // function approve(address _approved, uint256 _tokenId) public validPointId(_tokenId) { setTransferProxy(uint32(_tokenId), _approved); } // setApprovalForAll(): allow or disallow _operator to // transfer ownership of ALL points // owned by :msg.sender // function setApprovalForAll(address _operator, bool _approved) public { require(0x0 != _operator); azimuth.setOperator(msg.sender, _operator, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } // getApproved(): get the approved address for point _tokenId // function getApproved(uint256 _tokenId) public view validPointId(_tokenId) returns (address approved) { //NOTE redundant, transfer proxy cannot be set for // inactive points // require(azimuth.isActive(uint32(_tokenId))); return azimuth.getTransferProxy(uint32(_tokenId)); } // isApprovedForAll(): returns true if _operator is an // operator for _owner // function isApprovedForAll(address _owner, address _operator) public view returns (bool result) { return azimuth.isOperator(_owner, _operator); } // // ERC721Metadata interface // // name(): returns the name of a collection of points // function name() external view returns (string) { return "Azimuth Points"; } // symbol(): returns an abbreviates name for points // function symbol() external view returns (string) { return "AZP"; } // tokenURI(): returns a URL to an ERC-721 standard JSON file // function tokenURI(uint256 _tokenId) public view validPointId(_tokenId) returns (string _tokenURI) { _tokenURI = "https://azimuth.network/erc721/0000000000.json"; bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10); _tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10); _tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10); _tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10); _tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10); _tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10); _tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10); _tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10); _tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10); _tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10); } // // Points interface // // configureKeys(): configure _point with network public keys // _encryptionKey, _authenticationKey, // and corresponding _cryptoSuiteVersion, // incrementing the point's continuity number if needed // function configureKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion, bool _discontinuous) external activePointManager(_point) { if (_discontinuous) { azimuth.incrementContinuityNumber(_point); } azimuth.setKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion); } // spawn(): spawn _point, then either give, or allow _target to take, // ownership of _point // // if _target is the :msg.sender, _targets owns the _point right away. // otherwise, _target becomes the transfer proxy of _point. // // Requirements: // - _point must not be active // - _point must not be a planet with a galaxy prefix // - _point's prefix must be linked and under its spawn limit // - :msg.sender must be either the owner of _point's prefix, // or an authorized spawn proxy for it // function spawn(uint32 _point, address _target) external { // only currently unowned (and thus also inactive) points can be spawned // require(azimuth.isOwner(_point, 0x0)); // prefix: half-width prefix of _point // uint16 prefix = azimuth.getPrefix(_point); // only allow spawning of points of the size directly below the prefix // // this is possible because of how the address space works, // but supporting it introduces complexity through broken assumptions. // // example: // 0x0000.0000 - galaxy zero // 0x0000.0100 - the first star of galaxy zero // 0x0001.0100 - the first planet of the first star // 0x0001.0000 - the first planet of galaxy zero // require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); // prefix point must be linked and able to spawn // require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); // the owner of a prefix can always spawn its children; // other addresses need explicit permission (the role // of "spawnProxy" in the Azimuth contract) // require( azimuth.canSpawnAs(prefix, msg.sender) ); // if the caller is spawning the point to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern // making the _point prefix's owner the _point owner in the mean time // else { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } // doSpawn(): actual spawning logic, used in spawn(). creates _point, // making the _target its owner if _direct, or making the // _holder the owner and the _target the transfer proxy // if not _direct. // function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { // register the spawn for _point's prefix, incrementing spawn count // azimuth.registerSpawned(_point); // if the spawn is _direct, assume _target knows what they're doing // and resolve right away // if (_direct) { // make the point active and set its new owner // azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } // // when spawning indirectly, enforce a withdraw pattern by approving // the _target for transfer of the _point instead. // we make the _holder the owner of this _point in the mean time, // so that it may cancel the transfer (un-approve) if _target flakes. // we don't make _point active yet, because it still doesn't really // belong to anyone. // else { // have _holder hold on to the _point while _target gets to transfer // ownership of it // azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } // transferPoint(): transfer _point to _target, clearing all permissions // data and keys if _reset is true // // Note: the _reset flag is useful when transferring the point to // a recipient who doesn't trust the previous owner. // // Requirements: // - :msg.sender must be either _point's current owner, authorized // to transfer _point, or authorized to transfer the current // owner's points (as in ERC721's operator) // - _target must not be the zero address // function transferPoint(uint32 _point, address _target, bool _reset) public { // transfer is legitimate if the caller is the current owner, or // an operator for the current owner, or the _point's transfer proxy // require(azimuth.canTransfer(_point, msg.sender)); // if the point wasn't active yet, that means transferring it // is part of the "spawn" flow, so we need to activate it // if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } // if the owner would actually change, change it // // the only time this deliberately wouldn't be the case is when a // prefix owner wants to activate a spawned but untransferred child. // if ( !azimuth.isOwner(_point, _target) ) { // remember the previous owner, to be included in the Transfer event // address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); // according to ERC721, the approved address (here, transfer proxy) // gets cleared during every Transfer event // azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } // reset sensitive data // used when transferring the point to a new owner // if ( _reset ) { // clear the network public keys and break continuity, // but only if the point has already been linked // if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } // clear management proxy // azimuth.setManagementProxy(_point, 0); // clear voting proxy // azimuth.setVotingProxy(_point, 0); // clear transfer proxy // // in most cases this is done above, during the ownership transfer, // but we might not hit that and still be expected to reset the // transfer proxy. // doing it a second time is a no-op in Azimuth. // azimuth.setTransferProxy(_point, 0); // clear spawning proxy // azimuth.setSpawnProxy(_point, 0); // clear claims // claims.clearClaims(_point); } } // escape(): request escape as _point to _sponsor // // if an escape request is already active, this overwrites // the existing request // // Requirements: // - :msg.sender must be the owner or manager of _point, // - _point must be able to escape to _sponsor as per to canEscapeTo() // function escape(uint32 _point, uint32 _sponsor) external activePointManager(_point) { require(canEscapeTo(_point, _sponsor)); azimuth.setEscapeRequest(_point, _sponsor); } // cancelEscape(): cancel the currently set escape for _point // function cancelEscape(uint32 _point) external activePointManager(_point) { azimuth.cancelEscape(_point); } // adopt(): as the relevant sponsor, accept the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function adopt(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); // _sponsor becomes _point's sponsor // its escape request is reset to "not escaping" // azimuth.doEscape(_point); } // reject(): as the relevant sponsor, deny the _point's request // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function reject(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); // reset the _point's escape request to "not escaping" // azimuth.cancelEscape(_point); } // detach(): as the _sponsor, stop sponsoring the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's current sponsor // function detach(uint32 _point) external { require( azimuth.hasSponsor(_point) && azimuth.canManage(azimuth.getSponsor(_point), msg.sender) ); // signal that its sponsor no longer supports _point // azimuth.loseSponsor(_point); } // // Point rules // // getSpawnLimit(): returns the total number of children the _point // is allowed to spawn at _time. // function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { // in 2019, stars may spawn at most 1024 planets. this limit doubles // for every subsequent year. // // Note: 1546300800 corresponds to 2019-01-01 // uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } else // size == Azimuth.Size.Planet { // planets can create moons, but moons aren't on the chain // return 0; } } // canEscapeTo(): true if _point could try to escape to _sponsor // function canEscapeTo(uint32 _point, uint32 _sponsor) public view returns (bool canEscape) { // can't escape to a sponsor that hasn't been linked // if ( !azimuth.hasBeenLinked(_sponsor) ) return false; // Can only escape to a point one size higher than ourselves, // except in the special case where the escaping point hasn't // been linked yet -- in that case we may escape to points of // the same size, to support lightweight invitation chains. // // The use case for lightweight invitations is that a planet // owner should be able to invite their friends onto an // Azimuth network in a two-party transaction, without a new // star relationship. // The lightweight invitation process works by escaping your // own active (but never linked) point to one of your own // points, then transferring the point to your friend. // // These planets can, in turn, sponsor other unlinked planets, // so the "planet sponsorship chain" can grow to arbitrary // length. Most users, especially deep down the chain, will // want to improve their performance by switching to direct // star sponsors eventually. // Azimuth.Size pointSize = azimuth.getPointSize(_point); Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor); return ( // normal hierarchical escape structure // ( (uint8(sponsorSize) + 1) == uint8(pointSize) ) || // // special peer escape // ( (sponsorSize == pointSize) && // // peer escape is only for points that haven't been linked // yet, because it's only for lightweight invitation chains // !azimuth.hasBeenLinked(_point) ) ); } // // Permission management // // setManagementProxy(): configure the management proxy for _point // // The management proxy may perform "reversible" operations on // behalf of the owner. This includes public key configuration and // operations relating to sponsorship. // function setManagementProxy(uint32 _point, address _manager) external activePointManager(_point) { azimuth.setManagementProxy(_point, _manager); } // setSpawnProxy(): give _spawnProxy the right to spawn points // with the prefix _prefix // function setSpawnProxy(uint16 _prefix, address _spawnProxy) external activePointSpawner(_prefix) { azimuth.setSpawnProxy(_prefix, _spawnProxy); } // setVotingProxy(): configure the voting proxy for _galaxy // // the voting proxy is allowed to start polls and cast votes // on the point's behalf. // function setVotingProxy(uint8 _galaxy, address _voter) external activePointVoter(_galaxy) { azimuth.setVotingProxy(_galaxy, _voter); } // setTransferProxy(): give _transferProxy the right to transfer _point // // Requirements: // - :msg.sender must be either _point's current owner, // or be an operator for the current owner // function setTransferProxy(uint32 _point, address _transferProxy) public { // owner: owner of _point // address owner = azimuth.getOwner(_point); // caller must be :owner, or an operator designated by the owner. // require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender)); // set transfer proxy field in Azimuth contract // azimuth.setTransferProxy(_point, _transferProxy); // emit Approval event // emit Approval(owner, _transferProxy, uint256(_point)); } // // Poll actions // // startUpgradePoll(): as _galaxy, start a poll for the ecliptic // upgrade _proposal // // Requirements: // - :msg.sender must be the owner or voting proxy of _galaxy, // - the _proposal must expect to be upgraded from this specific // contract, as indicated by its previousEcliptic attribute // function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal) external activePointVoter(_galaxy) { // ensure that the upgrade target expects this contract as the source // require(_proposal.previousEcliptic() == address(this)); polls.startUpgradePoll(_proposal); } // startDocumentPoll(): as _galaxy, start a poll for the _proposal // // the _proposal argument is the keccak-256 hash of any arbitrary // document or string of text // function startDocumentPoll(uint8 _galaxy, bytes32 _proposal) external activePointVoter(_galaxy) { polls.startDocumentPoll(_proposal); } // castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic // upgrade _proposal // // _vote is true when in favor of the proposal, false otherwise // // If this vote results in a majority for the _proposal, it will // be upgraded to immediately. // function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { // majority: true if the vote resulted in a majority, false otherwise // bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // castDocumentVote(): as _galaxy, cast a _vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote) external activePointVoter(_galaxy) { polls.castDocumentVote(_galaxy, _proposal, _vote); } // updateUpgradePoll(): check whether the _proposal has achieved // majority, upgrading to it if it has // function updateUpgradePoll(EclipticBase _proposal) external { // majority: true if the poll ended in a majority, false otherwise // bool majority = polls.updateUpgradePoll(_proposal); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // updateDocumentPoll(): check whether the _proposal has achieved majority // // Note: the polls contract publicly exposes the function this calls, // but we offer it in the ecliptic interface as a convenience // function updateDocumentPoll(bytes32 _proposal) external { polls.updateDocumentPoll(_proposal); } // // Contract owner operations // // createGalaxy(): grant _target ownership of the _galaxy and register // it for voting // function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { // only currently unowned (and thus also inactive) galaxies can be // created, and only to non-zero addresses // require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); // new galaxy means a new registered voter // polls.incrementTotalVoters(); // if the caller is sending the galaxy to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern, // making the caller the owner in the mean time // else { doSpawn(_galaxy, _target, false, msg.sender); } } function setDnsDomains(string _primary, string _secondary, string _tertiary) external onlyOwner { azimuth.setDnsDomains(_primary, _secondary, _tertiary); } // // Function modifiers for this contract // // validPointId(): require that _id is a valid point // modifier validPointId(uint256 _id) { require(_id < 0x100000000); _; } }
Transfer: This emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are created (`from` == 0) and destroyed (`to` == 0). At the time of any transfer, the approved address for that NFT (if any) is reset to none. Approval: This emits when the approved address for an NFT is changed or reaffirmed. The zero address indicates there is no approved address. When a Transfer event emits, this also indicates that the approved address for that NFT (if any) is reset to none. ApprovalForAll: This emits when an operator is enabled or disabled for an owner. The operator can manage all NFTs of the owner. erc721Received: equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) which can be also obtained as: ERC721Receiver(0).onERC721Received.selector` claims: contract reference, for clearing claims on-transfer constructor(): set data contract addresses and signal interface support Note: during first deploy, ownership of these data contracts must be manually transferred to this contract.
{ using SafeMath for uint256; using AddressUtils for address; event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); bytes4 constant erc721Received = 0x150b7a02; Claims public claims; constructor(address _previous, Azimuth _azimuth, Polls _polls, Claims _claims) EclipticBase(_previous, _azimuth, _polls) public contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata { claims = _claims; } function balanceOf(address _owner) public view returns (uint256 balance) { require(0x0 != _owner); return azimuth.getOwnedPointCount(_owner); } function ownerOf(uint256 _tokenId) public view validPointId(_tokenId) returns (address owner) { uint32 id = uint32(_tokenId); require(azimuth.isActive(id)); return azimuth.getOwner(id); } function exists(uint256 _tokenId) public view returns (bool doesExist) { return ( (_tokenId < 0x100000000) && azimuth.isActive(uint32(_tokenId)) ); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { transferFrom(_from, _to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721Receiver(_to) .onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == erc721Received); } } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { transferFrom(_from, _to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721Receiver(_to) .onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == erc721Received); } } function transferFrom(address _from, address _to, uint256 _tokenId) public validPointId(_tokenId) { uint32 id = uint32(_tokenId); require(azimuth.isOwner(id, _from)); transferPoint(id, _to, true); } function approve(address _approved, uint256 _tokenId) public validPointId(_tokenId) { setTransferProxy(uint32(_tokenId), _approved); } function setApprovalForAll(address _operator, bool _approved) public { require(0x0 != _operator); azimuth.setOperator(msg.sender, _operator, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } function getApproved(uint256 _tokenId) public view validPointId(_tokenId) returns (address approved) { require(azimuth.isActive(uint32(_tokenId))); return azimuth.getTransferProxy(uint32(_tokenId)); } function isApprovedForAll(address _owner, address _operator) public view returns (bool result) { return azimuth.isOperator(_owner, _operator); } function name() external view returns (string) { return "Azimuth Points"; } function symbol() external view returns (string) { return "AZP"; } function tokenURI(uint256 _tokenId) public view validPointId(_tokenId) returns (string _tokenURI) { bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10); _tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10); _tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10); _tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10); _tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10); _tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10); _tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10); _tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10); _tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10); _tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10); } function configureKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion, bool _discontinuous) external activePointManager(_point) { if (_discontinuous) { azimuth.incrementContinuityNumber(_point); } azimuth.setKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion); } function configureKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion, bool _discontinuous) external activePointManager(_point) { if (_discontinuous) { azimuth.incrementContinuityNumber(_point); } azimuth.setKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion); } function spawn(uint32 _point, address _target) external { require(azimuth.isOwner(_point, 0x0)); uint16 prefix = azimuth.getPrefix(_point); require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); require( azimuth.canSpawnAs(prefix, msg.sender) ); if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } function spawn(uint32 _point, address _target) external { require(azimuth.isOwner(_point, 0x0)); uint16 prefix = azimuth.getPrefix(_point); require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); require( azimuth.canSpawnAs(prefix, msg.sender) ); if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } else function spawn(uint32 _point, address _target) external { require(azimuth.isOwner(_point, 0x0)); uint16 prefix = azimuth.getPrefix(_point); require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); require( azimuth.canSpawnAs(prefix, msg.sender) ); if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { azimuth.registerSpawned(_point); if (_direct) { azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } { azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { azimuth.registerSpawned(_point); if (_direct) { azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } { azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } else function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { azimuth.registerSpawned(_point); if (_direct) { azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } { azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } function transferPoint(uint32 _point, address _target, bool _reset) public { require(azimuth.canTransfer(_point, msg.sender)); if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } { address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } { if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } } } function transferPoint(uint32 _point, address _target, bool _reset) public { require(azimuth.canTransfer(_point, msg.sender)); if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } { address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } { if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } } } if ( !azimuth.isOwner(_point, _target) ) function transferPoint(uint32 _point, address _target, bool _reset) public { require(azimuth.canTransfer(_point, msg.sender)); if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } { address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } { if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } } } if ( _reset ) function transferPoint(uint32 _point, address _target, bool _reset) public { require(azimuth.canTransfer(_point, msg.sender)); if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } { address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } { if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } } } function transferPoint(uint32 _point, address _target, bool _reset) public { require(azimuth.canTransfer(_point, msg.sender)); if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } { address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } { if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } } } azimuth.setManagementProxy(_point, 0); azimuth.setVotingProxy(_point, 0); azimuth.setTransferProxy(_point, 0); azimuth.setSpawnProxy(_point, 0); claims.clearClaims(_point); function escape(uint32 _point, uint32 _sponsor) external activePointManager(_point) { require(canEscapeTo(_point, _sponsor)); azimuth.setEscapeRequest(_point, _sponsor); } function cancelEscape(uint32 _point) external activePointManager(_point) { azimuth.cancelEscape(_point); } function adopt(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); azimuth.doEscape(_point); } function reject(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); azimuth.cancelEscape(_point); } function detach(uint32 _point) external { require( azimuth.hasSponsor(_point) && azimuth.canManage(azimuth.getSponsor(_point), msg.sender) ); azimuth.loseSponsor(_point); } function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } { return 0; } } function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } { return 0; } } function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } { return 0; } } function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } { return 0; } } function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } { return 0; } } function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } { return 0; } } function canEscapeTo(uint32 _point, uint32 _sponsor) public view returns (bool canEscape) { if ( !azimuth.hasBeenLinked(_sponsor) ) return false; Azimuth.Size pointSize = azimuth.getPointSize(_point); Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor); ( (uint8(sponsorSize) + 1) == uint8(pointSize) ) || ( (sponsorSize == pointSize) && !azimuth.hasBeenLinked(_point) ) ); } function setManagementProxy(uint32 _point, address _manager) external activePointManager(_point) { azimuth.setManagementProxy(_point, _manager); } function setSpawnProxy(uint16 _prefix, address _spawnProxy) external activePointSpawner(_prefix) { azimuth.setSpawnProxy(_prefix, _spawnProxy); } function setVotingProxy(uint8 _galaxy, address _voter) external activePointVoter(_galaxy) { azimuth.setVotingProxy(_galaxy, _voter); } function setTransferProxy(uint32 _point, address _transferProxy) public { address owner = azimuth.getOwner(_point); require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender)); azimuth.setTransferProxy(_point, _transferProxy); emit Approval(owner, _transferProxy, uint256(_point)); } function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal) external activePointVoter(_galaxy) { require(_proposal.previousEcliptic() == address(this)); polls.startUpgradePoll(_proposal); } function startDocumentPoll(uint8 _galaxy, bytes32 _proposal) external activePointVoter(_galaxy) { polls.startDocumentPoll(_proposal); } function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote); if (majority) { upgrade(_proposal); } } function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote); if (majority) { upgrade(_proposal); } } function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote) external activePointVoter(_galaxy) { polls.castDocumentVote(_galaxy, _proposal, _vote); } function updateUpgradePoll(EclipticBase _proposal) external { bool majority = polls.updateUpgradePoll(_proposal); if (majority) { upgrade(_proposal); } } function updateUpgradePoll(EclipticBase _proposal) external { bool majority = polls.updateUpgradePoll(_proposal); if (majority) { upgrade(_proposal); } } function updateDocumentPoll(bytes32 _proposal) external { polls.updateDocumentPoll(_proposal); } function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); polls.incrementTotalVoters(); if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } { doSpawn(_galaxy, _target, false, msg.sender); } } function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); polls.incrementTotalVoters(); if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } { doSpawn(_galaxy, _target, false, msg.sender); } } else function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); polls.incrementTotalVoters(); if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } { doSpawn(_galaxy, _target, false, msg.sender); } } function setDnsDomains(string _primary, string _secondary, string _tertiary) external onlyOwner { azimuth.setDnsDomains(_primary, _secondary, _tertiary); } modifier validPointId(uint256 _id) { require(_id < 0x100000000); _; } }
11,899,608
[ 1, 5912, 30, 1220, 24169, 1347, 23178, 434, 1281, 423, 4464, 3478, 635, 1281, 12860, 18, 5411, 1220, 871, 24169, 1347, 423, 4464, 87, 854, 2522, 21863, 2080, 68, 422, 374, 13, 471, 5411, 17689, 21863, 869, 68, 422, 374, 2934, 2380, 326, 813, 434, 1281, 7412, 16, 326, 5411, 20412, 1758, 364, 716, 423, 4464, 261, 430, 1281, 13, 353, 2715, 358, 6555, 18, 225, 1716, 685, 1125, 30, 1220, 24169, 1347, 326, 20412, 1758, 364, 392, 423, 4464, 353, 3550, 578, 5411, 283, 7329, 11222, 18, 1021, 3634, 1758, 8527, 1915, 353, 1158, 20412, 5411, 1758, 18, 5203, 279, 12279, 871, 24169, 16, 333, 2546, 8527, 716, 5411, 326, 20412, 1758, 364, 716, 423, 4464, 261, 430, 1281, 13, 353, 2715, 358, 6555, 18, 225, 1716, 685, 1125, 1290, 1595, 30, 1220, 24169, 1347, 392, 3726, 353, 3696, 578, 5673, 364, 392, 5375, 3410, 18, 1021, 3726, 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, 95, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 5267, 1989, 364, 1758, 31, 203, 203, 225, 871, 12279, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 203, 1171, 2254, 5034, 8808, 389, 2316, 548, 1769, 203, 203, 225, 871, 1716, 685, 1125, 12, 2867, 8808, 389, 8443, 16, 1758, 8808, 389, 25990, 16, 203, 1171, 2254, 5034, 8808, 389, 2316, 548, 1769, 203, 203, 225, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 389, 8443, 16, 1758, 8808, 389, 9497, 16, 203, 15604, 1426, 389, 25990, 1769, 203, 203, 225, 1731, 24, 5381, 6445, 71, 27, 5340, 8872, 273, 374, 92, 23014, 70, 27, 69, 3103, 31, 203, 203, 225, 28895, 1071, 11955, 31, 203, 203, 225, 3885, 12, 2867, 389, 11515, 16, 203, 2868, 432, 94, 15968, 389, 28306, 16, 203, 2868, 6730, 3251, 389, 3915, 3251, 16, 203, 2868, 28895, 389, 28979, 13, 203, 565, 512, 4857, 21507, 2171, 24899, 11515, 16, 389, 28306, 16, 389, 3915, 3251, 13, 203, 565, 1071, 203, 203, 16351, 512, 4857, 21507, 353, 512, 4857, 21507, 2171, 16, 25110, 1358, 1190, 6609, 16, 4232, 39, 27, 5340, 2277, 203, 225, 288, 203, 565, 11955, 273, 389, 28979, 31, 203, 203, 225, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 203, 1377, 1071, 203, 1377, 1476, 203, 1377, 1135, 261, 11890, 5034, 11013, 13, 203, 565, 288, 203, 1377, 2583, 12, 20, 92, 20, 480, 389, 8443, 1769, 203, 1377, 327, 23090, 18, 2 ]
./full_match/1/0xf6aa125a49c7B371f27dEA01E7407DAa85AB91ed/sources/contracts/access/OwnableWithOperator.sol
* @dev Emits when the operator has been changed @param _previousOperator address of the previous operator @param _newOperator address of the new operator/* @dev Throws if called by any account other than the operator or the owner./
modifier onlyOperatorOrOwner() { address currentOwner = owner(); address currentOperator = s_operator; if (currentOperator != _msgSender() && currentOwner != _msgSender()) { revert Access__CallerNeitherOperatorNorOwner(_msgSender(), currentOperator, currentOwner); } _; }
3,847,647
[ 1, 1514, 1282, 1347, 326, 3726, 711, 2118, 3550, 225, 389, 11515, 5592, 1758, 434, 326, 2416, 3726, 225, 389, 2704, 5592, 1758, 434, 326, 394, 3726, 19, 225, 22435, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3726, 578, 326, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 9606, 1338, 5592, 1162, 5541, 1435, 288, 203, 3639, 1758, 783, 5541, 273, 3410, 5621, 203, 3639, 1758, 783, 5592, 273, 272, 67, 9497, 31, 203, 203, 3639, 309, 261, 2972, 5592, 480, 389, 3576, 12021, 1435, 597, 783, 5541, 480, 389, 3576, 12021, 10756, 288, 203, 5411, 15226, 5016, 972, 11095, 6586, 2927, 5592, 50, 280, 5541, 24899, 3576, 12021, 9334, 783, 5592, 16, 783, 5541, 1769, 203, 3639, 289, 203, 203, 3639, 389, 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 ]
./full_match/1/0x7EAdDe89C43B9577526cdF0714cC987D08A87992/sources/lend-core/contracts/protocol/tokenization/VariableDebtToken.sol
@inheritdoc VersionedInitializable
function getRevision() internal virtual override pure returns (uint256) { return DEBT_TOKEN_REVISION; }
17,099,213
[ 1, 36, 10093, 18607, 4435, 6934, 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, 26911, 1435, 2713, 5024, 3849, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 2030, 38, 56, 67, 8412, 67, 862, 25216, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.7.4; /** * @notice The TieredOwnable can assign ownership tiers to addresses, * allowing inheriting contracts to choose which tier can call which function. */ contract TieredOwnable { uint256 constant internal HIGHEST_OWNER_TIER = 2**256-1; //Highest possible tier mapping(address => uint256) internal ownerTier; event OwnershipGranted(address indexed owner, uint256 indexed previousTier, uint256 indexed newTier); /** * @dev Sets the _firstOwner provided to highest owner tier * @dev _firstOwner First address to be a owner of this contract */ constructor (address _firstOwner) { require(_firstOwner != address(0), "TieredOwnable#constructor: INVALID_FIRST_OWNER"); ownerTier[_firstOwner] = HIGHEST_OWNER_TIER; emit OwnershipGranted(_firstOwner, 0, HIGHEST_OWNER_TIER); } /** * @dev Throws if called by an account that's in lower ownership tier than expected */ modifier onlyOwnerTier(uint256 _minTier) { require(ownerTier[msg.sender] >= _minTier, "TieredOwnable#onlyOwnerTier: OWNER_TIER_IS_TOO_LOW"); _; } /** * @notice Highest owners can change ownership tier of other owners * @dev Prevents changing sender's tier to ensure there is always at least one HIGHEST_OWNER_TIER owner. * @param _address Address of the owner * @param _tier Ownership tier assigned to owner */ function assignOwnership(address _address, uint256 _tier) external onlyOwnerTier(HIGHEST_OWNER_TIER) { require(_address != address(0), "TieredOwnable#assignOwnership: INVALID_ADDRESS"); require(msg.sender != _address, "TieredOwnable#assignOwnership: UPDATING_SELF_TIER"); emit OwnershipGranted(_address, ownerTier[_address], _tier); ownerTier[_address] = _tier; } /** * @notice Returns the ownership tier of provided owner * @param _owner Owner's address to query ownership tier */ function getOwnerTier(address _owner) external view returns (uint256) { return ownerTier[_owner]; } }
* @notice Returns the ownership tier of provided owner @param _owner Owner's address to query ownership tier/
function getOwnerTier(address _owner) external view returns (uint256) { return ownerTier[_owner]; }
2,517,917
[ 1, 1356, 326, 23178, 17742, 434, 2112, 3410, 225, 389, 8443, 16837, 1807, 1758, 358, 843, 23178, 17742, 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, 225, 445, 13782, 15671, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 3410, 15671, 63, 67, 8443, 15533, 203, 225, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * This class provides an example upgradeable smart contract with the following features: * - adheres to the ERC20 token standard * - applies a 10% transaction fee: 5% gone forever (burned) and 5% transferred to a liquidity pool * - applies roughly 10% annual interest for holders, compounded annualy * - is upgradeable using OpenZeppelin's upgradeable contract model * * There will be comments throughout this file explaining the logic/reasoning behind each design choice * to help guide you in learning about smart contracts. * * You can see the source code for the base contracts at https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable. **/ contract MyUpgradeableContract is ERC20BurnableUpgradeable, OwnableUpgradeable { /** * Indicates the precision of quantity traded for this token. 18 is standard. * * Let's say this number were 2. Whenever you see '1025' being traded, minted, * an so on within this file, that really means that 10.25 tokens are minted. * * That is why in the initializer of this contract, we are initializing 1 trillion * 10^18 tokens. **/ uint8 private constant _decimalsImpl = 18; // Your contract should override this function to adhere to ERC20 standard. function decimals() public view virtual override returns (uint8) { return _decimalsImpl; } address private _minter; // save the address of the person who created this contract to allow for minter-only actions uint256 private _lastMintTime; uint256 private constant _mintIntervalSeconds = 604800; // one week uint256 private constant _oneYearSeconds = 31536000; // one year uint256 private constant _numIntervalsPerYear = _oneYearSeconds / _mintIntervalSeconds; // 52 uint256 private constant _interestMultiplierPerYear = (10**_decimalsImpl) + (10**(_decimalsImpl-1)); // 1.1x interest per year; uint256 private constant _interestDivisorPerYear = 10; // 1/10 additional interest per year uint256 private constant _interestDivisorPerInterval = _interestDivisorPerYear * _numIntervalsPerYear; uint256 private constant _burnDivisor = 20; // 1/20 total burn amount (5% gone forever) uint256 private constant _liquidateDivisor = 20; // 1/20 total liquidate amount (5% to LP) mapping (address => bool) private _existingUsers; address[] private _orderedUsers; // ordered by creation of user address to allow for interest over all users address private _liquidityPoolAddress; // once liquidity pool address is known, should be set via SetLiquidityPoolAddresss() // Upgradeable contracts cannot have constructors, so an initializer method must be written to "construct" the contract function initialize() public initializer { // Call all of the base classes initializers of this contract, starting with the most base class first __Context_init_unchained(); __ERC20_init_unchained("MyContract", "MyC"); // contract name and ticker __ERC20Burnable_init_unchained(); __Ownable_init_unchained(); uint256 startingSupply = (10**12) * (10**decimals()); // 1 trillion _minter = _msgSender(); _orderedUsers.push(_minter); _existingUsers[_minter] = true; _mint(_minter, startingSupply); _lastMintTime = nowSeconds(); // should be changed after contract deployment to the true liquidity pool address _liquidityPoolAddress = _minter; } function getSecondsSinceLastMint() private view returns (uint256) { return nowSeconds() - _lastMintTime; } function shouldMint() private view returns (bool) { return getSecondsSinceLastMint() > _mintIntervalSeconds; } function interest(address account) private { uint256 amountToMint = balanceOf(account) / _interestDivisorPerInterval; _mint(account, amountToMint); } function interestAll() private { for (uint i = 0; i < _orderedUsers.length; i++) { address temp = _orderedUsers[i]; require(_existingUsers[temp]); assert(_existingUsers[temp]); interest(temp); } _lastMintTime = nowSeconds(); } function forceInterestAll() public { require(_msgSender() == _minter); interestAll(); } function getBurnAmount(uint256 amount) private pure returns (uint256) { uint256 burnAmount = amount / _burnDivisor; assert(burnAmount <= amount); return burnAmount; } function getLiquidateAmount(uint256 amount) private pure returns (uint256) { uint256 liquidateAmount = amount / _liquidateDivisor; assert(liquidateAmount <= amount); return liquidateAmount; } function getFeeAmount(uint256 amount) private pure returns (uint256, uint256) { uint256 burnAmount = getBurnAmount(amount); uint256 liquidateAmount = getLiquidateAmount(amount); uint256 removalAmount = burnAmount + liquidateAmount; assert(removalAmount <= amount); return (burnAmount, liquidateAmount); } function setLiquidityPoolAddress(address liquidityPoolAddress) public { require(_msgSender() == _minter); _liquidityPoolAddress = liquidityPoolAddress; } function transfer(address recipient, uint256 amount) public override returns (bool) { require(_msgSender() != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(balanceOf(_msgSender()) >= amount); // apply fees for the transaction (uint256 burnAmount, uint256 liquidateAmount) = getFeeAmount(amount); uint256 removalAmount = burnAmount + liquidateAmount; amount -= removalAmount; burn(burnAmount); super.transfer(_liquidityPoolAddress, liquidateAmount); super.transfer(recipient, amount); require(_existingUsers[_msgSender()]); handleMintOnTransfer(_msgSender(), recipient); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(balanceOf(sender) >= amount); require(allowance(sender, _msgSender()) >= amount, "ERC20: transfer amount exceeds allowance"); // apply fees for the transaction (uint256 burnAmount, uint256 liquidateAmount) = getFeeAmount(amount); uint256 removalAmount = burnAmount + liquidateAmount; amount -= removalAmount; burnFrom(sender, burnAmount); super.transferFrom(sender, _liquidityPoolAddress, liquidateAmount); super.transferFrom(sender, recipient, amount); require(_existingUsers[_msgSender()]); require(_existingUsers[sender]); handleMintOnTransfer(sender, recipient); return true; } // The hook before all transfers allows us to keep track of which addresses exist for users function handleMintOnTransfer(address from, address to) private { bool fromAddressExists = _existingUsers[from]; bool toAddressExists = _existingUsers[to]; require(fromAddressExists); if (toAddressExists == false) { _existingUsers[to] = true; _orderedUsers.push(to); } if (shouldMint()) { interestAll(); } } function getNumUsers() external view returns (uint256) { return _orderedUsers.length; } function nowSeconds() private view returns (uint256) { return block.timestamp; } function getMinter() external view returns (address) { return _minter; } function getLiquidityPoolAddress() external view returns (address) { return _liquidityPoolAddress; } }
apply fees for the transaction
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(balanceOf(sender) >= amount); require(allowance(sender, _msgSender()) >= amount, "ERC20: transfer amount exceeds allowance"); (uint256 burnAmount, uint256 liquidateAmount) = getFeeAmount(amount); uint256 removalAmount = burnAmount + liquidateAmount; amount -= removalAmount; burnFrom(sender, burnAmount); super.transferFrom(sender, _liquidityPoolAddress, liquidateAmount); super.transferFrom(sender, recipient, amount); require(_existingUsers[_msgSender()]); require(_existingUsers[sender]); handleMintOnTransfer(sender, recipient); return true; }
5,402,032
[ 1, 9010, 1656, 281, 364, 326, 2492, 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, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 1071, 3849, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 12296, 951, 12, 15330, 13, 1545, 3844, 1769, 203, 3639, 2583, 12, 5965, 1359, 12, 15330, 16, 389, 3576, 12021, 10756, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 8863, 203, 203, 3639, 261, 11890, 5034, 18305, 6275, 16, 2254, 5034, 4501, 26595, 340, 6275, 13, 273, 2812, 1340, 6275, 12, 8949, 1769, 203, 3639, 2254, 5034, 14817, 6275, 273, 18305, 6275, 397, 4501, 26595, 340, 6275, 31, 203, 3639, 3844, 3947, 14817, 6275, 31, 203, 3639, 18305, 1265, 12, 15330, 16, 18305, 6275, 1769, 203, 3639, 2240, 18, 13866, 1265, 12, 15330, 16, 389, 549, 372, 24237, 2864, 1887, 16, 4501, 26595, 340, 6275, 1769, 203, 3639, 2240, 18, 13866, 1265, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 2583, 24899, 11711, 6588, 63, 67, 3576, 12021, 1435, 19226, 203, 3639, 2583, 24899, 11711, 6588, 63, 15330, 19226, 203, 3639, 1640, 49, 474, 1398, 5912, 12, 15330, 16, 8027, 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 ]
./partial_match/3/0xbDABd536706AE5d859aa9A930EdA95194610B56a/sources/VVV5Sale.sol
require(msg.sender!=owner);require(tokensRaised < fundingGoal);require(now < icoEnd && now > icoStart);if(tokensRaised + tokensToBuy > fundingGoal) { uint exceedingTokens = tokensRaised + tokensToBuy - fundingGoal; uint exceedingEther; exceedingEther = (exceedingTokens * 1 ether) / tokenRate; msg.sender.transfer(exceedingEther); tokensToBuy -= exceedingTokens; etherUsed -= exceedingEther; }tokensToBuy = tokensToBuy * 10 ** 18; transfer tokenstoken.transfer(msg.sender, tokensToBuy);emit Transfer(owner, msg.sender, tokensToBuy);balances[owner] = safeSub(balances[owner], tokensToBuy);balances[msg.sender] = safeAdd(balances[msg.sender], tokensToBuy);emit Transfer(owner, msg.sender, tokensToBuy);
function buy() public payable { emit BuyTokens( msg.sender , msg.value); uint tokensToBuy; uint etherUsed = msg.value; tokensToBuy = (etherUsed/ 1 ether) * tokenRate; owner.transfer(etherUsed); token.transferFrom(owner , msg.sender, tokensToBuy); uint buyerBalance = token.balanceOf(msg.sender); emit BuyerBalance(msg.sender, buyerBalance); tokensRaised += tokensToBuy; etherRaised += etherUsed; }
5,156,836
[ 1, 6528, 12, 3576, 18, 15330, 5, 33, 8443, 1769, 6528, 12, 7860, 12649, 5918, 411, 22058, 27716, 1769, 6528, 12, 3338, 411, 277, 2894, 1638, 597, 2037, 405, 277, 2894, 1685, 1769, 430, 12, 7860, 12649, 5918, 397, 2430, 774, 38, 9835, 405, 22058, 27716, 13, 288, 282, 2254, 9943, 310, 5157, 273, 2430, 12649, 5918, 397, 2430, 774, 38, 9835, 300, 22058, 27716, 31, 282, 2254, 9943, 310, 41, 1136, 31, 282, 9943, 310, 41, 1136, 273, 261, 338, 5288, 310, 5157, 225, 404, 225, 2437, 13, 342, 1147, 4727, 31, 282, 1234, 18, 15330, 18, 13866, 12, 338, 5288, 310, 41, 1136, 1769, 282, 2430, 774, 38, 9835, 3947, 9943, 310, 5157, 31, 282, 225, 2437, 6668, 3947, 9943, 310, 41, 1136, 31, 289, 7860, 774, 38, 9835, 273, 2430, 774, 38, 9835, 225, 1728, 225, 6549, 31, 7412, 1147, 334, 969, 18, 13866, 12, 3576, 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, 282, 445, 30143, 1435, 1071, 8843, 429, 288, 203, 203, 1377, 3626, 605, 9835, 5157, 12, 1234, 18, 15330, 269, 1234, 18, 1132, 1769, 203, 202, 21281, 1377, 2254, 2430, 774, 38, 9835, 31, 203, 1377, 2254, 225, 2437, 6668, 273, 1234, 18, 1132, 31, 203, 1377, 2430, 774, 38, 9835, 273, 261, 2437, 6668, 19, 404, 225, 2437, 13, 380, 1147, 4727, 31, 203, 203, 203, 203, 203, 203, 4202, 203, 1377, 3410, 18, 13866, 12, 2437, 6668, 1769, 203, 4202, 203, 4202, 203, 4202, 203, 1377, 1147, 18, 13866, 1265, 12, 8443, 269, 1234, 18, 15330, 16, 2430, 774, 38, 9835, 1769, 203, 4202, 203, 1377, 2254, 27037, 13937, 273, 1147, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 4202, 203, 1377, 3626, 605, 16213, 13937, 12, 3576, 18, 15330, 16, 27037, 13937, 1769, 203, 4202, 203, 203, 1377, 2430, 12649, 5918, 1011, 2430, 774, 38, 9835, 31, 203, 1377, 225, 2437, 12649, 5918, 1011, 225, 2437, 6668, 31, 203, 282, 289, 203, 27699, 27699, 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 ]
./partial_match/1/0x98b7893C5717aF41d3e351c6e3445Be02a062A90/sources/contracts/MapleLoanStorage.sol
The principal to remain at end of loan.
uint256 internal _endingPrincipal;
3,924,848
[ 1, 1986, 8897, 358, 7232, 622, 679, 434, 28183, 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 ]
[ 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, 565, 2254, 5034, 2713, 389, 2846, 9155, 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, -100, -100, -100, -100, -100 ]
//Address: 0x1d979bd0b663040f2fe8a9854a8569919ae153ac //Contract name: slot //Balance: 0.002436476745367404 Ether //Verification Date: 2/2/2017 //Transacion Count: 4888 // CODE STARTS HERE // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if(address(OAR)==0) oraclize_setNetwork(networkID_auto); oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); return true; } if (getCodeSize(0xc03a2615d5efaf5f49f60b7bb6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03a2615d5efaf5f49f60b7bb6583eaec212fdf1); return true; } if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); return true; } if (getCodeSize(0x93bbbe5ce77034e3095f0479919962a903f898ad)>0){ //norsborg testnet OAR = OraclizeAddrResolverI(0x93bbbe5ce77034e3095f0479919962a903f898ad); return true; } if (getCodeSize(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } // </ORACLIZE_API> contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) suicide(owner); } } contract slot is mortal, usingOraclize { /** which oraclize ID belong to which player address?**/ mapping (bytes32 => address) players; /** the amount of gas to be sent to oraclize**/ uint32 public oraclizeGas; /** probabilities of the different results (absolute frequency out of 1.000.000 spins)**/ uint32[] public probabilities; /** the prize per probability (shifted by two digits -> 375 is acutually 3.75)*/ uint32[] public prizes; /** the amount of ether per bet **/ mapping (bytes32 => uint) bets; /** the oraclize query string**/ string public query; /** the type of the oraclize query**/ string public queryType; /** tell the listeners the result first value: type, second value: player address, third value: oraclize ID**/ event gameResult(uint, address);// 0-> %5; 1 -> 80%; 2 -> loss, 3->error in callback; /** **/ function slot() payable{ probabilities.push(4); probabilities.push(50); probabilities.push(200); probabilities.push(600); probabilities.push(1000); probabilities.push(2000); probabilities.push(4000); probabilities.push(30000); probabilities.push(90000); prizes.push(5000); prizes.push(2500); prizes.push(2000); prizes.push(1900); prizes.push(1800); prizes.push(1700); prizes.push(1600); prizes.push(1500); prizes.push(375); oraclizeGas = 250000; query = "random number between 1 and 1000000"; queryType = "WolframAlpha"; } /** * If more than 0.1 ether and less than 1 ether is sent and the contracts holds enough to pay out the player in case of a win, a random number is asked from oraclize. * */ function() payable { if(msg.sender!=owner){//owner should be able to send funds to the contract anytime if(msg.value<100000000000000000||msg.value>1000000000000000000) throw;//bet has to lie between 0.1 and 1 ETH if(address(this).balance < msg.value/100*prizes[0]) throw; //make sure the contract is able to pay out the player in case he wins bytes32 oid = oraclize_query(queryType, query, oraclizeGas); bets[oid] = msg.value; players[oid] = msg.sender; } } /** * The random number from Oraclizes decides the game result. * If Oraclize sends a message instead of the requested number, the bet is returned to the player. * */ function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) throw; if (players[myid]==0x0) throw; uint random = convertToInt(result); if(random==0){//result not a number, return bet if(!players[myid].send(bets[myid])) throw; gameResult(101,players[myid]); delete players[myid]; return; } uint range = 0; for(uint i = 0; i<probabilities.length; i++){ range+=probabilities[i]; if(random<=range){ if(!players[myid].send(bets[myid]/100*prizes[i])){ gameResult(100,players[myid]);//100 -> error throw; } gameResult(i, players[myid]); delete players[myid]; return; } } //else player loses everything gameResult(probabilities.length, players[myid]); delete players[myid]; } /** * sets the amount of gas to be sent to oraclize * */ function setOraclizeGas(uint32 newGas){ if(!(msg.sender==owner)) throw; oraclizeGas = newGas; } /** * sets the amount of gas to be sent to oraclize * */ function setOraclizeQuery(string newQuery){ if(!(msg.sender==owner)) throw; query = newQuery; } /** * sets the amount of gas to be sent to oraclize * */ function setOraclizeQueryType(string newQueryType){ if(!(msg.sender==owner)) throw; queryType = newQueryType; } /** set the probabilities of the results (absolute frequencies out of 1.000.000 spins) **/ function setProbabilities(uint32[] probs){ if(!(msg.sender==owner)) throw; probabilities=probs; } /** set the prizes of the results (shifted by 2 digits -> 375 means 3.75)**/ function setPrizes(uint32[] priz){ if(!(msg.sender==owner)) throw; prizes=priz; } /** * allows the owner to collect the accumulated losses * */ function collectFees(uint amount){ if(!(msg.sender==owner)) throw; if( address(this).balance < amount) throw; if(!owner.send(amount)) throw; } /** * converts a string to an integer (there may only be digits) * */ function convertToInt(string _a) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ mint *= 10; mint += uint(bresult[i]) - 48; } else if((bresult[i] >= 58)&&(bresult[i] <= 126)) return 0;//its a message, no pure int } return mint; } }
* The random number from Oraclizes decides the game result. If Oraclize sends a message instead of the requested number, the bet is returned to the player. /
function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) throw; if (players[myid]==0x0) throw; uint random = convertToInt(result); if(!players[myid].send(bets[myid])) throw; gameResult(101,players[myid]); delete players[myid]; return; }
934,557
[ 1, 1986, 2744, 1300, 628, 531, 354, 830, 3128, 2109, 4369, 326, 7920, 563, 18, 971, 531, 354, 830, 554, 9573, 279, 883, 3560, 434, 326, 3764, 1300, 16, 326, 2701, 353, 2106, 358, 326, 7291, 18, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1001, 3394, 12, 3890, 1578, 3399, 350, 16, 533, 563, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 578, 10150, 554, 67, 7358, 1887, 10756, 604, 31, 203, 3639, 309, 261, 1601, 414, 63, 4811, 350, 65, 631, 20, 92, 20, 13, 604, 31, 203, 3639, 2254, 2744, 273, 8137, 1702, 12, 2088, 1769, 203, 5411, 309, 12, 5, 1601, 414, 63, 4811, 350, 8009, 4661, 12, 70, 2413, 63, 4811, 350, 22643, 604, 31, 203, 5411, 7920, 1253, 12, 15168, 16, 1601, 414, 63, 4811, 350, 19226, 203, 5411, 1430, 18115, 63, 4811, 350, 15533, 203, 5411, 327, 31, 203, 3639, 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 ]
./partial_match/1/0x4c0cd0b7b31dFF9bed77931f3a6183fC64B44d5B/sources/BING.sol
* Get total number of tokens in circulation. @return total number of tokens in circulation/
function totalSupply() public constant returns (uint256 supply) { return tokenCount; } string constant public name = "Bitcoinbing"; string constant public symbol = "BING"; uint8 constant public decimals = 18;
3,665,088
[ 1, 967, 2078, 1300, 434, 2430, 316, 5886, 1934, 367, 18, 327, 2078, 1300, 434, 2430, 316, 5886, 1934, 367, 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 ]
[ 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, 225, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 5034, 14467, 13, 288, 203, 565, 327, 1147, 1380, 31, 203, 225, 289, 203, 203, 225, 533, 5381, 1071, 508, 273, 315, 5775, 12645, 31169, 14432, 203, 225, 533, 5381, 1071, 3273, 273, 315, 38, 1360, 14432, 203, 225, 2254, 28, 5381, 1071, 15105, 273, 6549, 31, 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 ]
./full_match/4/0xB4b58210DC03c1A29021B296D80E17aD46427393/sources/contracts/base/ERC721.sol
* @dev Mints `tokenId`, transfers it to `to`, and emits two log events - 1. Credits the `creator` with the mint. 2. Shows transfer from the `creator` 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 creator, 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), creator, tokenId); emit Transfer(creator, to, tokenId); }
769,876
[ 1, 49, 28142, 1375, 2316, 548, 9191, 29375, 518, 358, 1375, 869, 9191, 471, 24169, 2795, 613, 2641, 300, 404, 18, 385, 1118, 1282, 326, 1375, 20394, 68, 598, 326, 312, 474, 18, 576, 18, 9674, 87, 7412, 628, 326, 1375, 20394, 68, 358, 1375, 869, 8338, 9744, 30, 10858, 434, 333, 707, 353, 19169, 477, 11349, 16, 999, 288, 67, 4626, 49, 474, 97, 17334, 3323, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 486, 1005, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 7377, 1282, 279, 288, 5912, 97, 871, 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, 389, 81, 474, 12, 203, 3639, 1758, 11784, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 296, 654, 39, 27, 5340, 30, 312, 474, 358, 326, 3634, 1758, 8284, 203, 3639, 2583, 12, 5, 67, 1808, 12, 2316, 548, 3631, 296, 654, 39, 27, 5340, 30, 1147, 1818, 312, 474, 329, 8284, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 70, 26488, 63, 869, 65, 1011, 404, 31, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 11784, 16, 1147, 548, 1769, 203, 3639, 3626, 12279, 12, 20394, 16, 358, 16, 1147, 548, 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 ]
/* ERC1820 Pseudo-introspection Registry Contract * This standard defines a universal registry smart contract where any address (contract or regular account) can * register which interface it supports and which smart contract is responsible for its implementation. * * Written in 2019 by Jordi Baylina and Jacques Dafflon * * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to * this software to the public domain worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. * * ███████╗██████╗ ██████╗ ██╗ █████╗ ██████╗ ██████╗ * ██╔════╝██╔══██╗██╔════╝███║██╔══██╗╚════██╗██╔═████╗ * █████╗ ██████╔╝██║ ╚██║╚█████╔╝ █████╔╝██║██╔██║ * ██╔══╝ ██╔══██╗██║ ██║██╔══██╗██╔═══╝ ████╔╝██║ * ███████╗██║ ██║╚██████╗ ██║╚█████╔╝███████╗╚██████╔╝ * ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚════╝ ╚══════╝ ╚═════╝ * * ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ * ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝ * ██████╔╝█████╗ ██║ ███╗██║███████╗ ██║ ██████╔╝ ╚████╔╝ * ██╔══██╗██╔══╝ ██║ ██║██║╚════██║ ██║ ██╔══██╗ ╚██╔╝ * ██║ ██║███████╗╚██████╔╝██║███████║ ██║ ██║ ██║ ██║ * ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ * */ pragma solidity 0.5.3; // IV is value needed to have a vanity address starting with '0x1820'. // IV: 53759 /// @dev The interface a contract MUST implement if it is the implementer of /// some (other) interface for any address other than itself. interface ERC1820ImplementerInterface { /// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not. /// @param interfaceHash keccak256 hash of the name of the interface /// @param addr Address for which the contract will implement the interface /// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'. function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32); } /// @title ERC1820 Pseudo-introspection Registry Contract /// @author Jordi Baylina and Jacques Dafflon /// @notice This contract is the official implementation of the ERC1820 Registry. /// @notice For more details, see https://eips.ethereum.org/EIPS/eip-1820 contract ERC1820Registry { /// @notice ERC165 Invalid ID. bytes4 constant internal INVALID_ID = 0xffffffff; /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`). bytes4 constant internal ERC165ID = 0x01ffc9a7; /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address. bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); /// @notice mapping from addresses and interface hashes to their implementers. mapping(address => mapping(bytes32 => address)) internal interfaces; /// @notice mapping from addresses to their manager. mapping(address => address) internal managers; /// @notice flag for each address and erc165 interface to indicate if it is cached. mapping(address => mapping(bytes4 => bool)) internal erc165Cached; /// @notice Indicates a contract is the 'implementer' of 'interfaceHash' for 'addr'. event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); /// @notice Indicates 'newManager' is the address of the new manager for 'addr'. event ManagerChanged(address indexed addr, address indexed newManager); /// @notice Query if an address implements an interface and through which contract. /// @param _addr Address being queried for the implementer of an interface. /// (If '_addr' is the zero address then 'msg.sender' is assumed.) /// @param _interfaceHash Keccak256 hash of the name of the interface as a string. /// E.g., 'web3.utils.keccak256("ERC777TokensRecipient")' for the 'ERC777TokensRecipient' interface. /// @return The address of the contract which implements the interface '_interfaceHash' for '_addr' /// or '0' if '_addr' did not register an implementer for this interface. function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) { address addr = _addr == address(0) ? msg.sender : _addr; if (isERC165Interface(_interfaceHash)) { bytes4 erc165InterfaceHash = bytes4(_interfaceHash); return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : address(0); } return interfaces[addr][_interfaceHash]; } /// @notice Sets the contract which implements a specific interface for an address. /// Only the manager defined for that address can set it. /// (Each address is the manager for itself until it sets a new manager.) /// @param _addr Address for which to set the interface. /// (If '_addr' is the zero address then 'msg.sender' is assumed.) /// @param _interfaceHash Keccak256 hash of the name of the interface as a string. /// E.g., 'web3.utils.keccak256("ERC777TokensRecipient")' for the 'ERC777TokensRecipient' interface. /// @param _implementer Contract address implementing '_interfaceHash' for '_addr'. function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external { address addr = _addr == address(0) ? msg.sender : _addr; require(getManager(addr) == msg.sender, "Not the manager"); require(!isERC165Interface(_interfaceHash), "Must not be an ERC165 hash"); if (_implementer != address(0) && _implementer != msg.sender) { require( ERC1820ImplementerInterface(_implementer) .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC, "Does not implement the interface" ); } interfaces[addr][_interfaceHash] = _implementer; emit InterfaceImplementerSet(addr, _interfaceHash, _implementer); } /// @notice Sets '_newManager' as manager for '_addr'. /// The new manager will be able to call 'setInterfaceImplementer' for '_addr'. /// @param _addr Address for which to set the new manager. /// @param _newManager Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.) function setManager(address _addr, address _newManager) external { require(getManager(_addr) == msg.sender, "Not the manager"); managers[_addr] = _newManager == _addr ? address(0) : _newManager; emit ManagerChanged(_addr, _newManager); } /// @notice Get the manager of an address. /// @param _addr Address for which to return the manager. /// @return Address of the manager for a given address. function getManager(address _addr) public view returns(address) { // By default the manager of an address is the same address if (managers[_addr] == address(0)) { return _addr; } else { return managers[_addr]; } } /// @notice Compute the keccak256 hash of an interface given its name. /// @param _interfaceName Name of the interface. /// @return The keccak256 hash of an interface name. function interfaceHash(string calldata _interfaceName) external pure returns(bytes32) { return keccak256(abi.encodePacked(_interfaceName)); } /* --- ERC165 Related Functions --- */ /* --- Developed in collaboration with William Entriken. --- */ /// @notice Updates the cache with whether the contract implements an ERC165 interface or not. /// @param _contract Address of the contract for which to update the cache. /// @param _interfaceId ERC165 interface for which to update the cache. function updateERC165Cache(address _contract, bytes4 _interfaceId) external { interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache( _contract, _interfaceId) ? _contract : address(0); erc165Cached[_contract][_interfaceId] = true; } /// @notice Checks whether a contract implements an ERC165 interface or not. // If the result is not cached a direct lookup on the contract address is performed. // If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling // 'updateERC165Cache' with the contract address. /// @param _contract Address of the contract to check. /// @param _interfaceId ERC165 interface to check. /// @return True if '_contract' implements '_interfaceId', false otherwise. function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) { if (!erc165Cached[_contract][_interfaceId]) { return implementsERC165InterfaceNoCache(_contract, _interfaceId); } return interfaces[_contract][_interfaceId] == _contract; } /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. /// @param _contract Address of the contract to check. /// @param _interfaceId ERC165 interface to check. /// @return True if '_contract' implements '_interfaceId', false otherwise. function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) { uint256 success; uint256 result; (success, result) = noThrowCall(_contract, ERC165ID); if (success == 0 || result == 0) { return false; } (success, result) = noThrowCall(_contract, INVALID_ID); if (success == 0 || result != 0) { return false; } (success, result) = noThrowCall(_contract, _interfaceId); if (success == 1 && result == 1) { return true; } return false; } /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not. /// @param _interfaceHash The hash to check. /// @return True if '_interfaceHash' is an ERC165 interface (ending with 28 zeroes), false otherwise. function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) { return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; } /// @dev Make a call on a contract without throwing if the function does not exist. function noThrowCall(address _contract, bytes4 _interfaceId) internal view returns (uint256 success, uint256 result) { bytes4 erc165ID = ERC165ID; assembly { let x := mload(0x40) // Find empty storage location using "free memory pointer" mstore(x, erc165ID) // Place signature at beginning of empty storage mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature success := staticcall( 30000, // 30k gas _contract, // To addr x, // Inputs are stored at location x 0x24, // Inputs are 36 (4 + 32) bytes long x, // Store output over input (saves space) 0x20 // Outputs are 32 bytes long ) result := mload(x) // Load the result } } }
@dev Make a call on a contract without throwing if the function does not exist.
function noThrowCall(address _contract, bytes4 _interfaceId) internal view returns (uint256 success, uint256 result) { bytes4 erc165ID = ERC165ID; assembly { success := staticcall( ) } }
2,123,893
[ 1, 6464, 279, 745, 603, 279, 6835, 2887, 19440, 309, 326, 445, 1552, 486, 1005, 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, 1158, 8282, 1477, 12, 2867, 389, 16351, 16, 1731, 24, 389, 5831, 548, 13, 203, 3639, 2713, 1476, 1135, 261, 11890, 5034, 2216, 16, 2254, 5034, 563, 13, 203, 565, 288, 203, 3639, 1731, 24, 6445, 71, 28275, 734, 273, 4232, 39, 28275, 734, 31, 203, 203, 3639, 19931, 288, 203, 203, 5411, 2216, 519, 760, 1991, 12, 203, 5411, 262, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/8453/0xCA7a940D12811390F1910c0399e2165AfC6Ca6D2/sources/AntiMEV.sol
supply is Fibonnaci
uint256 private constant _tTotal = 1123581321 * 10**_decimals;
16,724,885
[ 1, 2859, 1283, 353, 478, 495, 265, 82, 1077, 77, 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, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 23543, 4763, 11861, 1578, 21, 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 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts/math/SafeMath.sol"; import '@openzeppelin/contracts/utils/SafeCast.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import "./interface/INewPremiaFeeDiscount.sol"; import "./interface/IERC2612Permit.sol"; /// @author Premia /// @title A contract allowing you to lock xPremia to get Premia protocol fee discounts contract PremiaFeeDiscount is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeCast for uint256; struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } // The xPremia token IERC20 public xPremia; uint256 private constant _inverseBasisPoint = 1e4; // User data with balance staked and date at which lock ends mapping (address => UserInfo) public userInfo; // Available lockup periods with their bonus (seconds lockup => multiplier (x1 = 1e4)) mapping (uint256 => uint256) public stakePeriods; // List of all existing stake periods uint256[] public existingStakePeriods; // In case we want to upgrade this contract // Users will have to migrate their stake manually by calling migrateStake() so that there is no risk of funds being drained INewPremiaFeeDiscount public newContract; // Staking levels StakeLevel[] public stakeLevels; //////////// // Events // //////////// event Staked(address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil); event Unstaked(address indexed user, uint256 amount); event StakeMigrated(address indexed user, address newContract, uint256 amount, uint256 stakePeriod, uint256 lockedUntil); ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// /// @param _xPremia The xPremia token constructor(IERC20 _xPremia) { xPremia = _xPremia; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// /////////// // Admin // /////////// /// @notice Set a new PremiaFeeDiscount contract, to enable migration /// Users will have to call the migration function themselves to migrate their own stake /// @param _newContract The new contract address function setNewContract(INewPremiaFeeDiscount _newContract) external onlyOwner { newContract = _newContract; } /// @notice Set a stake period multiplier /// @param _secondsLocked The length (in seconds) that the stake will be locked for /// @param _multiplier The multiplier (In basis points) that users will get from choosing this staking period function setStakePeriod(uint256 _secondsLocked, uint256 _multiplier) external onlyOwner { if (_isInArray(_secondsLocked, existingStakePeriods)) { existingStakePeriods.push(_secondsLocked); } stakePeriods[_secondsLocked] = _multiplier; } /// @notice Set new amounts and discounts values for stake levels /// @dev Previous stake levels will be removed and replace by the new ones given /// @param _stakeLevels The new stake levels to set function setStakeLevels(StakeLevel[] memory _stakeLevels) external onlyOwner { for (uint256 i=0; i < _stakeLevels.length; i++) { if (i > 0) { require(_stakeLevels[i].amount > _stakeLevels[i-1].amount && _stakeLevels[i].discount > _stakeLevels[i-1].discount, "Wrong stake level"); } } delete stakeLevels; for (uint256 i=0; i < _stakeLevels.length; i++) { stakeLevels.push(_stakeLevels[i]); } } ////////////////////////////////////////////////// ////////// // Main // ////////// /// @notice Allow a user to migrate their stake to a new PremiaFeeDiscount contract (If a new contract has been set), /// while preserving same lockup expiration date function migrateStake() external nonReentrant { require(address(newContract) != address(0), "Migration disabled"); UserInfo memory user = userInfo[msg.sender]; require(user.balance > 0, "No stake"); delete userInfo[msg.sender]; xPremia.safeIncreaseAllowance(address(newContract), user.balance); newContract.migrate(msg.sender, user.balance, user.stakePeriod, user.lockedUntil); emit StakeMigrated(msg.sender, address(newContract), user.balance, user.stakePeriod, user.lockedUntil); } /// @notice Stake using IERC2612 permit /// @param _amount The amount of xPremia to stake /// @param _period The lockup period (in seconds) /// @param _deadline Deadline after which permit will fail /// @param _v V /// @param _r R /// @param _s S function stakeWithPermit(uint256 _amount, uint256 _period, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external { IERC2612Permit(address(xPremia)).permit(msg.sender, address(this), _amount, _deadline, _v, _r, _s); stake(_amount, _period); } /// @notice Lockup xPremia for protocol fee discounts /// Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation /// @param _amount The amount of xPremia to stake /// @param _period The lockup period (in seconds) function stake(uint256 _amount, uint256 _period) public nonReentrant { require(stakePeriods[_period] > 0, "Stake period does not exists"); UserInfo storage user = userInfo[msg.sender]; uint256 lockedUntil = block.timestamp.add(_period); require(lockedUntil > user.lockedUntil, "Cannot add stake with lower stake period"); xPremia.safeTransferFrom(msg.sender, address(this), _amount); user.balance = user.balance.add(_amount); user.lockedUntil = lockedUntil.toUint64(); user.stakePeriod = _period.toUint64(); emit Staked(msg.sender, _amount, _period, lockedUntil); } /// @notice Unstake xPremia (If lockup period has ended) /// @param _amount The amount of xPremia to unstake function unstake(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; // We allow unstake if the stakePeriod that the user used has been disabled require(stakePeriods[user.stakePeriod] == 0 || user.lockedUntil <= block.timestamp, "Stake still locked"); user.balance = user.balance.sub(_amount); xPremia.safeTransfer(msg.sender, _amount); emit Unstaked(msg.sender, _amount); } ////////////////////////////////////////////////// ////////// // View // ////////// /// @notice Get number of stake levels /// @return The amount of stake levels function stakeLevelsLength() external view returns(uint256) { return stakeLevels.length; } /// Calculate the stake amount of a user, after applying the bonus from the lockup period chosen /// @param _user The user from which to query the stake amount /// @return The user stake amount after applying the bonus function getStakeAmountWithBonus(address _user) public view returns(uint256) { UserInfo memory user = userInfo[_user]; return user.balance.mul(stakePeriods[user.stakePeriod]).div(_inverseBasisPoint); } /// @notice Calculate the % of fee discount for user, based on his stake /// @param _user The _user for which the discount is for /// @return Percentage of protocol fee discount (in basis point) /// Ex : 1000 = 10% fee discount function getDiscount(address _user) external view returns(uint256) { uint256 userBalance = getStakeAmountWithBonus(_user); for (uint256 i=0; i < stakeLevels.length; i++) { StakeLevel memory level = stakeLevels[i]; if (userBalance < level.amount) { uint256 amountPrevLevel; uint256 discountPrevLevel; // If stake is lower, user is in this level, and we need to LERP with prev level to get discount value if (i > 0) { amountPrevLevel = stakeLevels[i - 1].amount; discountPrevLevel = stakeLevels[i - 1].discount; } else { // If this is the first level, prev level is 0 / 0 amountPrevLevel = 0; discountPrevLevel = 0; } uint256 remappedDiscount = level.discount.sub(discountPrevLevel); uint256 remappedAmount = level.amount.sub(amountPrevLevel); uint256 remappedBalance = userBalance.sub(amountPrevLevel); uint256 levelProgress = remappedBalance.mul(_inverseBasisPoint).div(remappedAmount); return discountPrevLevel.add(remappedDiscount.mul(levelProgress).div(_inverseBasisPoint)); } } // If no match found it means user is >= max possible stake, and therefore has max discount possible return stakeLevels[stakeLevels.length - 1].discount; } ////////////////////////////////////////////////// ////////////// // Internal // ////////////// /// @notice Utility function to check if a value is inside an array /// @param _value The value to look for /// @param _array The array to check /// @return Whether the value is in the array or not function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns(bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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 Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface INewPremiaFeeDiscount { function migrate(address _user, uint256 _amount, uint256 _stakePeriod, uint256 _lockedUntil) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612Permit { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current ERC2612 nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } }
Calculate the stake amount of a user, after applying the bonus from the lockup period chosen @param _user The user from which to query the stake amount @return The user stake amount after applying the bonus
function getStakeAmountWithBonus(address _user) public view returns(uint256) { UserInfo memory user = userInfo[_user]; return user.balance.mul(stakePeriods[user.stakePeriod]).div(_inverseBasisPoint); }
1,360,809
[ 1, 8695, 326, 384, 911, 3844, 434, 279, 729, 16, 1839, 13650, 326, 324, 22889, 628, 326, 2176, 416, 3879, 10447, 225, 389, 1355, 1021, 729, 628, 1492, 358, 843, 326, 384, 911, 3844, 327, 1021, 729, 384, 911, 3844, 1839, 13650, 326, 324, 22889, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 21491, 911, 6275, 1190, 38, 22889, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 25003, 3778, 729, 273, 16753, 63, 67, 1355, 15533, 203, 3639, 327, 729, 18, 12296, 18, 16411, 12, 334, 911, 30807, 63, 1355, 18, 334, 911, 5027, 65, 2934, 2892, 24899, 22552, 11494, 291, 2148, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Power.sol"; // File @openzeppelin/contracts/introspection/[email protected] /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @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/[email protected] /** * @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); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @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); } } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require( map._entries.length > index, "EnumerableMap: index out of bounds" ); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address( uint160(uint256(_get(map._inner, bytes32(key), errorMessage))) ); } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "MetaV: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get( tokenId, "MetaV: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "MetaV: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, uint2str(tokenId))); } function uint2str(uint256 _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + (j % 10))); j /= 10; } str = string(bstr); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "MetaV: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "MetaV: 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), "MetaV: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "MetaV: 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), "MetaV: 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), "MetaV: 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), "MetaV: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "MetaV: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "MetaV: 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), "MetaV: mint to the zero address"); require(!_exists(tokenId), "MetaV: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "MetaV: transfer of token that is not own" ); // internal owner require(to != address(0), "MetaV: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { // require(_exists(tokenId), "MetaV: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "MetaV: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract MetaVCollection is ERC721, Power { // ( Serial Id ) => ( Next Mint Id ) mapping(uint256 => uint256) private _mintIds; // ( Serial Id ) => ( TotalSupply ) mapping(uint256 => uint256) private _totalCaps; constructor( string memory name, string memory symbol, string memory _defaultTokenURI ) public ERC721(name, symbol) { _setBaseURI(_defaultTokenURI); } function addSerial( uint256 serialId, uint256 baseId, uint256 totalCount ) public isPowerful { setSerialNextId(serialId, baseId); setTotalSupply(serialId, baseId + totalCount); } function setSerialNextId(uint256 serialId, uint256 baseId) public isPowerful { _mintIds[serialId] = baseId; } function getSerialNextId(uint256 serialId) public returns (uint256) { return _mintIds[serialId]; } function setTotalSupply(uint256 serialId, uint256 _totalSupply) public isPowerful { _totalCaps[serialId] = _totalSupply; } function getTotalSupply(uint256 serialId) public returns (uint256) { return _totalCaps[serialId]; } function mint(uint256 serialId, address user) public isPowerful { require(_mintIds[serialId] > 0, "MetaV: Invalid serial id"); require( _mintIds[serialId] <= _totalCaps[serialId], "MetaV: Exceed the supply limit" ); _mint(user, _mintIds[serialId]++); } function multiMint( uint256 serialId, address user, uint256 count ) public isPowerful { require(count <= 10, "MetaV: Too much one time"); for (uint256 i = 0; i < count; i++) { mint(serialId, user); } } } // contract MetaVMarket is ReentrancyGuard, Ownable { // using EnumerableSet for EnumerableSet.AddressSet; // mapping(uint256 => address) private _collectionSerials; // mapping(uint256 => uint256) private _serialPrices; // mapping(uint256 => uint256) private _presalePrices; // mapping(uint256 => uint256) private _biggerVoucher; // mapping(uint256 => address) public luckyDog; // EnumerableSet.AddressSet private whiteList; // uint256 presaleEndBlock; // constructor() public { // presaleEndBlock = block.number; // } // function purchase(uint256 serialId, uint256 count) // external // payable // nonReentrant // onlyEOA // { // require(count > 0 && count <= 100, "MetaV: Invalid count"); // uint256 price = _serialPrices[serialId]; // if (block.number < presaleEndBlock) { // require(whiteList.contains(msg.sender), ""); // price = _presalePrices[serialId]; // } // require( // msg.value >= price * count, // "MetaV: Insufficient ether to purchase" // ); // address token = _collectionSerials[serialId]; // for (uint256 i = 0; i < count; i++) { // MetaVCollection(token).deliver(_msgSender()); // } // uint256 currVoucher = voucher(); // if (_biggerVoucher[serialId] < currVoucher) { // _biggerVoucher[serialId] = currVoucher; // luckyDog[serialId] = _msgSender(); // } // } // function preMint( // uint256 serialId, // address _to, // uint256 count // ) external payable nonReentrant onlyOwner { // address token = _collectionSerials[serialId]; // for (uint256 i = 0; i < count; i++) { // MetaVCollection(token).deliver(serialId, _to); // } // } // function returnOwnership(uint256 serialId, address newOwner) external { // address token = _collectionSerials[serialId]; // Ownable(token).transferOwnership(newOwner); // } // function setPresaleBlock(uint256 _block) external onlyOwner { // presaleEndBlock = _block; // } // function addWhiteList(address[] memory addrs) external onlyOwner { // for (uint256 i = 0; i < addrs.length; i++) { // whiteList.add(addrs[i]); // } // } // function addSerial( // uint256 serialId, // address tokenAddr, // uint256 price, // uint256 presalePrice // ) external nonReentrant onlyOwner { // _collectionSerials[serialId] = tokenAddr; // _serialPrices[serialId] = price; // _presalePrices[serialId] = presalePrice; // } // modifier onlyEOA() { // require(msg.sender == tx.origin, "Illegal caller"); // _; // } // function voucher() internal view returns (uint256 value) { // bytes memory bs = abi.encodePacked(msg.sender); // bytes memory st = slice(bs, 4, 8); // assembly { // value := mload(add(st, 0x20)) // } // } // function withdraw(address payable checker) external onlyOwner { // checker.transfer(address(this).balance); // } // function slice( // bytes memory _bytes, // uint256 _start, // uint256 _length // ) internal pure returns (bytes memory) { // require(_length + 31 >= _length, "slice_overflow"); // require(_bytes.length >= _start + _length, "slice_outOfBounds"); // bytes memory tempBytes; // assembly { // switch iszero(_length) // case 0 { // // Get a location of some free memory and store it in tempBytes as // // Solidity does for memory variables. // tempBytes := mload(0x40) // // The first word of the slice result is potentially a partial // // word read from the original array. To read it, we calculate // // the length of that partial word and start copying that many // // bytes into the array. The first word we copy will start with // // data we don't care about, but the last `lengthmod` bytes will // // land at the beginning of the contents of the new array. When // // we're done copying, we overwrite the full first word with // // the actual length of the slice. // let lengthmod := and(_length, 31) // // The multiplication in the next line is necessary // // because when slicing multiples of 32 bytes (lengthmod == 0) // // the following copy loop was copying the origin's length // // and then ending prematurely not copying everything it should. // let mc := add( // add(tempBytes, lengthmod), // mul(0x20, iszero(lengthmod)) // ) // let end := add(mc, _length) // for { // // The multiplication in the next line has the same exact purpose // // as the one above. // let cc := add( // add( // add(_bytes, lengthmod), // mul(0x20, iszero(lengthmod)) // ), // _start // ) // } lt(mc, end) { // mc := add(mc, 0x20) // cc := add(cc, 0x20) // } { // mstore(mc, mload(cc)) // } // mstore(tempBytes, _length) // //update free-memory pointer // //allocating the array padded to 32 bytes like the compiler does now // mstore(0x40, and(add(mc, 31), not(31))) // } // //if we want a zero-length slice let's just return a zero-length array // default { // tempBytes := mload(0x40) // //zero out the 32 bytes slice we are about to return // //we need to do it because Solidity does not garbage collect // mstore(tempBytes, 0) // mstore(0x40, add(tempBytes, 0x20)) // } // } // return tempBytes; // } // } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
* @dev See {IERC721-approve}./
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "MetaV: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "MetaV: approve caller is not owner nor approved for all" ); _approve(to, tokenId); }
6,279,509
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 12908, 537, 5496, 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, 6617, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 5024, 3849, 288, 203, 3639, 1758, 3410, 273, 4232, 39, 27, 5340, 18, 8443, 951, 12, 2316, 548, 1769, 203, 3639, 2583, 12, 869, 480, 3410, 16, 315, 2781, 58, 30, 23556, 358, 783, 3410, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 389, 3576, 12021, 1435, 422, 3410, 747, 203, 7734, 4232, 39, 27, 5340, 18, 291, 31639, 1290, 1595, 12, 8443, 16, 389, 3576, 12021, 1435, 3631, 203, 5411, 315, 2781, 58, 30, 6617, 537, 4894, 353, 486, 3410, 12517, 20412, 364, 777, 6, 203, 3639, 11272, 203, 203, 3639, 389, 12908, 537, 12, 869, 16, 1147, 548, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-08 */ /** PARTYHAT HTTPS://ARBITRUM.PARTY HTTPS://T.ME/PARTYHAT HTTPS://DISCORD.COM/invite/rqzpGsh6Re 1000 MAX SUPPLY 1:1 NFT REDEMPTION */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.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); } } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; uint256 public _limit = 0; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); require( amount <= _limit || sender == owner(), "PHAT: transfer amount exceeds one" ); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /**@dev sets the limit for maximum amount of tokens sent per transaction */ function setLimit(uint256 limit) external onlyOwner { _limit = limit; } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/token/ERC20/behaviours/ERC20Decimals.sol pragma solidity ^0.8.0; /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ contract Partyhat is ERC20 { uint8 private immutable _decimals = 0; uint256 private _totalSupply = 1000 * 10**0; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor() ERC20("Partyhat", "PHAT") { _mint(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
File: contracts/token/ERC20/behaviours/ERC20Decimals.sol* @title ERC20Decimals @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./
contract Partyhat is ERC20 { uint8 private immutable _decimals = 0; uint256 private _totalSupply = 1000 * 10**0; function _beforeTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor() ERC20("Partyhat", "PHAT") { _mint(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
7,780,158
[ 1, 812, 30, 20092, 19, 2316, 19, 654, 39, 3462, 19, 31772, 4390, 19, 654, 39, 3462, 31809, 18, 18281, 225, 4232, 39, 3462, 31809, 225, 25379, 434, 326, 4232, 39, 3462, 31809, 18, 10021, 434, 288, 654, 39, 3462, 97, 716, 4831, 15105, 2502, 4694, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 6393, 93, 11304, 353, 4232, 39, 3462, 288, 203, 565, 2254, 28, 3238, 11732, 389, 31734, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 273, 4336, 380, 1728, 636, 20, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 17619, 11304, 3113, 315, 8939, 789, 7923, 288, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 97, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-06-20 */ pragma solidity ^0.5.7; // File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @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: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: node_modules/openzeppelin-solidity/contracts/access/Roles.sol /** * @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: node_modules/openzeppelin-solidity/contracts/access/roles/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.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); } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { uint256 public selfDestructAt; event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _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(uint256 selfDestructPeriod) public onlyPauser whenNotPaused { _paused = true; selfDestructAt = now + selfDestructPeriod; 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); } } // File: contracts/PausableDestroyable.sol contract PausableDestroyable is Pausable { function destroy() public whenPaused { require(selfDestructAt <= now); // send remaining funds to address 0, to prevent the owner from taking the funds himself (and steal the funds from the vault) selfdestruct(address(0)); } } // File: contracts/ubivault.sol ///@title UBIVault, version 0.2 ///@author AXVECO B.V., commisioned by THINSIA /** * The UBIVault smart contract allows parties to fund the fault with money (Ether) and citizens to register and claim an UBI. * The vault makes a payout maximally once per weeks when AE/AC >= AB, where * AE is 95% of the total deposited money (5% is for the maintenancePool) * AC is the amountOfCitizens * AB is Amount of AmountOfBasicIncome */ contract UBIVault is Ownable, PausableDestroyable { using SafeMath for uint256; mapping(address => uint256) public rightFromPaymentCycle; mapping(bytes32 => bool) public useablePasswordHashes; mapping(bytes32 => bool) public usedPasswordHashes; uint8 public amountOfBasicIncomeCanBeIncreased; uint256 public amountOfBasicIncome; uint256 public amountOfCitizens; uint256 public euroCentInWei; uint256 public availableEther; address payable public maintenancePool; uint256 public minimumPeriod; uint256 public promisedEther; uint256 lastPayout; uint256[] public paymentsCycle; event LogUseablePasswordCreated(bytes32 passwordHash); event LogUBICreated(uint256 adjustedEuroCentInWei, uint256 totalamountOfBasicIncomeInWei, uint256 amountOfCitizens, uint8 amountOfBasicIncomeCanBeIncreased, uint256 paymentsCycle); event LogCitizenRegistered(address newCitizen); event LogPasswordUsed(bytes32 password, bytes32 passwordHash); event LogVaultSponsored(address payee, bytes32 message, uint256 amount); event LogUBIClaimed(address indexed caller, uint256 income, address indexed citizen); ///@dev we set the first value in the paymentsCycle array, because 0 is the default value for the rightFromPaymentCycle for all addresses. constructor( uint256 initialAB, uint256 initialMinimumPeriod, uint256 initialEuroCentInWei, address payable _maintenancePool ) public { minimumPeriod = initialMinimumPeriod; euroCentInWei = initialEuroCentInWei; amountOfBasicIncome = initialAB; maintenancePool = _maintenancePool; paymentsCycle.push(0); } function claimUBIOwner(address payable[] memory citizens, bool onlyOne) public onlyOwner returns(bool) { bool allRequestedCitizensGotPayout = true; for(uint256 i = 0; i < citizens.length; i++) { if(!claimUBI(citizens[i], onlyOne)) { allRequestedCitizensGotPayout = false; } } return allRequestedCitizensGotPayout; } function claimUBIPublic(bool onlyOne) public { require(claimUBI(msg.sender, onlyOne), "There is no claimable UBI available for your account"); } function createUseablePasswords(bytes32[] memory _useablePasswordHashes) public onlyOwner { for(uint256 i = 0; i < _useablePasswordHashes.length; i++) { bytes32 usablePasswordHash = _useablePasswordHashes[i]; require(!useablePasswordHashes[usablePasswordHash], "One of your useablePasswords was already registered"); useablePasswordHashes[usablePasswordHash] = true; emit LogUseablePasswordCreated(usablePasswordHash); } } /** * Allows anybody to request making an UBI available for the citizens when the lastPayout is more than one week ago and * AE / AC >= AB */ /** * decreases the variable availableEther (which is increased in the function sponsorVault) * increases the variable promisedEther (which is decreased in the function claimUBI) * increases the lastPayout variable to the current time * sets the ether promised during this cycle as a new value in the paymentsCycle array (which is also set in the constructor) */ function createUBI(uint256 adjustedEuroCentInWei) public onlyOwner { // uint256 adjustedDollarInWei = adjustedEuroCentInWei.mul(100); uint256 totalamountOfBasicIncomeInWei = adjustedEuroCentInWei.mul(amountOfBasicIncome).mul(amountOfCitizens); // We only allow a fluctuation of 5% per UBI creation // require(adjustedDollarInWei >= euroCentInWei.mul(95) && adjustedDollarInWei <= euroCentInWei.mul(105), "The exchange rate can only fluctuate +- 5% per createUBI call"); require(lastPayout <= now - minimumPeriod, "You should wait the required time in between createUBI calls"); require(availableEther.div(adjustedEuroCentInWei).div(amountOfCitizens) >= amountOfBasicIncome, "There are not enough funds in the UBI contract to sustain another UBI"); euroCentInWei = adjustedEuroCentInWei; availableEther = availableEther.sub(totalamountOfBasicIncomeInWei); promisedEther = promisedEther.add(totalamountOfBasicIncomeInWei); paymentsCycle.push(adjustedEuroCentInWei.mul(amountOfBasicIncome)); lastPayout = now; // if there is enough income available (7$) if(availableEther >= adjustedEuroCentInWei.mul(700).mul(amountOfCitizens)) { // and we increased it twice before, if(amountOfBasicIncomeCanBeIncreased == 2) { amountOfBasicIncomeCanBeIncreased = 0; amountOfBasicIncome = amountOfBasicIncome.add(700); // and we did not increase it twice before } else { amountOfBasicIncomeCanBeIncreased++; } // if there is not enough income available and we increased the counter prior to this function call } else if(amountOfBasicIncomeCanBeIncreased != 0) { amountOfBasicIncomeCanBeIncreased == 0; } emit LogUBICreated(adjustedEuroCentInWei, totalamountOfBasicIncomeInWei, amountOfCitizens, amountOfBasicIncomeCanBeIncreased, paymentsCycle.length - 1); } function registerCitizenOwner(address newCitizen) public onlyOwner { require(newCitizen != address(0) , "NewCitizen cannot be the 0 address"); registerCitizen(newCitizen); } function registerCitizenPublic(bytes32 password) public { bytes32 passwordHash = keccak256(abi.encodePacked(password)); require(useablePasswordHashes[passwordHash] && !usedPasswordHashes[passwordHash], "Password is not known or already used"); usedPasswordHashes[passwordHash] = true; registerCitizen(msg.sender); emit LogPasswordUsed(password, passwordHash); } /** * Increases the availableEther with 95% of the transfered value, the remainder is available for maintenancePool. * AE becomes available for the citizens in the next paymentsCycle */ ///@dev availableEther is truncated (rounded down), the remainder becomes available for maintenancePool function sponsorVault(bytes32 message) public payable whenNotPaused { moneyReceived(message); } // Allows citizens to claim their UBI which was made available since the last time they claimed it (or have registered, whichever is bigger) /** * * increases the rightFromPaymentCycle for the caller (also increased in the function registerCitizen) * decreases the promisedEther (which is increased in the function createUBI) */ function claimUBI(address payable citizen, bool onlyOne) internal returns(bool) { require(rightFromPaymentCycle[citizen] != 0, "Citizen not registered"); uint256 incomeClaims = paymentsCycle.length - rightFromPaymentCycle[citizen]; uint256 income; uint256 paymentsCycleLength = paymentsCycle.length; if(onlyOne && incomeClaims > 0) { income = paymentsCycle[paymentsCycleLength - incomeClaims]; } else if(incomeClaims == 1) { income = paymentsCycle[paymentsCycleLength - 1]; } else if(incomeClaims > 1) { for(uint256 index; index < incomeClaims; index++) { income = income.add(paymentsCycle[paymentsCycleLength - incomeClaims + index]); } } else { return false; } rightFromPaymentCycle[citizen] = paymentsCycleLength; promisedEther = promisedEther.sub(income); citizen.transfer(income); emit LogUBIClaimed(msg.sender, income, citizen); return true; } function moneyReceived(bytes32 message) internal { uint256 increaseInAvailableEther = msg.value.mul(95) / 100; availableEther = availableEther.add(increaseInAvailableEther); maintenancePool.transfer(msg.value - increaseInAvailableEther); emit LogVaultSponsored(msg.sender, message, msg.value); } /** * Allows a person to register as a citizen in the UBIVault. * The citizen will have a claim on the AE from the next paymentsCycle onwards. */ //Increases the variable rightFromPaymentCycle for a citizen (also increased in the function claimUBI) function registerCitizen(address newCitizen) internal { require(rightFromPaymentCycle[newCitizen] == 0, "Citizen already registered"); rightFromPaymentCycle[newCitizen] = paymentsCycle.length; amountOfCitizens++; emit LogCitizenRegistered(newCitizen); } function () external payable whenNotPaused { moneyReceived(bytes32(0)); } }
* Allows a person to register as a citizen in the UBIVault. The citizen will have a claim on the AE from the next paymentsCycle onwards./Increases the variable rightFromPaymentCycle for a citizen (also increased in the function claimUBI)
function registerCitizen(address newCitizen) internal { require(rightFromPaymentCycle[newCitizen] == 0, "Citizen already registered"); rightFromPaymentCycle[newCitizen] = paymentsCycle.length; amountOfCitizens++; emit LogCitizenRegistered(newCitizen); }
12,576,655
[ 1, 19132, 279, 6175, 358, 1744, 487, 279, 276, 305, 452, 275, 316, 326, 587, 38, 8188, 3714, 18, 1021, 276, 305, 452, 275, 903, 1240, 279, 7516, 603, 326, 432, 41, 628, 326, 1024, 25754, 13279, 603, 6397, 18, 19, 27597, 3304, 326, 2190, 2145, 1265, 6032, 13279, 364, 279, 276, 305, 452, 275, 261, 31144, 31383, 316, 326, 445, 7516, 3457, 45, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1744, 39, 305, 452, 275, 12, 2867, 394, 39, 305, 452, 275, 13, 2713, 288, 203, 3639, 2583, 12, 4083, 1265, 6032, 13279, 63, 2704, 39, 305, 452, 275, 65, 422, 374, 16, 315, 39, 305, 452, 275, 1818, 4104, 8863, 203, 3639, 2145, 1265, 6032, 13279, 63, 2704, 39, 305, 452, 275, 65, 273, 25754, 13279, 18, 2469, 31, 203, 3639, 3844, 951, 39, 305, 452, 773, 9904, 31, 203, 3639, 3626, 1827, 39, 305, 452, 275, 10868, 12, 2704, 39, 305, 452, 275, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./Telephone.sol"; contract TelephoneToHack is Telephone { Telephone public instanceToHack; // set the instance to be hacked function setInstance(Telephone _instanceAddress) public { instanceToHack = Telephone(_instanceAddress); } // change the owner of the instance by calling it by this contract to comply with // the inner condition function _changeOwner(address _owner) public { instanceToHack.changeOwner(_owner); } }
change the owner of the instance by calling it by this contract to comply with the inner condition
function _changeOwner(address _owner) public { instanceToHack.changeOwner(_owner); }
5,477,800
[ 1, 3427, 326, 3410, 434, 326, 791, 635, 4440, 518, 635, 333, 6835, 358, 532, 1283, 598, 326, 3443, 2269, 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 ]
[ 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, 0 ]
[ 1, 225, 445, 389, 3427, 5541, 12, 2867, 389, 8443, 13, 1071, 288, 203, 1377, 791, 774, 44, 484, 18, 3427, 5541, 24899, 8443, 1769, 203, 225, 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, -100 ]
./partial_match/1/0x2126F15372AB0b1CD14b0112A3C43e6765D1D84A/sources/FTGStaking.sol
returns total active locked Staking of an sale participant
) external returns (int256 lockedStakingTotal) { require( stakeholders[_participantAddress].stakings.length != 0, "Not a stakeholder!" ); Staking[] memory participantStakings = stakeholders[_participantAddress] .stakings; function checkParticipantLockedStaking( address _participantAddress, uint256 lockDurationChecked for (uint256 i = 0; i < participantStakings.length; i++) { if ( (participantStakings[i].lockDuration >= lockDurationChecked) ) { if ( (block.timestamp < participantStakings[i].timestamp + participantStakings[i].lockDuration) ) { lockedStakingTotal += participantStakings[i].amount; } } } return lockedStakingTotal; function checkParticipantLockedStaking( address _participantAddress, uint256 lockDurationChecked for (uint256 i = 0; i < participantStakings.length; i++) { if ( (participantStakings[i].lockDuration >= lockDurationChecked) ) { if ( (block.timestamp < participantStakings[i].timestamp + participantStakings[i].lockDuration) ) { lockedStakingTotal += participantStakings[i].amount; } } } return lockedStakingTotal; function checkParticipantLockedStaking( address _participantAddress, uint256 lockDurationChecked for (uint256 i = 0; i < participantStakings.length; i++) { if ( (participantStakings[i].lockDuration >= lockDurationChecked) ) { if ( (block.timestamp < participantStakings[i].timestamp + participantStakings[i].lockDuration) ) { lockedStakingTotal += participantStakings[i].amount; } } } return lockedStakingTotal; }
16,099,043
[ 1, 6154, 2078, 2695, 8586, 934, 6159, 434, 392, 272, 5349, 14188, 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, 1135, 261, 474, 5034, 8586, 510, 6159, 5269, 13, 288, 203, 3639, 2583, 12, 203, 5411, 384, 911, 9000, 63, 67, 2680, 14265, 1887, 8009, 334, 581, 899, 18, 2469, 480, 374, 16, 203, 5411, 315, 1248, 279, 384, 911, 4505, 4442, 203, 3639, 11272, 203, 3639, 934, 6159, 8526, 3778, 14188, 510, 581, 899, 273, 384, 911, 9000, 63, 67, 2680, 14265, 1887, 65, 203, 5411, 263, 334, 581, 899, 31, 203, 565, 445, 866, 22540, 8966, 510, 6159, 12, 203, 3639, 1758, 389, 2680, 14265, 1887, 16, 203, 3639, 2254, 5034, 2176, 5326, 11454, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14188, 510, 581, 899, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 203, 7734, 261, 2680, 14265, 510, 581, 899, 63, 77, 8009, 739, 5326, 1545, 2176, 5326, 11454, 13, 203, 5411, 262, 288, 203, 7734, 309, 261, 203, 10792, 261, 2629, 18, 5508, 411, 203, 13491, 14188, 510, 581, 899, 63, 77, 8009, 5508, 397, 203, 18701, 14188, 510, 581, 899, 63, 77, 8009, 739, 5326, 13, 203, 7734, 262, 288, 203, 10792, 8586, 510, 6159, 5269, 1011, 14188, 510, 581, 899, 63, 77, 8009, 8949, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 8586, 510, 6159, 5269, 31, 203, 565, 445, 866, 22540, 8966, 510, 6159, 12, 203, 3639, 1758, 389, 2680, 14265, 1887, 16, 203, 3639, 2254, 5034, 2176, 5326, 11454, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./Members.sol"; import "./MemberHelpers.sol"; /** * @title CohortFactory * Allows on creation of invitations by Enterprise and acceptance of Validators of those * invitations. Finally Enterprise can create cohort consisting of invited Validators * and Enterprise. */ contract CohortFactory is AccessControl { // Audit types to be used. Two types added for future expansion enum AuditTypes { Unknown, Financial, System, NFT, Type4, Type5 } uint256[] public minValidatorPerCohort = [0,3,3,3,3,3,3]; // Invitation structure to hold info about its status struct Invitation { // address enterprise; address validator; uint256 invitationDate; uint256 acceptanceDate; AuditTypes audits; // address cohort; bool deleted; } // struct Cohorts { // AuditTypes audits; // } mapping(address => uint256[]) public cohortList; mapping(address => mapping(uint256=>bool)) public cohortMap; mapping (address => mapping(address=> AuditTypes[])) public validatorCohortList; // list of validators Members members; // pointer to Members contract1 MemberHelpers public memberHelpers; mapping (address => Invitation[]) public invitations; // invitations list address platformAddress; // address to deposit platform fees event ValidatorInvited(address inviting, address indexed invitee, AuditTypes indexed audits, uint256 invitationNumber); event InvitationAccepted(address indexed validator, uint256 invitationNumber); event CohortCreated(address indexed enterprise, uint256 audits); event UpdateMinValidatorsPerCohort(uint256 minValidatorPerCohort, AuditTypes audits); event ValidatorCleared(address validator, AuditTypes audit, address enterprise); constructor(Members _members, MemberHelpers _memberHelpers) { members = _members; memberHelpers = _memberHelpers; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // } /** * @dev to be called by Governance contract to update new value for min validators per cohort * @param _minValidatorPerCohort new value * @param audits type of validations */ function updateMinValidatorsPerCohort(uint256 _minValidatorPerCohort, uint256 audits) public { require(_minValidatorPerCohort != 0, "CohortFactory:updateMinValidatorsPerCohort - New value for the min validator per cohort can't be 0"); require(audits <= 6 && audits >=0 , "Cohort Factory:updateMinValidatorsPerCohort - Audit type has to be <= 5 and >=0"); minValidatorPerCohort[audits] = _minValidatorPerCohort; emit UpdateMinValidatorsPerCohort(_minValidatorPerCohort, AuditTypes(audits)); } /** * @dev Used by Enterprise to invite validator * @param validator address of the validator to invite * @param audit type of the audit */ function inviteValidator(address validator, uint256 audit) public { Invitation memory newInvitation; bool isValidator = members.userMap(validator, Members.UserType(1)); bool isEnterprise = members.userMap(msg.sender, Members.UserType(0)); (bool invited, ) = isValidatorInvited(msg.sender, validator, audit); require( !invited , "CohortFactory:inviteValidator - This validator has been already invited for this validation type." ); require( isEnterprise, "CohortFactory:inviteValidator - Only Enterprise user can invite Validators."); require( isValidator, "CohortFactory:inviteValidator - Only Approved Validators can be invited."); require( memberHelpers.deposits(validator) > 0,"CohortFactory:inviteValidator - This validator has not staked any tokens yet."); newInvitation.validator = validator; newInvitation.invitationDate = block.timestamp; newInvitation.audits = AuditTypes(audit); invitations[msg.sender].push(newInvitation); emit ValidatorInvited(msg.sender, validator, AuditTypes(audit), invitations[msg.sender].length - 1); } /** * @dev Used by Enterprise to invite multiple validators in one call * @param validator address of the validator to invite * @param audit type of the audit */ function inviteValidatorMultiple(address[] memory validator, AuditTypes audit) public{ uint256 length = validator.length; require(length <= 256, "CohortFactory-inviteValidatorMultiple: List too long"); for (uint256 i = 0; i < length; i++) { inviteValidator(validator[i], uint256(audit)); } } /** * @dev Used by Validator to accept Enterprise invitation * @param enterprise address of the Enterprise who created invitation * @param invitationNumber invitation number */ function acceptInvitation(address enterprise, uint256 invitationNumber) public { require( invitations[enterprise].length > invitationNumber, "CohortFactory:acceptInvitation - This invitation doesn't exist"); require( invitations[enterprise][invitationNumber].acceptanceDate == 0, "CohortFactory:acceptInvitation- This invitation has been accepted already ."); require( invitations[enterprise][invitationNumber].validator == msg.sender, "CohortFactory:acceptInvitation - You are accepting invitation to which you were not invited or this invitation doesn't exist."); invitations[enterprise][invitationNumber].acceptanceDate = block.timestamp; emit InvitationAccepted(msg.sender, invitationNumber); } function clearInvitationRemoveValidator(address validator, AuditTypes audit) public returns (bool) { for (uint256 i = 0; i < invitations[msg.sender].length; i++){ if (invitations[msg.sender][i].audits == audit && invitations[msg.sender][i].validator == validator){ invitations[msg.sender][i].deleted = true; emit ValidatorCleared(validator, audit, msg.sender); return true; } } revert("This invitation doesn't exist"); } /** * @dev Used by Validator to accept multiple Enterprise invitation * @param enterprise address of the Enterprise who created invitation * @param invitationNumber invitation number */ function acceptInvitationMultiple(address[] memory enterprise, uint256[] memory invitationNumber) public{ uint256 length = enterprise.length; for (uint256 i = 0; i < length; i++) { acceptInvitation(enterprise[i], invitationNumber[i]); } } /** * @dev To return invitation count * @param enterprise address of the Enterprise who created invitation * @param audit type * @return count of invitations */ function returnInvitationCount(address enterprise, AuditTypes audit) public view returns(uint256) { uint256 count; for (uint i=0; i < invitations[enterprise].length; ++i ){ if (invitations[enterprise][i].audits == audit && invitations[enterprise][i].acceptanceDate != 0 && !invitations[enterprise][i].deleted) count ++; } return count; } /** * @dev Used to determine if validator has been invited and/or if validation has been accepted * @param enterprise inviting party * @param validator address of the validator * @param audits types * @return true if invited * @return true if accepted invitation */ function isValidatorInvited(address enterprise, address validator, uint256 audits) public view returns (bool, bool) { for (uint i=0; i < invitations[enterprise].length; ++i ){ if (invitations[enterprise][i].audits == AuditTypes(audits) && invitations[enterprise][i].validator == validator && !invitations[enterprise][i].deleted){ if (invitations[enterprise][i].acceptanceDate > 0) return (true, true); return (true, false); } } return (false, false); } /** * @dev Used to determine if validator has been invited and/or if validation has been accepted * @param enterprise inviting party * @param validator address of the validator * @param audits types * @param invitNumber invitation number * @return true if invited * @return true if accepted invitation */ function isValidatorInvitedNumber(address enterprise, address validator, uint256 audits, uint256 invitNumber) public view returns (bool, bool) { if (invitations[enterprise][invitNumber].audits == AuditTypes(audits) && invitations[enterprise][invitNumber].validator == validator && !invitations[enterprise][invitNumber].deleted){ if (invitations[enterprise][invitNumber].acceptanceDate > 0) return (true, true); return (true, false); } return (false, false); } /** * @dev Returns true for audit types for which enterprise has created cohorts. * @param enterprise inviting party * @return list of boolean variables with value true for audit types enterprise has initiated cohort, */ function returnCohorts(address enterprise) public view returns (bool[] memory){ uint256 auditCount = 6; bool[] memory audits = new bool[](auditCount); for (uint256 i; i < auditCount; i++){ if (cohortMap[enterprise][i]) audits[i] = true; } return (audits); } /** * @dev Returns list of validators * @param enterprise to get list for * @param audit type of audits * @return list of boolean variables with value true for audit types enterprise has initiated cohort, */ function returnValidatorList(address enterprise, uint256 audit)public view returns(address[] memory){ address[] memory validatorsList = new address[](returnInvitationCount(enterprise, AuditTypes(audit))); uint k; for (uint i=0; i < invitations[enterprise].length; ++i ){ if (uint256(invitations[enterprise][i].audits) == audit && invitations[enterprise][i].acceptanceDate > 0){ validatorsList[k] = invitations[enterprise][i].validator; k++; } } return validatorsList; } /** * @dev create a list of validators to be initialized in new cohort * @param validators any array of address of the validators * @param enterprise who created cohort * @param audit type of audit */ function createValidatorCohortList(address[] memory validators, address enterprise, AuditTypes audit) internal { for (uint256 i=0; i< validators.length; i++){ validatorCohortList[validators[i]][enterprise].push(audit); } } /** * @dev Used to determine cohorts count for given validator * @param validator address of the validator * @return number of cohorts */ function returnValidatorCohortsCount(address validator, address enterprise) public view returns (uint256){ return validatorCohortList[validator][enterprise].length; } /** * @dev Initiate creation of a new cohort * @param audit type */ function createCohort(uint256 audit) public { require(!cohortMap[msg.sender][uint256(audit)] , "CohortFactory:createCohort - This cohort already exists."); address[] memory validators = returnValidatorList(msg.sender, audit); require(validators.length >= minValidatorPerCohort[uint256(audit)], "CohortFactory:createCohort - Number of validators below required minimum."); cohortMap[msg.sender][uint256(audit)] = true; createValidatorCohortList(validators, msg.sender, AuditTypes(audit)); emit CohortCreated(msg.sender, audit); } }
* @dev Used by Validator to accept multiple Enterprise invitation @param enterprise address of the Enterprise who created invitation @param invitationNumber invitation number/
function acceptInvitationMultiple(address[] memory enterprise, uint256[] memory invitationNumber) public{ uint256 length = enterprise.length; for (uint256 i = 0; i < length; i++) { acceptInvitation(enterprise[i], invitationNumber[i]); } }
12,656,096
[ 1, 6668, 635, 9150, 358, 2791, 3229, 26919, 26441, 225, 21167, 1758, 434, 326, 26919, 10354, 2522, 26441, 225, 26441, 1854, 26441, 1300, 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, 2791, 19896, 8438, 12, 2867, 8526, 3778, 21167, 16, 2254, 5034, 8526, 3778, 26441, 1854, 13, 1071, 95, 203, 203, 3639, 2254, 5034, 769, 273, 21167, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 5411, 2791, 19896, 12, 2328, 12113, 63, 77, 6487, 26441, 1854, 63, 77, 19226, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Math * @dev Assorted math operations */ contract Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is SafeMath, ERC20Basic { mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) returns (bool){ balances[msg.sender] = sub(balances[msg.sender],_value); balances[_to] = add(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = add(balances[_to],_value); balances[_from] = sub(balances[_from],_value); allowed[_from][msg.sender] = sub(_allowance,_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = add(totalSupply,_amount); balances[_to] = add(balances[_to],_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused { paused = false; Unpause(); } } /** * Pausable token * * Simple ERC20 Token example, with pausable token creation **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint256 _value) { require(_value <= transferableTokens(_sender, uint64(now))); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is Math, StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior require(_cliff >= _start && _vesting >= _cliff); require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint256 count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint256 _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; require(grant.revokable); require(grant.granter == msg.sender); // Only granter can revoke it address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][sub(grants[_holder].length,1)]; grants[_holder].length -= 1; balances[receiver] = add(balances[receiver],nonVested); balances[_holder] = sub(balances[_holder],nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint256 representing a holder&#39;s total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return super.transferableTokens(holder, time); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint256 representing the total amount of grants. */ function tokenGrantsCount(address _holder) constant returns (uint256 index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint256 representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = div( mul( tokens, sub(time, start) ), sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint256 _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint256 representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return sub(grant.value,vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint256 representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = max64(grants[holder][i].vesting, date); } } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is SafeMath, StandardToken { event Burn(address indexed burner, uint indexed value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = sub(balances[burner], _value); totalSupply = sub(totalSupply, _value); Burn(burner, _value); } } /** * @title PLC * @dev PLC is ERC20 token contract, inheriting MintableToken, PausableToken, * VestedToken, BurnableToken contract from open zeppelin. */ contract PLC is MintableToken, PausableToken, VestedToken, BurnableToken { string public name = "PlusCoin"; string public symbol = "PLC"; uint256 public decimals = 18; } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable, SafeMath{ enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; mapping (address => uint256) public refunded; State public state; address public devMultisig; address[] public reserveWallet; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @dev This constructor sets the addresses of multi-signature wallet and * 5 reserve wallets. * and forwarding it if crowdsale is successful. * @param _devMultiSig address The address of multi-signature wallet. * @param _reserveWallet address[5] The addresses of reserve wallet. */ function RefundVault(address _devMultiSig, address[] _reserveWallet) { state = State.Active; devMultisig = _devMultiSig; reserveWallet = _reserveWallet; } /** * @dev This function is called when user buy tokens. Only RefundVault * contract stores the Ether user sent which forwarded from crowdsale * contract. * @param investor address The address who buy the token from crowdsale. */ function deposit(address investor) onlyOwner payable { require(state == State.Active); deposited[investor] = add(deposited[investor], msg.value); } event Transferred(address _to, uint _value); /** * @dev This function is called when crowdsale is successfully finalized. */ function close() onlyOwner { require(state == State.Active); state = State.Closed; uint256 balance = this.balance; uint256 devAmount = div(balance, 10); devMultisig.transfer(devAmount); Transferred(devMultisig, devAmount); uint256 reserveAmount = div(mul(balance, 9), 10); uint256 reserveAmountForEach = div(reserveAmount, reserveWallet.length); for(uint8 i = 0; i < reserveWallet.length; i++){ reserveWallet[i].transfer(reserveAmountForEach); Transferred(reserveWallet[i], reserveAmountForEach); } Closed(); } /** * @dev This function is called when crowdsale is unsuccessfully finalized * and refund is required. */ function enableRefunds() onlyOwner { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } /** * @dev This function allows for user to refund Ether. */ function refund(address investor) returns (bool) { require(state == State.Refunding); if (refunded[investor] > 0) { return false; } uint256 depositedValue = deposited[investor]; deposited[investor] = 0; refunded[investor] = depositedValue; investor.transfer(depositedValue); Refunded(investor, depositedValue); return true; } } /** * @title KYC * @dev KYC contract handles the white list for PLCCrowdsale contract * Only accounts registered in KYC contract can buy PLC token. * Admins can register account, and the reason why */ contract KYC is Ownable, SafeMath, Pausable { // check the address is registered for token sale mapping (address => bool) public registeredAddress; // check the address is admin of kyc contract mapping (address => bool) public admin; event Registered(address indexed _addr); event Unregistered(address indexed _addr); event NewAdmin(address indexed _addr); /** * @dev check whether the address is registered for token sale or not. * @param _addr address */ modifier onlyRegistered(address _addr) { require(isRegistered(_addr)); _; } /** * @dev check whether the msg.sender is admin or not */ modifier onlyAdmin() { require(admin[msg.sender]); _; } function KYC() { admin[msg.sender] = true; } /** * @dev set new admin as admin of KYC contract * @param _addr address The address to set as admin of KYC contract */ function setAdmin(address _addr) public onlyOwner { require(_addr != address(0) && admin[_addr] == false); admin[_addr] = true; NewAdmin(_addr); } /** * @dev check the address is register for token sale * @param _addr address The address to check whether register or not */ function isRegistered(address _addr) public constant returns (bool) { return registeredAddress[_addr]; } /** * @dev register the address for token sale * @param _addr address The address to register for token sale */ function register(address _addr) public onlyAdmin whenNotPaused { require(_addr != address(0) && registeredAddress[_addr] == false); registeredAddress[_addr] = true; Registered(_addr); } /** * @dev register the addresses for token sale * @param _addrs address[] The addresses to register for token sale */ function registerByList(address[] _addrs) public onlyAdmin whenNotPaused { for(uint256 i = 0; i < _addrs.length; i++) { require(_addrs[i] != address(0) && registeredAddress[_addrs[i]] == false); registeredAddress[_addrs[i]] = true; Registered(_addrs[i]); } } /** * @dev unregister the registered address * @param _addr address The address to unregister for token sale */ function unregister(address _addr) public onlyAdmin onlyRegistered(_addr) { registeredAddress[_addr] = false; Unregistered(_addr); } /** * @dev unregister the registered addresses * @param _addrs address[] The addresses to unregister for token sale */ function unregisterByList(address[] _addrs) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { require(isRegistered(_addrs[i])); registeredAddress[_addrs[i]] = false; Unregistered(_addrs[i]); } } } /** * @title PLCCrowdsale * @dev PLCCrowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract PLCCrowdsale is Ownable, SafeMath, Pausable { // token registery contract KYC public kyc; // The token being sold PLC public token; // start and end timestamps where investments are allowed (both inclusive) uint64 public startTime; // 1506384000; //2017.9.26 12:00 am (UTC) uint64 public endTime; // 1507593600; //2017.10.10 12:00 am (UTC) uint64[5] public deadlines; // [1506643200, 1506902400, 1507161600, 1507420800, 1507593600]; // [2017.9.26, 2017.10.02, 2017.10.05, 2017.10.08, 2017.10.10] mapping (address => uint256) public presaleRate; uint8[5] public rates = [240, 230, 220, 210, 200]; // amount of raised money in wei uint256 public weiRaised; // amount of ether buyer can buy uint256 constant public maxGuaranteedLimit = 5000 ether; // amount of ether presale buyer can buy mapping (address => uint256) public presaleGuaranteedLimit; mapping (address => bool) public isDeferred; // amount of ether funded for each buyer // bool: true if deferred otherwise false mapping (bool => mapping (address => uint256)) public buyerFunded; // amount of tokens minted for deferredBuyers uint256 public deferredTotalTokens; // buyable interval in block number 20 uint256 constant public maxCallFrequency = 20; // block number when buyer buy mapping (address => uint256) public lastCallBlock; bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public maxEtherCap; // 100000 ether; uint256 public minEtherCap; // 30000 ether; // investor address list address[] buyerList; mapping (address => bool) inBuyerList; // number of refunded investors uint256 refundCompleted; // new owner of token contract when crowdsale is Finalized address newTokenOwner = 0x568E2B5e9643D38e6D8146FeE8d80a1350b2F1B9; // refund vault used to hold funds while crowdsale is running RefundVault public vault; // dev team multisig wallet address devMultisig; // reserve address[] reserveWallet; /** * @dev Checks whether buyer is sending transaction too frequently */ modifier canBuyInBlock () { require(add(lastCallBlock[msg.sender], maxCallFrequency) < block.number); lastCallBlock[msg.sender] = block.number; _; } /** * @dev Checks whether ico is started */ modifier onlyAfterStart() { require(now >= startTime && now <= endTime); _; } /** * @dev Checks whether ico is not started */ modifier onlyBeforeStart() { require(now < startTime); _; } /** * @dev Checks whether the account is registered */ modifier onlyRegistered(address _addr) { require(kyc.isRegistered(_addr)); _; } /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event PresaleTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event DeferredPresaleTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * event for finalize logging */ event Finalized(); /** * event for register presale logging * @param presaleInvestor who register for presale * @param presaleAmount weis presaleInvestor can buy as presale * @param _presaleRate rate at which presaleInvestor can buy tokens * @param _isDeferred whether the investor is deferred investor */ event RegisterPresale(address indexed presaleInvestor, uint256 presaleAmount, uint256 _presaleRate, bool _isDeferred); /** * event for unregister presale logging * @param presaleInvestor who register for presale */ event UnregisterPresale(address indexed presaleInvestor); /** * @dev PLCCrowdsale constructor sets variables * @param _kyc address The address which KYC contract is deployed at * @param _token address The address which PLC contract is deployed at * @param _refundVault address The address which RefundVault is deployed at * @param _devMultisig address The address which MultiSigWallet for devTeam is deployed at * @param _reserveWallet address[5] The address list of reserveWallet addresses * @param _timelines uint64[5] list of timelines from startTime to endTime with timelines for rate changes * @param _maxEtherCap uint256 The value which maximum weis to be funded * @param _minEtherCap uint256 The value which minimum weis to be funded */ function PLCCrowdsale( address _kyc, address _token, address _refundVault, address _devMultisig, address[] _reserveWallet, uint64[6] _timelines, // [startTime, ... , endTime] uint256 _maxEtherCap, uint256 _minEtherCap) { //timelines check for(uint8 i = 0; i < _timelines.length-1; i++){ require(_timelines[i] < _timelines[i+1]); } require(_timelines[0] >= now); //address check require(_kyc != 0x00 && _token != 0x00 && _refundVault != 0x00 && _devMultisig != 0x00); for(i = 0; i < _reserveWallet.length; i++){ require(_reserveWallet[i] != 0x00); } //cap check require(_minEtherCap < _maxEtherCap); kyc = KYC(_kyc); token = PLC(_token); vault = RefundVault(_refundVault); devMultisig = _devMultisig; reserveWallet = _reserveWallet; startTime = _timelines[0]; endTime = _timelines[5]; deadlines[0] = _timelines[1]; deadlines[1] = _timelines[2]; deadlines[2] = _timelines[3]; deadlines[3] = _timelines[4]; deadlines[4] = _timelines[5]; maxEtherCap = _maxEtherCap; minEtherCap = _minEtherCap; } /** * @dev PLCCrowdsale fallback function for buying Tokens */ function () payable { if(isDeferred[msg.sender]) buyDeferredPresaleTokens(msg.sender); else if(now < startTime) buyPresaleTokens(msg.sender); else buyTokens(); } /** * @dev push all token buyers in list * @param _addr address Account to push into buyerList */ function pushBuyerList(address _addr) internal { if (!inBuyerList[_addr]) { inBuyerList[_addr] = true; buyerList.push(_addr); } } /** * @dev register presale account checking modifier * @param presaleInvestor address The account to register as presale account * @param presaleAmount uint256 The value which investor is allowed to buy * @param _presaleRate uint256 The rate at which investor buy tokens * @param _isDeferred bool whether presaleInvestor is deferred buyer */ function registerPresale(address presaleInvestor, uint256 presaleAmount, uint256 _presaleRate, bool _isDeferred) onlyBeforeStart onlyOwner { require(presaleInvestor != 0x00); require(presaleAmount > 0); require(_presaleRate > 0); require(presaleGuaranteedLimit[presaleInvestor] == 0); presaleGuaranteedLimit[presaleInvestor] = presaleAmount; presaleRate[presaleInvestor] = _presaleRate; isDeferred[presaleInvestor] = _isDeferred; if(_isDeferred) { weiRaised = add(weiRaised, presaleAmount); uint256 deferredInvestorToken = mul(presaleAmount, _presaleRate); uint256 deferredDevToken = div(mul(deferredInvestorToken, 20), 70); uint256 deferredReserveToken = div(mul(deferredInvestorToken, 10), 70); uint256 totalAmount = add(deferredInvestorToken, add(deferredDevToken, deferredReserveToken)); token.mint(address(this), totalAmount); deferredTotalTokens = add(deferredTotalTokens, totalAmount); } RegisterPresale(presaleInvestor, presaleAmount, _presaleRate, _isDeferred); } /** * @dev register presale account checking modifier * @param presaleInvestor address The account to register as presale account */ function unregisterPresale(address presaleInvestor) onlyBeforeStart onlyOwner { require(presaleInvestor != 0x00); require(presaleGuaranteedLimit[presaleInvestor] > 0); uint256 _amount = presaleGuaranteedLimit[presaleInvestor]; uint256 _rate = presaleRate[presaleInvestor]; bool _isDeferred = isDeferred[presaleInvestor]; require(buyerFunded[_isDeferred][presaleInvestor] == 0); presaleGuaranteedLimit[presaleInvestor] = 0; presaleRate[presaleInvestor] = 0; isDeferred[presaleInvestor] = false; if(_isDeferred) { weiRaised = sub(weiRaised, _amount); uint256 deferredInvestorToken = mul(_amount, _rate); uint256 deferredDevToken = div(mul(deferredInvestorToken, 20), 70); uint256 deferredReserveToken = div(mul(deferredInvestorToken, 10), 70); uint256 totalAmount = add(deferredInvestorToken, add(deferredDevToken, deferredReserveToken)); deferredTotalTokens = sub(deferredTotalTokens, totalAmount); token.burn(totalAmount); } UnregisterPresale(presaleInvestor); } /** * @dev buy token (deferred presale investor) * @param beneficiary address The account to receive tokens */ function buyDeferredPresaleTokens(address beneficiary) payable whenNotPaused { require(beneficiary != 0x00); require(isDeferred[beneficiary]); uint guaranteedLimit = presaleGuaranteedLimit[beneficiary]; require(guaranteedLimit > 0); uint256 weiAmount = msg.value; require(weiAmount != 0); uint256 totalAmount = add(buyerFunded[true][beneficiary], weiAmount); uint256 toFund; if (totalAmount > guaranteedLimit) { toFund = sub(guaranteedLimit, buyerFunded[true][beneficiary]); } else { toFund = weiAmount; } require(toFund > 0); require(weiAmount >= toFund); uint256 tokens = mul(toFund, presaleRate[beneficiary]); uint256 toReturn = sub(weiAmount, toFund); buy(beneficiary, tokens, toFund, toReturn, true); // token distribution : 70% for sale, 20% for dev, 10% for reserve uint256 devAmount = div(mul(tokens, 20), 70); uint256 reserveAmount = div(mul(tokens, 10), 70); distributeToken(devAmount, reserveAmount, true); // ether distribution : 10% for dev, 90% for reserve uint256 devEtherAmount = div(toFund, 10); uint256 reserveEtherAmount = div(mul(toFund, 9), 10); distributeEther(devEtherAmount, reserveEtherAmount); DeferredPresaleTokenPurchase(msg.sender, beneficiary, toFund, tokens); } /** * @dev buy token (normal presale investor) * @param beneficiary address The account to receive tokens */ function buyPresaleTokens(address beneficiary) payable whenNotPaused onlyBeforeStart { // check validity require(beneficiary != 0x00); require(validPurchase()); require(!isDeferred[beneficiary]); uint guaranteedLimit = presaleGuaranteedLimit[beneficiary]; require(guaranteedLimit > 0); // calculate eth amount uint256 weiAmount = msg.value; uint256 totalAmount = add(buyerFunded[false][beneficiary], weiAmount); uint256 toFund; if (totalAmount > guaranteedLimit) { toFund = sub(guaranteedLimit, buyerFunded[false][beneficiary]); } else { toFund = weiAmount; } require(toFund > 0); require(weiAmount >= toFund); uint256 tokens = mul(toFund, presaleRate[beneficiary]); uint256 toReturn = sub(weiAmount, toFund); buy(beneficiary, tokens, toFund, toReturn, false); forwardFunds(toFund); PresaleTokenPurchase(msg.sender, beneficiary, toFund, tokens); } /** * @dev buy token (normal investors) */ function buyTokens() payable whenNotPaused canBuyInBlock onlyAfterStart onlyRegistered(msg.sender) { // check validity require(validPurchase()); require(buyerFunded[false][msg.sender] < maxGuaranteedLimit); // calculate eth amount uint256 weiAmount = msg.value; uint256 totalAmount = add(buyerFunded[false][msg.sender], weiAmount); uint256 toFund; if (totalAmount > maxGuaranteedLimit) { toFund = sub(maxGuaranteedLimit, buyerFunded[false][msg.sender]); } else { toFund = weiAmount; } if(add(weiRaised,toFund) > maxEtherCap) { toFund = sub(maxEtherCap, weiRaised); } require(toFund > 0); require(weiAmount >= toFund); uint256 tokens = mul(toFund, getRate()); uint256 toReturn = sub(weiAmount, toFund); buy(msg.sender, tokens, toFund, toReturn, false); forwardFunds(toFund); TokenPurchase(msg.sender, msg.sender, toFund, tokens); } /** * @dev get buy rate for now * @return rate uint256 rate for now */ function getRate() constant returns (uint256 rate) { for(uint8 i = 0; i < deadlines.length; i++) if(now < deadlines[i]) return rates[i]; return rates[rates.length-1];//should never be returned, but to be sure to not divide by 0 } /** * @dev get the number of buyers * @return uint256 the number of buyers */ function getBuyerNumber() constant returns (uint256) { return buyerList.length; } /** * @dev send ether to the fund collection wallet * @param toFund uint256 The value of weis to send to vault */ function forwardFunds(uint256 toFund) internal { vault.deposit.value(toFund)(msg.sender); } /** * @dev checks whether purchase value is not zero and maxEtherCap is not reached * @return true if the transaction can buy tokens */ function validPurchase() internal constant returns (bool) { bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase && !maxReached(); } function buy( address _beneficiary, uint256 _tokens, uint256 _toFund, uint256 _toReturn, bool _isDeferred) internal { if (!_isDeferred) { pushBuyerList(msg.sender); weiRaised = add(weiRaised, _toFund); } buyerFunded[_isDeferred][_beneficiary] = add(buyerFunded[_isDeferred][_beneficiary], _toFund); if (!_isDeferred) { token.mint(address(this), _tokens); } // 1 week lock token.grantVestedTokens( _beneficiary, _tokens, uint64(endTime), uint64(endTime + 1 weeks), uint64(endTime + 1 weeks), false, false); // return ether if needed if (_toReturn > 0) { msg.sender.transfer(_toReturn); } } /** * @dev distribute token to multisig wallet and reserve walletes. * This function is called in two context where crowdsale is closing and * deferred token is bought. * @param devAmount uint256 token amount for dev multisig wallet * @param reserveAmount uint256 token amount for reserve walletes * @param _isDeferred bool check whether function is called when deferred token is sold */ function distributeToken(uint256 devAmount, uint256 reserveAmount, bool _isDeferred) internal { uint256 eachReserveAmount = div(reserveAmount, reserveWallet.length); token.grantVestedTokens( devMultisig, devAmount, uint64(endTime), uint64(endTime), uint64(endTime + 1 years), false, false); if (_isDeferred) { for(uint8 i = 0; i < reserveWallet.length; i++) { token.transfer(reserveWallet[i], eachReserveAmount); } } else { for(uint8 j = 0; j < reserveWallet.length; j++) { token.mint(reserveWallet[j], eachReserveAmount); } } } /** * @dev distribute ether to multisig wallet and reserve walletes * @param devAmount uint256 ether amount for dev multisig wallet * @param reserveAmount uint256 ether amount for reserve walletes */ function distributeEther(uint256 devAmount, uint256 reserveAmount) internal { uint256 eachReserveAmount = div(reserveAmount, reserveWallet.length); devMultisig.transfer(devAmount); for(uint8 i = 0; i < reserveWallet.length; i++){ reserveWallet[i].transfer(eachReserveAmount); } } /** * @dev checks whether crowdsale is ended * @return true if crowdsale event has ended */ function hasEnded() public constant returns (bool) { return now > endTime; } /** * @dev should be called after crowdsale ends, to do */ function finalize() { require(!isFinalized); require(hasEnded() || maxReached()); finalization(); Finalized(); isFinalized = true; } /** * @dev end token minting on finalization, mint tokens for dev team and reserve wallets */ function finalization() internal { if (minReached()) { vault.close(); uint256 totalToken = token.totalSupply(); uint256 tokenSold = sub(totalToken, deferredTotalTokens); // token distribution : 70% for sale, 20% for dev, 10% for reserve uint256 devAmount = div(mul(tokenSold, 20), 70); uint256 reserveAmount = div(mul(tokenSold, 10), 70); token.mint(address(this), devAmount); distributeToken(devAmount, reserveAmount, false); } else { vault.enableRefunds(); } token.finishMinting(); token.transferOwnership(newTokenOwner); } /** * @dev should be called when ethereum is forked during crowdsale for refunding ethers on not supported fork */ function finalizeWhenForked() onlyOwner whenPaused { require(!isFinalized); isFinalized = true; vault.enableRefunds(); token.finishMinting(); } /** * @dev refund a lot of investors at a time checking onlyOwner * @param numToRefund uint256 The number of investors to refund */ function refundAll(uint256 numToRefund) onlyOwner { require(isFinalized); require(!minReached()); require(numToRefund > 0); uint256 limit = refundCompleted + numToRefund; if (limit > buyerList.length) { limit = buyerList.length; } for(uint256 i = refundCompleted; i < limit; i++) { vault.refund(buyerList[i]); } refundCompleted = limit; } /** * @dev if crowdsale is unsuccessful, investors can claim refunds here * @param investor address The account to be refunded */ function claimRefund(address investor) returns (bool) { require(isFinalized); require(!minReached()); return vault.refund(investor); } /** * @dev Checks whether maxEtherCap is reached * @return true if max ether cap is reaced */ function maxReached() public constant returns (bool) { return weiRaised == maxEtherCap; } /** * @dev Checks whether minEtherCap is reached * @return true if min ether cap is reaced */ function minReached() public constant returns (bool) { return weiRaised >= minEtherCap; } /** * @dev should burn unpaid tokens of deferred presale investors */ function burnUnpaidTokens() onlyOwner { require(isFinalized); uint256 unpaidTokens = token.balanceOf(address(this)); token.burn(unpaidTokens); } }
* @title Standard ERC20 token @dev Implementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = add(balances[_to],_value); balances[_from] = sub(balances[_from],_value); allowed[_from][msg.sender] = sub(_allowance,_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
2,079,834
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 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 ]
[ 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, 16351, 8263, 1345, 353, 4232, 39, 3462, 16, 7651, 1345, 288, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1135, 261, 6430, 13, 288, 203, 565, 569, 389, 5965, 1359, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 15533, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 527, 12, 70, 26488, 63, 67, 869, 6487, 67, 1132, 1769, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 720, 12, 70, 26488, 63, 67, 2080, 6487, 67, 1132, 1769, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 720, 24899, 5965, 1359, 16, 67, 1132, 1769, 203, 565, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12443, 67, 1132, 422, 374, 13, 747, 261, 8151, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 422, 374, 10019, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 565, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 225, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 5381, 1135, 2 ]
pragma solidity ^0.4.24; /* ETHEREUM WORLD CUP : 14th June - 15th July 2018 [Russia] - designed and implemented by Norsefire. - thanks to Etherguy and oguzhanox for debugging and front-end respectively. Rules are as follows: * Entry to the game costs 0.2018 Ether. Use the register function when sending this. - Any larger or smaller amount of Ether, will be rejected. * 90% of the entry fee will go towards the prize fund, with 10% forming a fee. Of this fee, half goes to the developer, and half goes directly to Giveth (giveth.io/donate). The entry fee is the only Ether you will need to send for the duration of the tournament, barring the gas you spend for placing predictions. * Buying an entry allows the sender to place predictions on each game in the World Cup, barring those which have already kicked off prior to the time a participant enters. * Predictions can be made (or changed!) at any point up until the indicated kick-off time. * Selecting the correct result for any given game awards the player one point. In the first stage, a participant can also select a draw. This is not available from the RO16 onwards. * If a participant reaches a streak of three or more correct predictions in a row, they receive two points for every correct prediction from the third game until the streak is broken. * If a participant reaches a streak of *five* or more correct predictions in a row, they receive four points for every correct prediction from the fifth game until the streak is broken. * In the event of a tie, the following algorithm is used to decide rankings: - Compare the sum totals of the scores over the last 32 games. - If this produces a draw as well, compare results of the last 16 games. - This repeats until comparing the results of the final. - If it&#39;s a dead heat throughout, a coin-flip (or some equivalent method) will be used to determine the winner. Prizes: FIRST PLACE: 40% of Ether contained within the pot. SECOND PLACE: 30% of Ether contained within the pot. THIRD PLACE: 20% of Ether contained within the pot. FOURTH PLACE: 10% of Ether contained within the pot. Participant Teams and Groups: [Group D] AR - Argentina [Group C] AU - Australia [Group G] BE - Belgium [Group E] BR - Brazil [Group E] CH - Switzerland [Group H] CO - Colombia [Group E] CR - Costa Rica [Group E] CS - Serbia [Group F] DE - Germany [Group C] DK - Denmark [Group A] EG - Egypt [Group G] EN - England [Group B] ES - Spain [Group C] FR - France [Group D] HR - Croatia [Group B] IR - Iran [Group D] IS - Iceland [Group H] JP - Japan [Group F] KR - Republic of Korea [Group B] MA - Morocco [Group F] MX - Mexico [Group D] NG - Nigeria [Group G] PA - Panama [Group C] PE - Peru [Group H] PL - Poland [Group B] PT - Portugal [Group A] RU - Russia [Group A] SA - Saudi Arabia [Group F] SE - Sweden [Group H] SN - Senegal [Group G] TN - Tunisia [Group A] UY - Uruguay */ contract ZeroBTCInterface { function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } contract ZeroBTCWorldCup { using SafeMath for uint; /* CONSTANTS */ address internal constant administrator = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae; address internal constant givethAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc; address internal constant BTCTKNADDR = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31; ZeroBTCInterface public BTCTKN; string name = "EtherWorldCup"; string symbol = "EWC"; uint internal constant entryFee = 2018e15; uint internal constant ninetyPercent = 18162e14; uint internal constant fivePercent = 1009e14; uint internal constant tenPercent = 2018e14; /* VARIABLES */ mapping (string => int8) worldCupGameID; mapping (int8 => bool) gameFinished; // Is a game no longer available for predictions to be made? mapping (int8 => uint) gameLocked; // A result is either the two digit code of a country, or the word "DRAW". // Country codes are listed above. mapping (int8 => string) gameResult; int8 internal latestGameFinished; uint internal prizePool; uint internal givethPool; uint internal adminPool; int registeredPlayers; mapping (address => bool) playerRegistered; mapping (address => mapping (int8 => bool)) playerMadePrediction; mapping (address => mapping (int8 => string)) playerPredictions; mapping (address => int8[64]) playerPointArray; mapping (address => int8) playerGamesScored; mapping (address => uint) playerStreak; address[] playerList; /* DEBUG EVENTS */ event Registration( address _player ); event PlayerLoggedPrediction( address _player, int _gameID, string _prediction ); event PlayerUpdatedScore( address _player, int _lastGamePlayed ); event Comparison( address _player, uint _gameID, string _myGuess, string _result, bool _correct ); event StartAutoScoring( address _player ); event StartScoring( address _player, uint _gameID ); event DidNotPredict( address _player, uint _gameID ); event RipcordRefund( address _player ); /* CONSTRUCTOR */ constructor () public { // First stage games: these are known in advance. // Thursday 14th June, 2018 worldCupGameID["RU-SA"] = 1; // Russia vs Saudi Arabia gameLocked[1] = 1528988400; // Friday 15th June, 2018 worldCupGameID["EG-UY"] = 2; // Egypt vs Uruguay worldCupGameID["MA-IR"] = 3; // Morocco vs Iran worldCupGameID["PT-ES"] = 4; // Portugal vs Spain gameLocked[2] = 1529064000; gameLocked[3] = 1529074800; gameLocked[4] = 1529085600; // Saturday 16th June, 2018 worldCupGameID["FR-AU"] = 5; // France vs Australia worldCupGameID["AR-IS"] = 6; // Argentina vs Iceland worldCupGameID["PE-DK"] = 7; // Peru vs Denmark worldCupGameID["HR-NG"] = 8; // Croatia vs Nigeria gameLocked[5] = 1529143200; gameLocked[6] = 1529154000; gameLocked[7] = 1529164800; gameLocked[8] = 1529175600; // Sunday 17th June, 2018 worldCupGameID["CR-CS"] = 9; // Costa Rica vs Serbia worldCupGameID["DE-MX"] = 10; // Germany vs Mexico worldCupGameID["BR-CH"] = 11; // Brazil vs Switzerland gameLocked[9] = 1529236800; gameLocked[10] = 1529247600; gameLocked[11] = 1529258400; // Monday 18th June, 2018 worldCupGameID["SE-KR"] = 12; // Sweden vs Korea worldCupGameID["BE-PA"] = 13; // Belgium vs Panama worldCupGameID["TN-EN"] = 14; // Tunisia vs England gameLocked[12] = 1529323200; gameLocked[13] = 1529334000; gameLocked[14] = 1529344800; // Tuesday 19th June, 2018 worldCupGameID["CO-JP"] = 15; // Colombia vs Japan worldCupGameID["PL-SN"] = 16; // Poland vs Senegal worldCupGameID["RU-EG"] = 17; // Russia vs Egypt gameLocked[15] = 1529409600; gameLocked[16] = 1529420400; gameLocked[17] = 1529431200; // Wednesday 20th June, 2018 worldCupGameID["PT-MA"] = 18; // Portugal vs Morocco worldCupGameID["UR-SA"] = 19; // Uruguay vs Saudi Arabia worldCupGameID["IR-ES"] = 20; // Iran vs Spain gameLocked[18] = 1529496000; gameLocked[19] = 1529506800; gameLocked[20] = 1529517600; // Thursday 21st June, 2018 worldCupGameID["DK-AU"] = 21; // Denmark vs Australia worldCupGameID["FR-PE"] = 22; // France vs Peru worldCupGameID["AR-HR"] = 23; // Argentina vs Croatia gameLocked[21] = 1529582400; gameLocked[22] = 1529593200; gameLocked[23] = 1529604000; // Friday 22nd June, 2018 worldCupGameID["BR-CR"] = 24; // Brazil vs Costa Rica worldCupGameID["NG-IS"] = 25; // Nigeria vs Iceland worldCupGameID["CS-CH"] = 26; // Serbia vs Switzerland gameLocked[24] = 1529668800; gameLocked[25] = 1529679600; gameLocked[26] = 1529690400; // Saturday 23rd June, 2018 worldCupGameID["BE-TN"] = 27; // Belgium vs Tunisia worldCupGameID["KR-MX"] = 28; // Korea vs Mexico worldCupGameID["DE-SE"] = 29; // Germany vs Sweden gameLocked[27] = 1529755200; gameLocked[28] = 1529766000; gameLocked[29] = 1529776800; // Sunday 24th June, 2018 worldCupGameID["EN-PA"] = 30; // England vs Panama worldCupGameID["JP-SN"] = 31; // Japan vs Senegal worldCupGameID["PL-CO"] = 32; // Poland vs Colombia gameLocked[30] = 1529841600; gameLocked[31] = 1529852400; gameLocked[32] = 1529863200; // Monday 25th June, 2018 worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt worldCupGameID["ES-MA"] = 35; // Spain vs Morocco worldCupGameID["IR-PT"] = 36; // Iran vs Portugal gameLocked[33] = 1529935200; gameLocked[34] = 1529935200; gameLocked[35] = 1529949600; gameLocked[36] = 1529949600; // Tuesday 26th June, 2018 worldCupGameID["AU-PE"] = 37; // Australia vs Peru worldCupGameID["DK-FR"] = 38; // Denmark vs France worldCupGameID["NG-AR"] = 39; // Nigeria vs Argentina worldCupGameID["IS-HR"] = 40; // Iceland vs Croatia gameLocked[37] = 1530021600; gameLocked[38] = 1530021600; gameLocked[39] = 1530036000; gameLocked[40] = 1530036000; // Wednesday 27th June, 2018 worldCupGameID["KR-DE"] = 41; // Korea vs Germany worldCupGameID["MX-SE"] = 42; // Mexico vs Sweden worldCupGameID["CS-BR"] = 43; // Serbia vs Brazil worldCupGameID["CH-CR"] = 44; // Switzerland vs Costa Rica gameLocked[41] = 1530108000; gameLocked[42] = 1530108000; gameLocked[43] = 1530122400; gameLocked[44] = 1530122400; // Thursday 28th June, 2018 worldCupGameID["JP-PL"] = 45; // Japan vs Poland worldCupGameID["SN-CO"] = 46; // Senegal vs Colombia worldCupGameID["PA-TN"] = 47; // Panama vs Tunisia worldCupGameID["EN-BE"] = 48; // England vs Belgium gameLocked[45] = 1530194400; gameLocked[46] = 1530194400; gameLocked[47] = 1530208800; gameLocked[48] = 1530208800; // Second stage games and onwards. The string values for these will be overwritten // as the tournament progresses. This is the order that will be followed for the // purposes of calculating winning streaks, as per the World Cup website. // Round of 16 // Saturday 30th June, 2018 worldCupGameID["1C-2D"] = 49; // 1C vs 2D worldCupGameID["1A-2B"] = 50; // 1A vs 2B gameLocked[49] = 1530367200; gameLocked[50] = 1530381600; // Sunday 1st July, 2018 worldCupGameID["1B-2A"] = 51; // 1B vs 2A worldCupGameID["1D-2C"] = 52; // 1D vs 2C gameLocked[51] = 1530453600; gameLocked[52] = 1530468000; // Monday 2nd July, 2018 worldCupGameID["1E-2F"] = 53; // 1E vs 2F worldCupGameID["1G-2H"] = 54; // 1G vs 2H gameLocked[53] = 1530540000; gameLocked[54] = 1530554400; // Tuesday 3rd July, 2018 worldCupGameID["1F-2E"] = 55; // 1F vs 2E worldCupGameID["1H-2G"] = 56; // 1H vs 2G gameLocked[55] = 1530626400; gameLocked[56] = 1530640800; // Quarter Finals // Friday 6th July, 2018 worldCupGameID["W49-W50"] = 57; // W49 vs W50 worldCupGameID["W53-W54"] = 58; // W53 vs W54 gameLocked[57] = 1530885600; gameLocked[58] = 1530900000; // Saturday 7th July, 2018 worldCupGameID["W55-W56"] = 59; // W55 vs W56 worldCupGameID["W51-W52"] = 60; // W51 vs W52 gameLocked[59] = 1530972000; gameLocked[60] = 1530986400; // Semi Finals // Tuesday 10th July, 2018 worldCupGameID["W57-W58"] = 61; // W57 vs W58 gameLocked[61] = 1531245600; // Wednesday 11th July, 2018 worldCupGameID["W59-W60"] = 62; // W59 vs W60 gameLocked[62] = 1531332000; // Third Place Playoff // Saturday 14th July, 2018 worldCupGameID["L61-L62"] = 63; // L61 vs L62 gameLocked[63] = 1531576800; // Grand Final // Sunday 15th July, 2018 worldCupGameID["W61-W62"] = 64; // W61 vs W62 gameLocked[64] = 1531666800; // Set initial variables. latestGameFinished = 0; } /* PUBLIC-FACING COMPETITION INTERACTIONS */ // Register to participate in the competition. Apart from gas costs from // making predictions and updating your score if necessary, this is the // only Ether you will need to spend throughout the tournament. function register() public payable { address _customerAddress = msg.sender; require( !playerRegistered[_customerAddress] && tx.origin == _customerAddress); // Receive the entry fee tokens. require(BTCTKN.transferFrom(_customerAddress, address(this), entryFee)); registeredPlayers = SafeMath.addint256(registeredPlayers, 1); playerRegistered[_customerAddress] = true; playerGamesScored[_customerAddress] = 0; playerList.push(_customerAddress); require(playerRegistered[_customerAddress]); prizePool = prizePool.add(ninetyPercent); givethPool = givethPool.add(fivePercent); adminPool = adminPool.add(fivePercent); emit Registration(_customerAddress); } // Make a prediction for a game. An example would be makePrediction(1, "DRAW") // if you anticipate a draw in the game between Russia and Saudi Arabia, // or makePrediction(2, "UY") if you expect Uruguay to beat Egypt. // The "DRAW" option becomes invalid after the group stage games have been played. function makePrediction(int8 _gameID, string _prediction) public { address _customerAddress = msg.sender; uint predictionTime = now; require(playerRegistered[_customerAddress] && !gameFinished[_gameID] && predictionTime < gameLocked[_gameID]); // No draws allowed after the qualification stage. if (_gameID > 48 && equalStrings(_prediction, "DRAW")) { revert(); } else { playerPredictions[_customerAddress][_gameID] = _prediction; playerMadePrediction[_customerAddress][_gameID] = true; emit PlayerLoggedPrediction(_customerAddress, _gameID, _prediction); } } // What is the current score of a given tournament participant? function showPlayerScores(address _participant) view public returns (int8[64]) { return playerPointArray[_participant]; } function seekApproval() public returns (bool) { BTCTKN.approve(address(this), entryFee); } // What was the last game ID that has had an official score registered for it? function gameResultsLogged() view public returns (int) { return latestGameFinished; } // Sum up the individual scores throughout the tournament and produce a final result. function calculateScore(address _participant) view public returns (int16) { int16 finalScore = 0; for (int8 i = 0; i < latestGameFinished; i++) { uint j = uint(i); int16 gameScore = playerPointArray[_participant][j]; finalScore = SafeMath.addint16(finalScore, gameScore); } return finalScore; } // How many people are taking part in the tournament? function countParticipants() public view returns (int) { return registeredPlayers; } // Keeping this open for anyone to update anyone else so that at the end of // the tournament we can force a score update for everyone using a script. function updateScore(address _participant) public { int8 lastPlayed = latestGameFinished; require(lastPlayed > 0); // Most recent game scored for this participant. int8 lastScored = playerGamesScored[_participant]; // Most recent game played in the tournament (sets bounds for scoring iteration). mapping (int8 => bool) madePrediction = playerMadePrediction[_participant]; mapping (int8 => string) playerGuesses = playerPredictions[_participant]; for (int8 i = lastScored; i < lastPlayed; i++) { uint j = uint(i); uint k = j.add(1); uint streak = playerStreak[_participant]; emit StartScoring(_participant, k); if (!madePrediction[int8(k)]) { playerPointArray[_participant][j] = 0; playerStreak[_participant] = 0; emit DidNotPredict(_participant, k); } else { string storage playerResult = playerGuesses[int8(k)]; string storage actualResult = gameResult[int8(k)]; bool correctGuess = equalStrings(playerResult, actualResult); emit Comparison(_participant, k, playerResult, actualResult, correctGuess); if (!correctGuess) { // The guess was wrong. playerPointArray[_participant][j] = 0; playerStreak[_participant] = 0; } else { // The guess was right. streak = streak.add(1); playerStreak[_participant] = streak; if (streak >= 5) { // On a long streak - four points. playerPointArray[_participant][j] = 4; } else { if (streak >= 3) { // On a short streak - two points. playerPointArray[_participant][j] = 2; } // Not yet at a streak - standard one point. else { playerPointArray[_participant][j] = 1; } } } } } playerGamesScored[_participant] = lastPlayed; } // Invoke this function to get *everyone* up to date score-wise. // This is probably best used at the end of the tournament, to ensure // that prizes are awarded to the correct addresses. // Note: this is going to be VERY gas-intensive. Use it if you&#39;re desperate // to see how you square up against everyone else if they&#39;re slow to // update their own scores. Alternatively, if there&#39;s just one or two // stragglers, you can just call updateScore for them alone. function updateAllScores() public { uint allPlayers = playerList.length; for (uint i = 0; i < allPlayers; i++) { address _toScore = playerList[i]; emit StartAutoScoring(_toScore); updateScore(_toScore); } } // Which game ID has a player last computed their score up to // using the updateScore function? function playerLastScoredGame(address _player) public view returns (int8) { return playerGamesScored[_player]; } // Is a player registered? function playerIsRegistered(address _player) public view returns (bool) { return playerRegistered[_player]; } // What was the official result of a game? function correctResult(int8 _gameID) public view returns (string) { return gameResult[_gameID]; } // What was the caller&#39;s prediction for a given game? function playerGuess(int8 _gameID) public view returns (string) { return playerPredictions[msg.sender][_gameID]; } // Lets us calculate what a participants score would be if they ran updateScore. // Does NOT perform any state update. function viewScore(address _participant) public view returns (uint) { int8 lastPlayed = latestGameFinished; // Most recent game played in the tournament (sets bounds for scoring iteration). mapping (int8 => bool) madePrediction = playerMadePrediction[_participant]; mapping (int8 => string) playerGuesses = playerPredictions[_participant]; uint internalResult = 0; uint internalStreak = 0; for (int8 i = 0; i < lastPlayed; i++) { uint j = uint(i); uint k = j.add(1); uint streak = internalStreak; if (!madePrediction[int8(k)]) { internalStreak = 0; } else { string storage playerResult = playerGuesses[int8(k)]; string storage actualResult = gameResult[int8(k)]; bool correctGuess = equalStrings(playerResult, actualResult); if (!correctGuess) { internalStreak = 0; } else { // The guess was right. internalStreak++; streak++; if (streak >= 5) { // On a long streak - four points. internalResult += 4; } else { if (streak >= 3) { // On a short streak - two points. internalResult += 2; } // Not yet at a streak - standard one point. else { internalResult += 1; } } } } } return internalResult; } /* ADMINISTRATOR FUNCTIONS FOR COMPETITION MAINTENANCE */ modifier isAdministrator() { address _sender = msg.sender; if (_sender == administrator) { _; } else { revert(); } } function _btcToken(address _tokenContract) private pure returns (bool) { return _tokenContract == BTCTKNADDR; // Returns "true" if this is the 0xBTC Token Contract } // As new fixtures become known through progression or elimination, they&#39;re added here. function addNewGame(string _opponents, int8 _gameID) isAdministrator public { worldCupGameID[_opponents] = _gameID; } // When the result of a game is known, enter the result. function logResult(int8 _gameID, string _winner) isAdministrator public { require((int8(0) < _gameID) && (_gameID <= 64) && _gameID == latestGameFinished + 1); // No draws allowed after the qualification stage. if (_gameID > 48 && equalStrings(_winner, "DRAW")) { revert(); } else { require(!gameFinished[_gameID]); gameFinished [_gameID] = true; gameResult [_gameID] = _winner; latestGameFinished = _gameID; assert(gameFinished[_gameID]); } } // Concludes the tournament and issues the prizes, then self-destructs. function concludeTournament(address _first // 40% Ether. , address _second // 30% Ether. , address _third // 20% Ether. , address _fourth) // 10% Ether. isAdministrator public { // Don&#39;t hand out prizes until the final&#39;s... actually been played. require(gameFinished[64] && playerIsRegistered(_first) && playerIsRegistered(_second) && playerIsRegistered(_third) && playerIsRegistered(_fourth)); // Determine 10% of the prize pool to distribute to winners. uint tenth = prizePool.div(10); // Determine the prize allocations. uint firstPrize = tenth.mul(4); uint secondPrize = tenth.mul(3); uint thirdPrize = tenth.mul(2); // Send the first three prizes. BTCTKN.approve(_first, firstPrize); BTCTKN.transferFrom(address(this), _first, firstPrize); BTCTKN.approve(_second, secondPrize); BTCTKN.transferFrom(address(this), _second, secondPrize); BTCTKN.approve(_third, thirdPrize); BTCTKN.transferFrom(address(this), _third, thirdPrize); // Send the tokens raised to Giveth. BTCTKN.approve(givethAddress, givethPool); BTCTKN.transferFrom(address(this), givethAddress, givethPool); // Send the tokens assigned to developer. BTCTKN.approve(administrator, adminPool); BTCTKN.transferFrom(address(this), administrator, adminPool); // Since there might be rounding errors, fourth place gets everything else. uint fourthPrize = ((prizePool.sub(firstPrize)).sub(secondPrize)).sub(thirdPrize); BTCTKN.approve(_fourth, fourthPrize); BTCTKN.transferFrom(address(this), _fourth, fourthPrize); selfdestruct(administrator); } // The emergency escape hatch in case something has gone wrong. // Given the small amount of individual coins per participant, it would // be far more expensive in gas than what&#39;s sent back if required. // You&#39;re going to have to take it on trust that I (the dev, duh), will // sort out refunds. Let&#39;s pray to Suarez it doesn&#39;t need pulling. function pullRipCord() isAdministrator public { uint totalPool = (prizePool.add(givethPool)).add(adminPool); BTCTKN.approve(administrator, totalPool); BTCTKN.transferFrom(address(this), administrator, totalPool); selfdestruct(administrator); } /* INTERNAL FUNCTIONS */ // Gateway check - did you send exactly the right amount? function _isCorrectBuyin(uint _buyin) private pure returns (bool) { return _buyin == entryFee; } // Internal comparison between strings, returning 0 if equal, 1 otherwise. function compare(string _a, string _b) private pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// Compares two strings and returns true if and only if they are equal. function equalStrings(string _a, string _b) pure private returns (bool) { return compare(_a, _b) == 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold 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) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function addint16(int16 a, int16 b) internal pure returns (int16) { int16 c = a + b; assert(c >= a); return c; } function addint256(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert(c >= a); return c; } }
Internal comparison between strings, returning 0 if equal, 1 otherwise.
function compare(string _a, string _b) private pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; }
7,826,965
[ 1, 3061, 5826, 3086, 2064, 16, 5785, 374, 309, 3959, 16, 404, 3541, 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 ]
[ 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, 3400, 12, 1080, 389, 69, 16, 533, 389, 70, 13, 203, 3639, 3238, 203, 3639, 16618, 203, 3639, 1135, 261, 474, 13, 203, 565, 288, 203, 3639, 1731, 3778, 279, 273, 1731, 24899, 69, 1769, 203, 3639, 1731, 3778, 324, 273, 1731, 24899, 70, 1769, 203, 3639, 2254, 21552, 273, 279, 18, 2469, 31, 203, 3639, 309, 261, 70, 18, 2469, 411, 21552, 13, 21552, 273, 324, 18, 2469, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 21552, 31, 277, 965, 13, 203, 5411, 309, 261, 69, 63, 77, 65, 411, 324, 63, 77, 5717, 203, 7734, 327, 300, 21, 31, 203, 5411, 469, 309, 261, 69, 63, 77, 65, 405, 324, 63, 77, 5717, 203, 7734, 327, 404, 31, 203, 3639, 309, 261, 69, 18, 2469, 411, 324, 18, 2469, 13, 203, 5411, 327, 300, 21, 31, 203, 3639, 469, 309, 261, 69, 18, 2469, 405, 324, 18, 2469, 13, 203, 5411, 327, 404, 31, 203, 3639, 469, 203, 5411, 327, 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 ]
./full_match/1/0x60BC206FA39D70AE7ACFe50ef021D1A7dD80c010/sources/contracts/Market.sol
check pear token allowance and balance
checkPearTokenBalance(msg.sender);
2,963,868
[ 1, 1893, 293, 2091, 1147, 1699, 1359, 471, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 866, 52, 2091, 1345, 13937, 12, 3576, 18, 15330, 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, -100 ]
pragma solidity ^0.4.22; // File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/Marketplace.sol // Note about numbers: // All prices and exchange rates are in "decimal fixed-point", that is, scaled by 10^18, like ETH vs wei. // Seconds are integers as usual. contract Marketplace is Ownable { using SafeMath for uint256; // product events event ProductCreated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductUpdated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductDeleted(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductRedeployed(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductOwnershipOffered(address indexed owner, bytes32 indexed id, address indexed to); event ProductOwnershipChanged(address indexed newOwner, bytes32 indexed id, address indexed oldOwner); // subscription events event Subscribed(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event NewSubscription(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionExtended(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionTransferred(bytes32 indexed productId, address indexed from, address indexed to, uint secondsTransferred); // currency events event ExchangeRatesUpdated(uint timestamp, uint dataInUsd); enum ProductState { NotDeployed, // non-existent or deleted Deployed // created or redeployed } enum Currency { DATA, // "token wei" (10^-18 DATA) USD // attodollars (10^-18 USD) } struct Product { bytes32 id; string name; address owner; address beneficiary; // account where revenue is directed to uint pricePerSecond; Currency priceCurrency; uint minimumSubscriptionSeconds; ProductState state; mapping(address => TimeBasedSubscription) subscriptions; address newOwnerCandidate; // Two phase hand-over to minimize the chance that the product ownership is lost to a non-existent address. } struct TimeBasedSubscription { uint endTimestamp; } /////////////// Marketplace lifecycle ///////////////// ERC20 public datacoin; address public currencyUpdateAgent; function Marketplace(address datacoinAddress, address currencyUpdateAgentAddress) Ownable() public { _initialize(datacoinAddress, currencyUpdateAgentAddress); } function _initialize(address datacoinAddress, address currencyUpdateAgentAddress) internal { currencyUpdateAgent = currencyUpdateAgentAddress; datacoin = ERC20(datacoinAddress); } ////////////////// Product management ///////////////// mapping (bytes32 => Product) public products; function getProduct(bytes32 id) public view returns (string name, address owner, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, ProductState state) { return ( products[id].name, products[id].owner, products[id].beneficiary, products[id].pricePerSecond, products[id].priceCurrency, products[id].minimumSubscriptionSeconds, products[id].state ); } // also checks that p exists: p.owner == 0 for non-existent products modifier onlyProductOwner(bytes32 productId) { Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.owner == msg.sender || owner == msg.sender, "error_productOwnersOnly"); _; } function createProduct(bytes32 id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public whenNotHalted { require(id != 0x0, "error_nullProductId"); require(pricePerSecond > 0, "error_freeProductsNotSupported"); Product storage p = products[id]; require(p.id == 0x0, "error_alreadyExists"); products[id] = Product(id, name, msg.sender, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, ProductState.Deployed, 0); emit ProductCreated(msg.sender, id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); } /** * Stop offering the product */ function deleteProduct(bytes32 productId) public onlyProductOwner(productId) { Product storage p = products[productId]; require(p.state == ProductState.Deployed, "error_notDeployed"); p.state = ProductState.NotDeployed; emit ProductDeleted(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } /** * Return product to market */ function redeployProduct(bytes32 productId) public onlyProductOwner(productId) { Product storage p = products[productId]; require(p.state == ProductState.NotDeployed, "error_mustBeNotDeployed"); p.state = ProductState.Deployed; emit ProductRedeployed(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } function updateProduct(bytes32 productId, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public onlyProductOwner(productId) { require(pricePerSecond > 0, "error_freeProductsNotSupported"); Product storage p = products[productId]; p.name = name; p.beneficiary = beneficiary; p.pricePerSecond = pricePerSecond; p.priceCurrency = currency; p.minimumSubscriptionSeconds = minimumSubscriptionSeconds; emit ProductUpdated(p.owner, p.id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); } /** * Changes ownership of the product. Two phase hand-over minimizes the chance that the product ownership is lost to a non-existent address. */ function offerProductOwnership(bytes32 productId, address newOwnerCandidate) public onlyProductOwner(productId) { // that productId exists is already checked in onlyProductOwner products[productId].newOwnerCandidate = newOwnerCandidate; emit ProductOwnershipOffered(products[productId].owner, productId, newOwnerCandidate); } /** * Changes ownership of the product. Two phase hand-over minimizes the chance that the product ownership is lost to a non-existent address. */ function claimProductOwnership(bytes32 productId) public whenNotHalted { // also checks that productId exists (newOwnerCandidate is zero for non-existent) Product storage p = products[productId]; require(msg.sender == p.newOwnerCandidate, "error_notPermitted"); emit ProductOwnershipChanged(msg.sender, productId, p.owner); p.owner = msg.sender; p.newOwnerCandidate = 0; } /////////////// Subscription management /////////////// function getSubscription(bytes32 productId, address subscriber) public view returns (bool isValid, uint endTimestamp) { TimeBasedSubscription storage sub; (isValid, , sub) = _getSubscription(productId, subscriber); endTimestamp = sub.endTimestamp; } function getSubscriptionTo(bytes32 productId) public view returns (bool isValid, uint endTimestamp) { return getSubscription(productId, msg.sender); } /** * Purchases access to this stream for msg.sender. * If the address already has a valid subscription, extends the subscription by the given period. */ function buy(bytes32 productId, uint subscriptionSeconds) public whenNotHalted { var (, product, sub) = _getSubscription(productId, msg.sender); require(product.state == ProductState.Deployed, "error_notDeployed"); _addSubscription(product, msg.sender, subscriptionSeconds, sub); uint price = getPriceInData(subscriptionSeconds, product.pricePerSecond, product.priceCurrency); require(datacoin.transferFrom(msg.sender, product.beneficiary, price), "error_paymentFailed"); } /** * Checks if the given address currently has a valid subscription */ function hasValidSubscription(bytes32 productId, address subscriber) public constant returns (bool isValid) { (isValid, ,) = _getSubscription(productId, subscriber); } /** * Transfer a valid subscription from msg.sender to a new address. * If the address already has a valid subscription, extends the subscription by the msg.sender's remaining period. */ function transferSubscription(bytes32 productId, address newSubscriber) public whenNotHalted { var (isValid, product, sub) = _getSubscription(productId, msg.sender); require(isValid, "error_subscriptionNotValid"); uint secondsLeft = sub.endTimestamp.sub(block.timestamp); TimeBasedSubscription storage newSub = product.subscriptions[newSubscriber]; _addSubscription(product, newSubscriber, secondsLeft, newSub); delete product.subscriptions[msg.sender]; emit SubscriptionTransferred(productId, msg.sender, newSubscriber, secondsLeft); } function _getSubscription(bytes32 productId, address subscriber) internal constant returns (bool subIsValid, Product storage, TimeBasedSubscription storage) { Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); TimeBasedSubscription storage s = p.subscriptions[subscriber]; return (s.endTimestamp >= block.timestamp, p, s); } function _addSubscription(Product storage p, address subscriber, uint addSeconds, TimeBasedSubscription storage oldSub) internal { uint endTimestamp; if (oldSub.endTimestamp > block.timestamp) { require(addSeconds > 0, "error_topUpTooSmall"); endTimestamp = oldSub.endTimestamp.add(addSeconds); oldSub.endTimestamp = endTimestamp; emit SubscriptionExtended(p.id, subscriber, endTimestamp); } else { require(addSeconds >= p.minimumSubscriptionSeconds, "error_newSubscriptionTooSmall"); endTimestamp = block.timestamp.add(addSeconds); TimeBasedSubscription memory newSub = TimeBasedSubscription(endTimestamp); p.subscriptions[subscriber] = newSub; emit NewSubscription(p.id, subscriber, endTimestamp); } emit Subscribed(p.id, subscriber, endTimestamp); } // TODO: transfer allowance to another Marketplace contract // Mechanism basically is that this Marketplace draws from the allowance and credits // the account on another Marketplace; OR that there is a central credit pool (say, an ERC20 token) // Creating another ERC20 token for this could be a simple fix: it would need the ability to transfer allowances /////////////// Currency management /////////////// // Exchange rates are formatted as "decimal fixed-point", that is, scaled by 10^18, like ether. // Exponent: 10^18 15 12 9 6 3 0 // | | | | | | | uint public dataPerUsd = 100000000000000000; // ~= 0.1 DATA/USD /** * Update currency exchange rates; all purchases are still billed in DATAcoin * @param timestamp in seconds when the exchange rates were last updated * @param dataUsd how many data atoms (10^-18 DATA) equal one USD dollar */ function updateExchangeRates(uint timestamp, uint dataUsd) public { require(msg.sender == currencyUpdateAgent, "error_notPermitted"); require(dataUsd > 0); dataPerUsd = dataUsd; emit ExchangeRatesUpdated(timestamp, dataUsd); } /** * Helper function to calculate (hypothetical) subscription cost for given seconds and price, using current exchange rates. * @param subscriptionSeconds length of hypothetical subscription, as a non-scaled integer * @param price nominal price scaled by 10^18 ("token wei" or "attodollars") * @param unit unit of the number price */ function getPriceInData(uint subscriptionSeconds, uint price, Currency unit) public view returns (uint datacoinAmount) { if (unit == Currency.DATA) { return price.mul(subscriptionSeconds); } return price.mul(dataPerUsd).div(10**18).mul(subscriptionSeconds); } /////////////// Admin functionality /////////////// event Halted(); event Resumed(); bool public halted = false; modifier whenNotHalted() { require(!halted || owner == msg.sender, "error_halted"); _; } function halt() public onlyOwner { halted = true; emit Halted(); } function resume() public onlyOwner { halted = false; emit Resumed(); } function reInitialize(address datacoinAddress, address currencyUpdateAgentAddress) public onlyOwner { _initialize(datacoinAddress, currencyUpdateAgentAddress); } }
* Checks if the given address currently has a valid subscription/
function hasValidSubscription(bytes32 productId, address subscriber) public constant returns (bool isValid) { (isValid, ,) = _getSubscription(productId, subscriber); }
11,970,119
[ 1, 4081, 309, 326, 864, 1758, 4551, 711, 279, 923, 4915, 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 ]
[ 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, 711, 1556, 6663, 12, 3890, 1578, 23820, 16, 1758, 9467, 13, 1071, 5381, 1135, 261, 6430, 4908, 13, 288, 203, 3639, 261, 26810, 16, 269, 13, 273, 389, 588, 6663, 12, 5896, 548, 16, 9467, 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 ]
./partial_match/8453/0x3d3c9B6a4A0c393287451054ffdF0dDe8c670C07/sources/BasedSniper.sol
* @dev Wrappers over Solidity's arithmetic operations. NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler now has built in overflow checking./
library SafeMath { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
16,777,791
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 18, 5219, 30, 1375, 9890, 10477, 68, 353, 19190, 486, 3577, 5023, 598, 348, 7953, 560, 374, 18, 28, 16, 3241, 326, 5274, 2037, 711, 6650, 316, 9391, 6728, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 14060, 10477, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 276, 1769, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 276, 1769, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 775, 1676, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 2 ]
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/EIP712Whitelisting.sol //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.7; contract EIP712Whitelisting is Ownable { using ECDSA for bytes32; address whitelistSigningKey = address(0); bytes32 public PREMIUM_DOMAIN; bytes32 public VIP_DOMAIN; bytes32 public DISCOUNT_DOMAIN; bytes32 public PROMO_DOMAIN; bytes32 public FREE_DOMAIN; bytes32 public constant MINTER_TYPEHASH = keccak256("Minter(address wallet)"); bytes32 public constant DOMAIN_HEADER = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bool public redemptionActive; enum MintType {PREMIUM, VIP, DISCOUNT, RESERVED, PROMO, FREE} constructor() { PREMIUM_DOMAIN = setDomain("PREMIUM", "1"); VIP_DOMAIN = setDomain("VIP", "1"); DISCOUNT_DOMAIN = setDomain("DISCOUNT", "1"); PROMO_DOMAIN = setDomain("PROMO", "1"); FREE_DOMAIN = setDomain("FREE", "1"); redemptionActive = false; } function setDomain(string memory _name, string memory _version) internal view returns (bytes32) { return keccak256( abi.encode( DOMAIN_HEADER, keccak256(bytes(_name)), keccak256(bytes(_version)), block.chainid, address(this) ) ); } function setSigningAddress(address newSigningKey) public onlyOwner { whitelistSigningKey = newSigningKey; setRedemptionActive(true); } function setRedemptionActive(bool _redemptionState) public onlyOwner { require(whitelistSigningKey != address(0), "SIGNING KEY NOT SET"); redemptionActive = _redemptionState; } modifier requiresSignature(bytes calldata _signature, MintType _mintType) { require(whitelistSigningKey != address(0), "SIGNING KEY NOT SET"); bytes32 domain; if (_mintType == MintType.FREE || _mintType == MintType.PROMO) { require(redemptionActive, "REDEMPTIONS ARE NOT ACTIVE"); } if (_mintType == MintType.FREE) { domain = FREE_DOMAIN; } else if (_mintType == MintType.PROMO) { domain = PROMO_DOMAIN; } else if (_mintType == MintType.VIP) { domain = VIP_DOMAIN; } else if (_mintType == MintType.DISCOUNT) { domain = DISCOUNT_DOMAIN; } else { domain = PREMIUM_DOMAIN; } bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domain, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender)))); address recoveredAddress = digest.recover(_signature); require(recoveredAddress == whitelistSigningKey, "INVALID SIGNATURE"); _; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "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); _afterTokenTransfer(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); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/CreekMembership.sol // Amended by CREEK pragma solidity ^0.8.7; contract CreekMembership is ERC721, ReentrancyGuard, Ownable, EIP712Whitelisting { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private premiumIssued; Counters.Counter private vipIssued; Counters.Counter private reservedIssued; Counters.Counter private promoIssued; Counters.Counter private freeIssued; string public uriPrefix; string public uriSuffix; string public contractURI; // Contract Creation uint256 public immutable createdOn; // Supply Limits uint256 public constant totalSupply = 110; uint256 public constant MAX_PREMIUM_SUPPLY = 100; uint256 public constant MAX_VIP_SUPPLY = 10; uint256 public maxReservedSupply = 10; uint256 public maxFreeSupply = 15; uint256 public maxPromoSupply = 10; // Pricing uint256 public premiumCost = 0.02 ether; uint256 public vipCost = 0.5 ether; uint256 public discountCost = 0.015 ether; // Max Per Wallet uint256 public maxPremiumPerWallet = 3; uint256 public maxOtherPerWallet = 1; uint256 public immutable giveawaySecs; // Contract Minting State bool public paused = false; bool public giveawayIssued = false; constructor(uint256 _totalGiveawaySeconds) ERC721("CREEK Plus Membership", "CREEKPLUS") EIP712Whitelisting() { uriPrefix = "https://ipfs.creekdrops.io/ipfs/QmdK8GWmEevLjnMSYKaZHGhCAGFn4bk1UjoTHjzjQyh2fB/"; uriSuffix = ".json"; contractURI = "https://creekdrops.io/creek-plus.json/"; createdOn = block.timestamp; giveawaySecs = _totalGiveawaySeconds; } //=======================================// // Set mint price //======================================// function costToMint(uint256 _mintAmount, MintType _mintType) internal view returns (uint256) { if (_mintType == MintType.DISCOUNT) { return discountCost * _mintAmount; } else if (_mintType == MintType.VIP) { return vipCost * _mintAmount; } else if (_mintType == MintType.PREMIUM) { return premiumCost * _mintAmount; } else { return 0; } } //=======================================// // Max assets per wallet //======================================// // Mappings for payable mints mapping(address => uint256) private premiumMintCountMap; mapping(address => uint256) private vipMintCountMap; // Mappings for free mints mapping(address => uint256) private freeMintCountMap; mapping(address => uint256) private promoMintCountMap; mapping(address => uint256) private reservedMintCountMap; // Ensure that user cannot mint more than is allowed per wallet in single TX. function maxPaidPerTx(MintType _mintType) internal view returns (uint256) { if (_mintType == MintType.PREMIUM || _mintType == MintType.DISCOUNT) { return maxPremiumPerWallet; } return maxOtherPerWallet; } // Ensure that user cannot mint more than is allowed per wallet. function allowedMintCount(address _to, MintType _mintType) public view returns (uint256) { uint256 _maxPremium = maxPremiumPerWallet; uint256 _maxOther = maxOtherPerWallet; if (_mintType == MintType.PREMIUM || _mintType == MintType.DISCOUNT) { return _maxPremium - premiumMintCountMap[_to]; } else if (_mintType == MintType.VIP) { return _maxOther - vipMintCountMap[_to]; } else if (_mintType == MintType.PROMO) { return _maxOther - promoMintCountMap[_to]; } else if (_mintType == MintType.RESERVED) { return _maxOther - reservedMintCountMap[_to]; } return _maxOther - freeMintCountMap[_to]; } function supplyIssued(MintType _mintType) external view returns (uint256) { if (_mintType == MintType.VIP) { return vipIssued.current(); } else if (_mintType == MintType.RESERVED) { return reservedIssued.current(); } else if (_mintType == MintType.FREE) { return freeIssued.current(); } else if (_mintType == MintType.PROMO) { return promoIssued.current(); } else if (_mintType == MintType.PREMIUM) { return premiumIssued.current(); } else { return 0; } } function availableSupply(MintType _mintType) public view returns (uint256) { if (_mintType == MintType.VIP) { return MAX_VIP_SUPPLY - vipIssued.current(); } else if (_mintType == MintType.RESERVED) { return maxReservedSupply - reservedIssued.current(); } else if (_mintType == MintType.FREE) { return maxFreeSupply - freeIssued.current(); } else if (_mintType == MintType.PROMO) { return maxPromoSupply - promoIssued.current(); } return MAX_PREMIUM_SUPPLY - maxReservedSupply - maxFreeSupply - maxPromoSupply - premiumIssued.current(); } //=======================================// // Mint Functions //======================================// function incrementMint(address _to, MintType _mintType) private { if (_mintType == MintType.PREMIUM || _mintType == MintType.DISCOUNT) { premiumIssued.increment(); premiumMintCountMap[_to] += 1; } else if (_mintType == MintType.VIP) { vipIssued.increment(); vipMintCountMap[_to] += 1; } else if (_mintType == MintType.PROMO) { promoIssued.increment(); promoMintCountMap[_to] += 1; premiumMintCountMap[_to] += 1; } else if (_mintType == MintType.FREE) { freeIssued.increment(); freeMintCountMap[_to] += 1; premiumMintCountMap[_to] += 1; } else if (_mintType == MintType.RESERVED) { reservedIssued.increment(); reservedMintCountMap[_to] += 1; premiumMintCountMap[_to] += 1; } } function currentMintId(MintType _mintType) internal view returns (uint256) { if (_mintType == MintType.VIP) { return MAX_PREMIUM_SUPPLY + vipIssued.current(); } return premiumIssued.current() + promoIssued.current() + freeIssued.current() + reservedIssued.current(); } function _mintLoop( address _to, uint256 _mintAmount, MintType _mintType ) internal { for (uint256 i = 0; i < _mintAmount; i++) { incrementMint(_to, _mintType); _safeMint(_to, currentMintId(_mintType)); } } function isHolder(address _owner, MintType _mintType) external view returns (bool) { uint256 id; uint256 max; if (_mintType == MintType.PREMIUM) { id = 1; max = 100; } else if (_mintType == MintType.VIP) { id = 101; max = 110; } else { revert("INVALID MINT TYPE"); } while (id <= max) { if (ownerOf(id) == _owner) { return true; } else { id++; } } return false; } function mintToAddress(address _to) public onlyOwner { require(allowedMintCount(_to, MintType.RESERVED) > 0, "MINT LIMIT REACHED"); require(availableSupply(MintType.RESERVED) > 0, "NONE AVAILABLE"); _mintLoop(_to, 1, MintType.RESERVED); } function mint( uint256 _mintAmount, MintType _mintType, bytes calldata signature ) public payable requiresSignature(signature, _mintType) nonReentrant { require(!paused, "CONTRACT IS PAUSED"); require(_mintAmount <= maxPaidPerTx(_mintType), "EXCEEDS PER TX LIMIT"); require(allowedMintCount(msg.sender, _mintType) >= _mintAmount, "MINT LIMIT REACHED"); require(availableSupply(_mintType) >= _mintAmount, "NOT ENOUGH AVAILABLE"); require(tx.origin == msg.sender, "CUSTOM CONTRACT MINTING NOT ALLOWED"); require(msg.value >= costToMint(_mintAmount, _mintType), "INSUFFICIENT FUNDS"); _mintLoop(msg.sender, _mintAmount, _mintType); } //=======================================// /** URI Functions **/ //======================================// function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } //=======================================// /** UPDATE CONTRACT **/ //======================================// function setCost(MintType _mintType, uint256 _cost) external onlyOwner { require( _mintType == MintType.PREMIUM || _mintType == MintType.VIP || _mintType == MintType.DISCOUNT, "Invalid mint type" ); if (_mintType == MintType.PREMIUM) { premiumCost = _cost; } else if (_mintType == MintType.VIP) { vipCost = _cost; } else { discountCost = _cost; } } function setMaxPerWallet(MintType _mintType, uint256 _max) external onlyOwner { _mintType == MintType.PREMIUM ? maxPremiumPerWallet = _max : maxOtherPerWallet = _max; } function setUriPrefix(string memory _uriPrefix) external onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) external onlyOwner { uriSuffix = _uriSuffix; } function setContractUri(string memory _uri) external onlyOwner { contractURI = _uri; } function togglePaused() external onlyOwner { paused = !paused; } function disableRedemption() external onlyOwner { setRedemptionActive(false); maxPromoSupply = promoIssued.current(); maxFreeSupply = freeIssued.current(); } // Will transfer 10% of the initial sale revenue to a single token holder function gibs(uint256 _tokenId) public onlyOwner { require( block.timestamp >= createdOn + giveawaySecs || (availableSupply(MintType.VIP) == 0 && availableSupply(MintType.PREMIUM) == 0), "CANNOT BE CALLED YET" ); address winrar = ownerOf(_tokenId); (bool _winrar, ) = payable(winrar).call{value: (address(this).balance * 10) / 100}(""); giveawayIssued = true; require(_winrar); } // Withdraws the remaining balance to the owners address. function withdraw() public onlyOwner { require(giveawayIssued, "ISSUE GIVEAWAY FIRST"); (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
======================================= Set mint price======================================
function costToMint(uint256 _mintAmount, MintType _mintType) internal view returns (uint256) { if (_mintType == MintType.DISCOUNT) { return discountCost * _mintAmount; return vipCost * _mintAmount; return premiumCost * _mintAmount; return 0; } } mapping(address => uint256) private vipMintCountMap; mapping(address => uint256) private promoMintCountMap; mapping(address => uint256) private reservedMintCountMap;
5,744,387
[ 1, 4428, 894, 12275, 225, 1000, 312, 474, 6205, 4428, 894, 631, 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, 225, 445, 6991, 774, 49, 474, 12, 11890, 5034, 389, 81, 474, 6275, 16, 490, 474, 559, 389, 81, 474, 559, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 67, 81, 474, 559, 422, 490, 474, 559, 18, 2565, 16224, 5321, 13, 288, 203, 1377, 327, 12137, 8018, 380, 389, 81, 474, 6275, 31, 203, 1377, 327, 26180, 8018, 380, 389, 81, 474, 6275, 31, 203, 1377, 327, 23020, 5077, 8018, 380, 389, 81, 474, 6275, 31, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 225, 289, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 26180, 49, 474, 1380, 863, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 3012, 83, 49, 474, 1380, 863, 31, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 8735, 49, 474, 1380, 863, 31, 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 ]
./partial_match/42/0x4ffADC639B57e864150ff98a55D249fed53fa63B/sources/ZuniBadge.sol
To the extent possible, modify state variables before calling functions
_mintPoolShare(initialSupply);
3,449,046
[ 1, 774, 326, 11933, 3323, 16, 5612, 919, 3152, 1865, 4440, 4186, 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, 3639, 389, 81, 474, 2864, 9535, 12, 6769, 3088, 1283, 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, -100 ]
./full_match/1/0x96AdA1cd013b5A28548A5F8B8698f029A8DA30a2/sources/ShibWalletStaking.sol
staked token amount
uint256 stakedAmount;
8,367,954
[ 1, 334, 9477, 1147, 3844, 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, 2254, 5034, 384, 9477, 6275, 31, 6647, 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 ]