file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "./ITokenageERC721PermitUpgradeable.sol"; /** * @dev Implementation of the ERC721 Permit extension allowing approvals to be made via signatures. * * Adds the {permit} method, which can be used to change an account's ERC721 allowance by * presenting a message signed by the account. By not relying on `{IERC721-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * This implementation was inspired by openzeppelin's ERC20PermitUpgradeable. * This implementation will likely be deprecated after the official implementation is released by openzeppelin. * Make sure to implement your smart contracts accordingly to be able to upgrade it properly. */ abstract contract TokenageERC721PermitUpgradeable is Initializable, ERC721Upgradeable, ITokenageERC721PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC721 token name. */ // solhint-disable-next-line func-name-mixedcase function __TokenageERC721Permit_init(string memory name) internal onlyInitializing { __EIP712_init_unchained(name, "1"); __TokenageERC721Permit_init_unchained(); } // solhint-disable-next-line func-name-mixedcase function __TokenageERC721Permit_init_unchained() internal onlyInitializing { _PERMIT_TYPEHASH = keccak256( "TokenagePermitERC721(address >From,address >To,uint256 >Token ID,uint256 >Nonce,uint256 >Deadline)" ); } /** * @dev See {IERC721Permit-permit}. */ function permit( address owner, address spender, uint256 tokenId, uint256 deadline, bytes memory signature ) public virtual override { require( block.timestamp <= deadline, "TokenageERC721Permit: expired deadline" ); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, tokenId, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, signature); require(signer == owner, "TokenageERC721Permit: invalid signature"); _approve(spender, tokenId); } /** * @dev See {IERC721Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC721Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
solhint-disable-next-line func-name-mixedcase
function __TokenageERC721Permit_init_unchained() internal onlyInitializing { _PERMIT_TYPEHASH = keccak256( "TokenagePermitERC721(address >From,address >To,uint256 >Token ID,uint256 >Nonce,uint256 >Deadline)" ); }
15,834,004
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 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, 1001, 1345, 410, 654, 39, 27, 5340, 9123, 305, 67, 2738, 67, 4384, 8707, 1435, 2713, 1338, 29782, 288, 203, 3639, 389, 3194, 6068, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 203, 5411, 315, 1345, 410, 9123, 305, 654, 39, 27, 5340, 12, 2867, 405, 1265, 16, 2867, 405, 774, 16, 11890, 5034, 405, 1345, 1599, 16, 11890, 5034, 405, 13611, 16, 11890, 5034, 405, 15839, 2225, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/13337/0xa5e2C4E3f7B3CB1EbEd7Aa7D7315aB49Dc61db26/sources/project:/contracts/photon/ScheduledVestingContract.sol
VestingSchedule[] memory _schedules = new VestingSchedule[](amount.length); allow initial allocation to be withdrawn immediately
constructor(address owner, address tokenAddress, uint256 startTime, uint192[] memory amount, uint32[] memory startMonths, uint32[] memory endMonths) { token = IERC20(tokenAddress); for (uint256 i = 0; i < amount.length; i++) { uint32 start = uint32(startTime + startMonths[i] * 2630160); uint32 end = uint32(startTime + endMonths[i] * 2630160); if (startMonths[i] == 0 && endMonths[i] == 0) { start = 0; end = 0; } schedules.push(VestingSchedule(amount[i], start, end)); } }
13,235,990
[ 1, 58, 10100, 6061, 8526, 3778, 389, 87, 15511, 273, 394, 776, 10100, 6061, 8526, 12, 8949, 18, 2469, 1769, 1699, 2172, 13481, 358, 506, 598, 9446, 82, 7636, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 3410, 16, 1758, 1147, 1887, 16, 2254, 5034, 8657, 16, 2254, 15561, 8526, 3778, 3844, 16, 2254, 1578, 8526, 3778, 787, 19749, 16, 2254, 1578, 8526, 3778, 679, 19749, 13, 288, 203, 3639, 1147, 273, 467, 654, 39, 3462, 12, 2316, 1887, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3844, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 1578, 787, 273, 2254, 1578, 12, 1937, 950, 397, 787, 19749, 63, 77, 65, 380, 576, 4449, 1611, 4848, 1769, 203, 5411, 2254, 1578, 679, 273, 2254, 1578, 12, 1937, 950, 397, 679, 19749, 63, 77, 65, 380, 576, 4449, 1611, 4848, 1769, 203, 5411, 309, 261, 1937, 19749, 63, 77, 65, 422, 374, 597, 679, 19749, 63, 77, 65, 422, 374, 13, 288, 203, 7734, 787, 273, 374, 31, 203, 7734, 679, 273, 374, 31, 203, 5411, 289, 203, 5411, 26720, 18, 6206, 12, 58, 10100, 6061, 12, 8949, 63, 77, 6487, 787, 16, 679, 10019, 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 ]
./full_match/42/0x9748461D4f94D04637F8995c0bE9B82530a90280/sources/contracts/FundMe.sol
require(getConversionRate(msg.value) >= minimumUsd, "You needs spends more ETH!"); Map the address calling this function with the amount of ether they sent
function fund() public payable { uint256 minimumUsd = 50 * 10 ** 18; }
16,234,298
[ 1, 6528, 12, 588, 6814, 4727, 12, 3576, 18, 1132, 13, 1545, 5224, 3477, 72, 16, 315, 6225, 4260, 17571, 87, 1898, 512, 2455, 4442, 1769, 1635, 326, 1758, 4440, 333, 445, 598, 326, 3844, 434, 225, 2437, 2898, 3271, 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, 284, 1074, 1435, 1071, 8843, 429, 225, 288, 203, 540, 203, 3639, 2254, 5034, 5224, 3477, 72, 273, 6437, 380, 1728, 2826, 6549, 31, 203, 540, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; pragma experimental "v0.5.0"; /* Copyright 2018 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // 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) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#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/introspection/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); } // File: openzeppelin-solidity/contracts/token/ERC721/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(&#39;balanceOf(address)&#39;)) ^ * bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ * bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ * bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ * bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ * bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256(&#39;exists(uint256)&#39;)) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256(&#39;totalSupply()&#39;)) ^ * bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256(&#39;name()&#39;)) ^ * bytes4(keccak256(&#39;symbol()&#39;)) ^ * bytes4(keccak256(&#39;tokenURI(uint256)&#39;)) */ 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; } // File: openzeppelin-solidity/contracts/token/ERC721/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 { } // File: openzeppelin-solidity/contracts/token/ERC721/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); } // File: openzeppelin-solidity/contracts/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; } } // File: openzeppelin-solidity/contracts/introspection/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(&#39;supportsInterface(bytes4)&#39;)) */ /** * @dev a mapping of interface id to whether or not it&#39;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; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a >= _b ? _a : _b; } function min64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a < _b ? _a : _b; } function max256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a >= _b ? _a : _b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // 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 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; } } // File: contracts/lib/AccessControlledBase.sol /** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } } // File: contracts/lib/StaticAccessControlled.sol /** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } } // File: contracts/lib/GeneralERC20.sol /** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; } // File: contracts/lib/TokenInteract.sol /** * @title TokenInteract * @author dYdX * * This library contains functions for interacting with ERC20 tokens */ library TokenInteract { function balanceOf( address token, address owner ) internal view returns (uint256) { return GeneralERC20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return GeneralERC20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { GeneralERC20(token).approve(spender, amount); require( checkSuccess(), "TokenInteract#approve: Approval failed" ); } function transfer( address token, address to, uint256 amount ) internal { address from = address(this); if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transfer(to, amount); require( checkSuccess(), "TokenInteract#transfer: Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transferFrom(from, to, amount); require( checkSuccess(), "TokenInteract#transferFrom: TransferFrom failed" ); } // ============ Private Helper-Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } } // File: contracts/margin/TokenProxy.sol /** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } } // File: contracts/margin/Vault.sol /** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract&#39;s address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } } // File: contracts/lib/Fraction.sol /** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } } // File: contracts/lib/FractionMath.sol /** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256&#39;s. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } } // File: contracts/lib/Exponent.sol /** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } } // File: contracts/lib/MathHelpers.sol /** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } } // File: contracts/margin/impl/InterestImpl.sol /** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } } // File: contracts/margin/impl/MarginState.sol /** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } } // File: contracts/margin/interfaces/lender/LoanOwner.sol /** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/PositionOwner.sol /** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/TransferInternal.sol /** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } } // File: contracts/lib/TimestampHelper.sol /** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } } // File: contracts/margin/impl/MarginCommon.sol /** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } } // File: contracts/margin/interfaces/PayoutRecipient.sol /** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); } // File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol /** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol /** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/impl/ClosePositionShared.sol /** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } } // File: contracts/margin/interfaces/ExchangeWrapper.sol /** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); } // File: contracts/margin/impl/ClosePositionImpl.sol /** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } } // File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol /** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } } // File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol /** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/DepositCollateralImpl.sol /** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } } // File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol /** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/ForceRecoverCollateralImpl.sol /* solium-disable-next-line max-len*/ /** * @title ForceRecoverCollateralImpl * @author dYdX * * This library contains the implementation for the forceRecoverCollateral function of Margin */ library ForceRecoverCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); // ============ Public Implementation Functions ============ function forceRecoverCollateralImpl( MarginState.State storage state, bytes32 positionId, address recipient ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Can only force recover after either: // 1) The loan was called and the call period has elapsed // 2) The maxDuration of the position has elapsed require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" ); // Ensure lender consent forceRecoverCollateralOnBehalfOfRecurse( position.lender, msg.sender, positionId, recipient ); // Send the tokens uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId); Vault(state.VAULT).transferFromVault( positionId, position.heldToken, recipient, heldTokenRecovered ); // Delete the position // NOTE: Since position is a storage pointer, this will also set all fields on // the position variable to 0 MarginCommon.cleanupPosition( state, positionId ); // Log an event emit CollateralForceRecovered( positionId, recipient, heldTokenRecovered ); return heldTokenRecovered; } // ============ Private Helper-Functions ============ function forceRecoverCollateralOnBehalfOfRecurse( address contractAddr, address recoverer, bytes32 positionId, address recipient ) private { // no need to ask for permission if (recoverer == contractAddr) { return; } address newContractAddr = ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf( recoverer, positionId, recipient ); if (newContractAddr != contractAddr) { forceRecoverCollateralOnBehalfOfRecurse( newContractAddr, recoverer, positionId, recipient ); } } } // File: contracts/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/margin/interfaces/LoanOfferingVerifier.sol /** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/BorrowShared.sol /** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender&#39;s owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender&#39;s owedToken and the trader&#39;s deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } } // File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol /** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol /** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/IncreasePositionImpl.sol /** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering&#39;s maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } } // File: contracts/margin/impl/MarginStorage.sol /** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; } // File: contracts/margin/impl/LoanGetters.sol /** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } } // File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol /** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/lender/MarginCallDelegator.sol /** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/LoanImpl.sol /** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/MarginAdmin.sol /** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } } // File: contracts/margin/impl/MarginEvents.sol /** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don&#39;t support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); } // File: contracts/margin/impl/OpenPositionImpl.sol /** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol /** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } } // File: contracts/margin/impl/PositionGetters.sol /** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0&#39;s will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } } // File: contracts/margin/impl/TransferImpl.sol /** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn&#39;t change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn&#39;t change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } } // File: contracts/margin/Margin.sol /** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering&#39;s payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } } // File: contracts/margin/interfaces/OnlyMargin.sol /** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } } // File: contracts/margin/external/interfaces/PositionCustodian.sol /** * @title PositionCustodian * @author dYdX * * Interface to interact with other second-layer contracts. For contracts that own positions as a * proxy for other addresses. */ interface PositionCustodian { /** * Function that is intended to be called by external contracts to see where to pay any fees or * tokens as a result of closing a position on behalf of another contract. * * @param positionId Unique ID of the position * @return Address of the true owner of the position */ function getPositionDeedHolder( bytes32 positionId ) external view returns (address); } // File: contracts/margin/external/ERC721/ERC721MarginPosition.sol /** * @title ERC721MarginPosition * @author dYdX * * Contract used to tokenize positions as ERC721-compliant non-fungible tokens. Holding the * token allows the holder to close the position. Functionality is added to let users approve * other addresses to close their positions for them. */ contract ERC721MarginPosition is ReentrancyGuard, ERC721Token, OnlyMargin, PositionOwner, IncreasePositionDelegator, ClosePositionDelegator, DepositCollateralDelegator, PositionCustodian { using SafeMath for uint256; // ============ Events ============ /** * A token was created by transferring direct position ownership to this contract. */ event PositionTokenized( bytes32 indexed positionId, address indexed owner ); /** * A token was burned from transferring direct position ownership to an address other than * this contract. */ event PositionUntokenized( bytes32 indexed positionId, address indexed owner, address ownershipSentTo ); /** * Closer approval was granted or revoked. */ event CloserApproval( address indexed owner, address indexed approved, bool isApproved ); /** * Recipient approval was granted or revoked. */ event RecipientApproval( address indexed owner, address indexed approved, bool isApproved ); // ============ State Variables ============ // Mapping from an address to other addresses that are approved to be positions closers mapping (address => mapping (address => bool)) public approvedClosers; // Mapping from an address to other addresses that are approved to be payoutRecipients mapping (address => mapping (address => bool)) public approvedRecipients; // ============ Constructor ============ constructor( address margin ) public ERC721Token("dYdX ERC721 Margin Positions", "d/PO") OnlyMargin(margin) {} // ============ Token-Holder functions ============ /** * Approve any close with the specified closer as the msg.sender of the close. * * @param closer Address of the closer * @param isApproved True if approving the closer, false if revoking approval */ function approveCloser( address closer, bool isApproved ) external nonReentrant { // cannot approve self since any address can already close its own positions require( closer != msg.sender, "ERC721MarginPosition#approveCloser: Cannot approve self" ); if (approvedClosers[msg.sender][closer] != isApproved) { approvedClosers[msg.sender][closer] = isApproved; emit CloserApproval(msg.sender, closer, isApproved); } } /** * Approve any close with the specified recipient as the payoutRecipient of the close. * * NOTE: An account approving itself as a recipient is often a very bad idea. A smart contract * that approves itself should implement the PayoutRecipient interface for dYdX to verify that * it is given a fair payout for an external account closing the position. * * @param recipient Address of the recipient * @param isApproved True if approving the recipient, false if revoking approval */ function approveRecipient( address recipient, bool isApproved ) external nonReentrant { if (approvedRecipients[msg.sender][recipient] != isApproved) { approvedRecipients[msg.sender][recipient] = isApproved; emit RecipientApproval(msg.sender, recipient, isApproved); } } /** * Transfer ownership of the position externally to this contract, thereby burning the token * * @param positionId Unique ID of the position * @param to Address to transfer postion ownership to */ function untokenizePosition( bytes32 positionId, address to ) external nonReentrant { uint256 tokenId = uint256(positionId); address owner = ownerOf(tokenId); require( msg.sender == owner, "ERC721MarginPosition#untokenizePosition: Only token owner can call" ); _burn(owner, tokenId); Margin(DYDX_MARGIN).transferPosition(positionId, to); emit PositionUntokenized(positionId, owner, to); } /** * Burn an invalid token. Callable by anyone. Used to burn unecessary tokens for clarity and to * free up storage. Throws if the position is not yet closed. * * @param positionId Unique ID of the position */ function burnClosedToken( bytes32 positionId ) external nonReentrant { burnClosedTokenInternal(positionId); } /** * Burn several invalid tokens. Callable by anyone. Used to burn unecessary tokens for clarity * and to free up storage. Throws if the position is not yet closed. * * @param positionIds Unique IDs of the positions */ function burnClosedTokenMultiple( bytes32[] positionIds ) external nonReentrant { for (uint256 i = 0; i < positionIds.length; i++) { burnClosedTokenInternal(positionIds[i]); } } // ============ OnlyMargin Functions ============ /** * Called by the Margin contract when anyone transfers ownership of a position to this contract. * This function mints a new ERC721 Token and returns this address to * indicate to Margin that it is willing to take ownership of the position. * * @param from Address of previous position owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receivePositionOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant returns (address) { _mint(from, uint256(positionId)); emit PositionTokenized(positionId, from); return address(this); // returning own address retains ownership of position } /** * Called by Margin when additional value is added onto the position this contract * owns. Defer approval to the token holder * * param trader (unused) * @param positionId Unique ID of the position * param principalAdded (unused) * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address /* trader */, bytes32 positionId, uint256 /* principalAdded */ ) external onlyMargin nonReentrant returns (address) { return ownerOfPosition(positionId); } /** * Called by Margin when an owner of this token is attempting to close some of the * position. Implementation is required per PositionOwner contract in order to be used by * Margin to approve closing parts of a position. * * @param closer Address of the caller of the close function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Amount of the position being closed * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external onlyMargin nonReentrant returns (address, uint256) { // Cannot burn the token since the position hasn&#39;t been closed yet and getPositionDeedHolder // must return the owner of the position after it has been closed in the current transaction address owner = ownerOfPosition(positionId); if (approvedClosers[owner][closer] || approvedRecipients[owner][payoutRecipient]) { return (address(this), requestedAmount); } return (owner, requestedAmount); } /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * param depositor (unused) * @param positionId Unique ID of the position * param amount (unused) * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address /* depositor */, bytes32 positionId, uint256 /* amount */ ) external onlyMargin nonReentrant returns (address) { return ownerOfPosition(positionId); } // ============ PositionCustodian Functions ============ function getPositionDeedHolder( bytes32 positionId ) external view returns (address) { return ownerOfPosition(positionId); } // ============ Private Helper-Functions ============ function burnClosedTokenInternal( bytes32 positionId ) private { require( Margin(DYDX_MARGIN).isPositionClosed(positionId), "ERC721MarginPosition#burnClosedTokenInternal: Position is not closed" ); _burn(ownerOfPosition(positionId), uint256(positionId)); } function ownerOfPosition( bytes32 positionId ) private view returns (address) { address owner = ownerOf(uint256(positionId)); // ownerOf() should have already required this assert(owner != address(0)); require( owner != address(this), "ERC721MarginPosition#ownerOfPosition: 721 contract should not own tokens" ); return owner; } }
============ Events ============ ============ State Variables ============ Mapping from an address to other addresses that are approved to be positions closers Mapping from an address to other addresses that are approved to be payoutRecipients ============ Constructor ============ ============ Token-Holder functions ============
{ using SafeMath for uint256; event PositionTokenized( bytes32 indexed positionId, address indexed owner ); event PositionUntokenized( bytes32 indexed positionId, address indexed owner, address ownershipSentTo ); event CloserApproval( address indexed owner, address indexed approved, bool isApproved ); event RecipientApproval( address indexed owner, address indexed approved, bool isApproved ); mapping (address => mapping (address => bool)) public approvedClosers; mapping (address => mapping (address => bool)) public approvedRecipients; constructor( address margin ) public ERC721Token("dYdX ERC721 Margin Positions", "d/PO") OnlyMargin(margin) function approveCloser( address closer, bool isApproved ) external nonReentrant } contract ERC721MarginPosition is {} { require( closer != msg.sender, "ERC721MarginPosition#approveCloser: Cannot approve self" ); if (approvedClosers[msg.sender][closer] != isApproved) { approvedClosers[msg.sender][closer] = isApproved; emit CloserApproval(msg.sender, closer, isApproved); } } { require( closer != msg.sender, "ERC721MarginPosition#approveCloser: Cannot approve self" ); if (approvedClosers[msg.sender][closer] != isApproved) { approvedClosers[msg.sender][closer] = isApproved; emit CloserApproval(msg.sender, closer, isApproved); } } function approveRecipient( address recipient, bool isApproved ) external nonReentrant { if (approvedRecipients[msg.sender][recipient] != isApproved) { approvedRecipients[msg.sender][recipient] = isApproved; emit RecipientApproval(msg.sender, recipient, isApproved); } } function approveRecipient( address recipient, bool isApproved ) external nonReentrant { if (approvedRecipients[msg.sender][recipient] != isApproved) { approvedRecipients[msg.sender][recipient] = isApproved; emit RecipientApproval(msg.sender, recipient, isApproved); } } function untokenizePosition( bytes32 positionId, address to ) external nonReentrant { uint256 tokenId = uint256(positionId); address owner = ownerOf(tokenId); require( msg.sender == owner, "ERC721MarginPosition#untokenizePosition: Only token owner can call" ); _burn(owner, tokenId); Margin(DYDX_MARGIN).transferPosition(positionId, to); emit PositionUntokenized(positionId, owner, to); } function burnClosedToken( bytes32 positionId ) external nonReentrant { burnClosedTokenInternal(positionId); } function burnClosedTokenMultiple( bytes32[] positionIds ) external nonReentrant { for (uint256 i = 0; i < positionIds.length; i++) { burnClosedTokenInternal(positionIds[i]); } } function burnClosedTokenMultiple( bytes32[] positionIds ) external nonReentrant { for (uint256 i = 0; i < positionIds.length; i++) { burnClosedTokenInternal(positionIds[i]); } } function receivePositionOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant returns (address) { _mint(from, uint256(positionId)); emit PositionTokenized(positionId, from); } function increasePositionOnBehalfOf( address /* trader */, bytes32 positionId, uint256 /* principalAdded */ ) external onlyMargin nonReentrant returns (address) { return ownerOfPosition(positionId); } function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external onlyMargin nonReentrant returns (address, uint256) { address owner = ownerOfPosition(positionId); if (approvedClosers[owner][closer] || approvedRecipients[owner][payoutRecipient]) { return (address(this), requestedAmount); } return (owner, requestedAmount); } function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external onlyMargin nonReentrant returns (address, uint256) { address owner = ownerOfPosition(positionId); if (approvedClosers[owner][closer] || approvedRecipients[owner][payoutRecipient]) { return (address(this), requestedAmount); } return (owner, requestedAmount); } function depositCollateralOnBehalfOf( address /* depositor */, bytes32 positionId, uint256 /* amount */ ) external onlyMargin nonReentrant returns (address) { return ownerOfPosition(positionId); } function getPositionDeedHolder( bytes32 positionId ) external view returns (address) { return ownerOfPosition(positionId); } function burnClosedTokenInternal( bytes32 positionId ) private { require( Margin(DYDX_MARGIN).isPositionClosed(positionId), "ERC721MarginPosition#burnClosedTokenInternal: Position is not closed" ); _burn(ownerOfPosition(positionId), uint256(positionId)); } function ownerOfPosition( bytes32 positionId ) private view returns (address) { address owner = ownerOf(uint256(positionId)); assert(owner != address(0)); require( owner != address(this), "ERC721MarginPosition#ownerOfPosition: 721 contract should not own tokens" ); return owner; } }
7,913,269
[ 1, 14468, 9043, 422, 1432, 631, 422, 1432, 631, 3287, 23536, 422, 1432, 631, 9408, 628, 392, 1758, 358, 1308, 6138, 716, 854, 20412, 358, 506, 6865, 1219, 5944, 9408, 628, 392, 1758, 358, 1308, 6138, 716, 854, 20412, 358, 506, 293, 2012, 22740, 422, 1432, 631, 11417, 422, 1432, 631, 422, 1432, 631, 3155, 17, 6064, 4186, 422, 1432, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 871, 11010, 1345, 1235, 12, 203, 3639, 1731, 1578, 8808, 1754, 548, 16, 203, 3639, 1758, 8808, 3410, 203, 565, 11272, 203, 203, 565, 871, 11010, 57, 496, 969, 1235, 12, 203, 3639, 1731, 1578, 8808, 1754, 548, 16, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 23178, 7828, 774, 203, 565, 11272, 203, 203, 565, 871, 22442, 550, 23461, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 20412, 16, 203, 3639, 1426, 353, 31639, 203, 565, 11272, 203, 203, 565, 871, 23550, 23461, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 20412, 16, 203, 3639, 1426, 353, 31639, 203, 565, 11272, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 1426, 3719, 1071, 20412, 4082, 5944, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 1426, 3719, 1071, 20412, 22740, 31, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 7333, 203, 565, 262, 203, 3639, 1071, 203, 3639, 4232, 39, 27, 5340, 1345, 2932, 72, 61, 72, 60, 4232, 39, 27, 5340, 490, 5243, 6818, 5029, 3113, 315, 72, 19, 2419, 7923, 203, 3639, 5098, 9524, 12, 10107, 13, 203, 203, 203, 565, 445, 6617, 537, 10924, 12, 203, 3639, 1758, 13306, 16, 203, 3639, 1426, 353, 31639, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 97, 203, 203, 16351, 4232, 39, 27, 5340, 9524, 2555, 353, 203, 565, 2618, 2 ]
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * Minado - Crypto Token Mining & Forging Community * * Minado has been optimized for mining ERC918-compatible tokens via * the InfinityPool; a public storage of mineable ERC-20 tokens. * * Learn more below: * * Official : https://minado.network * Ethereum : https://eips.ethereum.org/EIPS/eip-918 * Github : https://github.com/ethereum/EIPs/pull/918 * Reddit : https://www.reddit.com/r/Tokenmining * * Version 19.7.18 * * Web : https://d14na.org * Email : [email protected] */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /******************************************************************************* * * InfinityPool Interface */ contract InfinityPoolInterface { function transfer(address _token, address _to, uint _tokens) external returns (bool success); } /******************************************************************************* * * InfinityWell Interface */ contract InfinityWellInterface { function forgeStones(address _owner, uint _tokens) external returns (bool success); function destroyStones(address _owner, uint _tokens) external returns (bool success); function transferERC20(address _token, address _to, uint _tokens) external returns (bool success); function transferERC721(address _token, address _to, uint256 _tokenId) external returns (bool success); } /******************************************************************************* * * Staek(house) Factory Interface */ contract StaekFactoryInterface { function balanceOf(bytes32 _staekhouseId) public view returns (uint balance); function balanceOf(bytes32 _staekhouseId, address _owner) public view returns (uint balance); function getStaekhouse(bytes32 _staekhouseId, address _staeker) external view returns (address factory, address token, address owner, uint ownerLockTime, uint providerLockTime, uint debtLimit, uint lockInterval, uint balance); } /******************************************************************************* * * @notice Minado - Token Mining Contract * * @dev This is a multi-token mining contract, which manages the proof-of-work * verifications before authorizing the movement of tokens from the * InfinityPool and InfinityWell. */ contract Minado is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /** * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * Zer0netDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'minado'; /** * Large Target * * A big number used for difficulty targeting. * * NOTE: Bitcoin uses `2**224`. */ uint private _MAXIMUM_TARGET = 2**234; /** * Minimum Targets * * Minimum number used for difficulty targeting. */ uint private _MINIMUM_TARGET = 2**16; /** * Set basis-point multiplier. * * NOTE: Used for (integer-based) fractional calculations. */ uint private _BP_MUL = 10000; /* Set InfinityStone decimals. */ uint private _STONE_DECIMALS = 18; /* Set single InfinityStone. */ uint private _SINGLE_STONE = 1 * 10**_STONE_DECIMALS; /** * (Ethereum) Blocks Per Forge * * NOTE: Ethereum blocks take approx 15 seconds each. * 1,000 blocks takes approx 4 hours. */ uint private _BLOCKS_PER_STONE_FORGE = 1000; /** * (Ethereum) Blocks Per Generation * * NOTE: We mirror the Bitcoin POW mining algorithm. * We want miners to spend 10 minutes to mine each 'block'. * (about 40 Ethereum blocks for every 1 Bitcoin block) */ uint BLOCKS_PER_GENERATION = 40; // Mainnet & Ropsten // uint BLOCKS_PER_GENERATION = 120; // Kovan /** * (Mint) Generations Per Re-adjustment * * By default, we automatically trigger a difficulty adjustment * after 144 generations / mints (approx 24 hours). * * Frequent adjustments are especially important with low-liquidity * tokens, which are more susceptible to mining manipulation. * * For additional control, token providers retain the ability to trigger * a difficulty re-calculation at any time. * * NOTE: Bitcoin re-adjusts its difficulty every 2,016 generations, * which occurs approx. every 14 days. */ uint private _DEFAULT_GENERATIONS_PER_ADJUSTMENT = 144; // approx. 24hrs event Claim( address owner, address token, uint amount, address collectible, uint collectibleId ); event Excavate( address indexed token, address indexed miner, uint mintAmount, uint epochCount, bytes32 newChallenge ); event Mint( address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallenge ); event ReCalculate( address token, uint newDifficulty ); event Solution( address indexed token, address indexed miner, uint difficulty, uint nonce, bytes32 challenge, bytes32 newChallenge ); /* Constructor. */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); // _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN // _zer0netDb = Zer0netDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Minado(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * @dev Only allow access to "registered" authorized user/contract. */ modifier onlyTokenProvider( address _token ) { /* Validate authorized token manager. */ require(_zer0netDb.getBool(keccak256(abi.encodePacked( _namespace, '.', msg.sender, '.has.auth.for.', _token ))) == true); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Initialize Token */ function init( address _token, address _provider ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(hash, block.number); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _DEFAULT_GENERATIONS_PER_ADJUSTMENT); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Set mining target. */ // NOTE: This is the default difficulty of 1. _setMiningTarget( _token, _MAXIMUM_TARGET ); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, true); return true; } /** * Mint */ function mint( address _token, bytes32 _digest, uint _nonce ) public returns (bool success) { /* Retrieve the current challenge. */ uint challenge = getChallenge(_token); /* Get mint digest. */ bytes32 digest = getMintDigest( challenge, msg.sender, _nonce ); /* The challenge digest must match the expected. */ if (digest != _digest) { revert('Oops! That solution is NOT valid.'); } /* The digest must be smaller than the target. */ if (uint(digest) > getTarget(_token)) { revert('Oops! That solution is NOT valid.'); } /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', digest, '.solutions' )); /* Retrieve value from Zer0net Db. */ uint solution = _zer0netDb.getUint(hash); /* Validate solution. */ if (solution != 0x0) { revert('Oops! That solution is a DUPLICATE.'); } /* Save this digest to 'solved' solutions. */ _zer0netDb.setUint(hash, uint(digest)); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ uint generation = _zer0netDb.getUint(hash); /* Increment the generation. */ generation = generation.add(1); /* Increment the generation count by 1. */ _zer0netDb.setUint(hash, generation); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(hash); // every so often, readjust difficulty. Dont readjust when deploying if (generation % genPerAdjustment == 0) { _reAdjustDifficulty(_token); } /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /** * Make the latest ethereum block hash a part of the next challenge * for PoW to prevent pre-mining future blocks. Do this last, * since this is a protection mechanism in the mint() function. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Retrieve mining reward. */ // FIXME Add support for percentage reward. uint rewardAmount = getMintFixed(_token); /* Transfer (token) reward to minter. */ _infinityPool().transfer( _token, msg.sender, rewardAmount ); /* Emit log info. */ emit Mint( msg.sender, rewardAmount, generation, blockhash(block.number - 1) // next target ); /* Return success. */ return true; } /** * Test Mint Solution */ function testMint( bytes32 _digest, uint _challenge, address _minter, uint _nonce, uint _target ) public pure returns (bool success) { /* Retrieve digest. */ bytes32 digest = getMintDigest( _challenge, _minter, _nonce ); /* Validate digest. */ // NOTE: Cast type to 256-bit integer if (uint(digest) > _target) { /* Set flag. */ success = false; } else { /* Verify success. */ success = (digest == _digest); } } /** * Re-calculate Difficulty * * Token owner(s) can "manually" trigger the re-calculation of their token, * based on the parameters that have been set. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function reCalculateDifficulty( address _token ) external onlyTokenProvider(_token) returns (bool success) { /* Re-calculate difficulty. */ return _reAdjustDifficulty(_token); } /** * Re-adjust Difficulty * * Re-adjust the target by 5 percent. * (source: https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F) * * NOTE: Assume 240 ethereum blocks per hour (approx. 15/sec) * * NOTE: As of 2017 the bitcoin difficulty was up to 17 zeroes, * it was only 8 in the early days. */ function _reAdjustDifficulty( address _token ) private returns (bool success) { /* Set hash. */ bytes32 lastAdjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Retrieve value from Zer0net Db. */ uint lastAdjustment = _zer0netDb.getUint(lastAdjustmentHash); /* Retrieve value from Zer0net Db. */ uint blocksSinceLastAdjustment = block.number - lastAdjustment; /* Set hash. */ bytes32 adjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(adjustmentHash); /* Calculate number of expected blocks per adjustment. */ uint expectedBlocksPerAdjustment = genPerAdjustment.mul(BLOCKS_PER_GENERATION); /* Retrieve mining target. */ uint miningTarget = getTarget(_token); /* Validate the number of blocks passed; if there were less eth blocks * passed in time than expected, then miners are excavating too quickly. */ if (blocksSinceLastAdjustment < expectedBlocksPerAdjustment) { // NOTE: This number will be an integer greater than 10000. uint excess_block_pct = expectedBlocksPerAdjustment.mul(10000) .div(blocksSinceLastAdjustment); /** * Excess Block Percentage Extra * * For example: * If there were 5% more blocks mined than expected, then this is 500. * If there were 25% more blocks mined than expected, then this is 2500. */ uint excess_block_pct_extra = excess_block_pct.sub(10000); /* Set a maximum difficulty INCREASE of 50%. */ // NOTE: By default, this is within a 24hr period. if (excess_block_pct_extra > 5000) { excess_block_pct_extra = 5000; } /** * Reset the Mining Target * * Calculate the difficulty difference, then SUBTRACT * that value from the current difficulty. */ miningTarget = miningTarget.sub( /* Calculate difficulty difference. */ miningTarget .mul(excess_block_pct_extra) .div(10000) ); } else { // NOTE: This number will be an integer greater than 10000. uint shortage_block_pct = blocksSinceLastAdjustment.mul(10000) .div(expectedBlocksPerAdjustment); /** * Shortage Block Percentage Extra * * For example: * If it took 5% longer to mine than expected, then this is 500. * If it took 25% longer to mine than expected, then this is 2500. */ uint shortage_block_pct_extra = shortage_block_pct.sub(10000); // NOTE: There is NO limit on the amount of difficulty DECREASE. /** * Reset the Mining Target * * Calculate the difficulty difference, then ADD * that value to the current difficulty. */ miningTarget = miningTarget.add( miningTarget .mul(shortage_block_pct_extra) .div(10000) ); } /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(lastAdjustmentHash, block.number); /* Validate TOO SMALL mining target. */ // NOTE: This is very difficult to guess. if (miningTarget < _MINIMUM_TARGET) { miningTarget = _MINIMUM_TARGET; } /* Validate TOO LARGE mining target. */ // NOTE: This is very easy to guess. if (miningTarget > _MAXIMUM_TARGET) { miningTarget = _MAXIMUM_TARGET; } /* Set mining target. */ _setMiningTarget( _token, miningTarget ); /* Return success. */ return true; } /*************************************************************************** * * GETTERS * */ /** * Get Starting Block * * Starting Blocks * --------------- * * First blocks honoring the start of Miss Piggy's celebration year: * - Mainnet : 7,175,716 * - Ropsten : 4,956,268 * - Kovan : 10,283,438 * * NOTE: Pulls value from db `minado.starting.block` using the * respective networks. */ function getStartingBlock() public view returns (uint startingBlock) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.starting.block' )); /* Retrieve value from Zer0net Db. */ startingBlock = _zer0netDb.getUint(hash); } /** * Get minter's mintng address. */ function getMinter() external view returns (address minter) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.minter' )); /* Retrieve value from Zer0net Db. */ minter = _zer0netDb.getAddress(hash); } /** * Get generation details. */ function getGeneration( address _token ) external view returns ( uint generation, uint cycle ) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ generation = _zer0netDb.getUint(hash); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ cycle = _zer0netDb.getUint(hash); } /** * Get Minting FIXED amount */ function getMintFixed( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get Minting PERCENTAGE amount */ function getMintPct( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get (Mining) Challenge * * This is an integer representation of a recent ethereum block hash, * used to prevent pre-mining future blocks. */ function getChallenge( address _token ) public view returns (uint challenge) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Retrieve value from Zer0net Db. */ // NOTE: Convert from bytes to integer. challenge = uint(_bytesToBytes32( _zer0netDb.getBytes(hash) )); } /** * Get (Mining) Difficulty * * The number of zeroes the digest of the PoW solution requires. * (auto adjusts) */ function getDifficulty( address _token ) public view returns (uint difficulty) { /* Caclulate difficulty. */ difficulty = _MAXIMUM_TARGET.div(getTarget(_token)); } /** * Get (Mining) Target */ function getTarget( address _token ) public view returns (uint target) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Retrieve value from Zer0net Db. */ target = _zer0netDb.getUint(hash); } /** * Get Mint Digest * * The PoW must contain work that includes a recent * ethereum block hash (challenge hash) and the * msg.sender's address to prevent MITM attacks */ function getMintDigest( uint _challenge, address _minter, uint _nonce ) public pure returns (bytes32 digest) { /* Calculate digest. */ digest = keccak256(abi.encodePacked( _challenge, _minter, _nonce )); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /*************************************************************************** * * SETTERS * */ /** * Set Generations Per (Difficulty) Adjustment * * Token owner(s) can adjust the number of generations * per difficulty re-calculation. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function setGenPerAdjustment( address _token, uint _numBlocks ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _numBlocks); /* Return success. */ return true; } /** * Set (Fixed) Mint Amount */ function setMintFixed( address _token, uint _amount ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _amount); /* Return success. */ return true; } /** * Set (Dynamic) Mint Percentage */ function setMintPct( address _token, uint _pct ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _pct); /* Return success. */ return true; } /** * Set Token Parent(s) * * Enables the use of merged mining by specifying (parent) tokens * that offer an acceptibly HIGH difficulty for the child's own * mining challenge. * * Parents are saved in priority levels: * 1 - Most significant parent * 2 - 2nd most significant parent * ... * # - Least significant parent */ function setTokenParents( address _token, address[] _parents ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.parents' )); // FIXME How should we store a dynamic amount of parents? // Packed as bytes?? // FIXME TEMPORARILY LIMITED TO 3 bytes memory allParents = abi.encodePacked( _parents[0], _parents[1], _parents[2] ); /* Set value in Zer0net Db. */ _zer0netDb.setBytes(hash, allParents); /* Return success. */ return true; } /** * Set Token Provider */ function setTokenProvider( address _token, address _provider, bool _auth ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, _auth); /* Return success. */ return true; } /** * Set Mining Target */ function _setMiningTarget( address _token, uint _target ) private returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _target); /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * InfinityPool Interface * * Retrieves the current InfinityPool interface, * using the aname record from Zer0netDb. */ function _infinityPool() private view returns ( InfinityPoolInterface infinityPool ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitypool'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityPool = InfinityPoolInterface(aname); } /** * InfinityWell Interface * * Retrieves the current InfinityWell interface, * using the aname record from Zer0netDb. */ function _infinityWell() private view returns ( InfinityWellInterface infinityWell ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitywell'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityWell = InfinityWellInterface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } }
* Bytes-to-Address Converts bytes into type address./
function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); }
902,675
[ 1, 2160, 17, 869, 17, 1887, 20377, 1731, 1368, 618, 1758, 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, 565, 445, 389, 3890, 774, 1887, 12, 3890, 389, 2867, 13, 3238, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 2254, 16874, 312, 273, 374, 31, 203, 3639, 2254, 16874, 324, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 4200, 31, 277, 27245, 288, 203, 5411, 312, 6413, 8303, 31, 203, 5411, 324, 273, 2254, 16874, 24899, 2867, 63, 77, 19226, 203, 5411, 312, 1011, 261, 70, 1769, 203, 3639, 289, 203, 203, 3639, 327, 1758, 12, 81, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; /** * @title secretThoughts */ contract secretThoughts { // global public uint256 public globalThoughtID; uint256 internal upVoteSpecialLimit; uint256 internal downVoteSpecialLimit; address internal admin; // constructor constructor(uint256 upSL, uint256 downSL){ globalThoughtID = 1; upVoteSpecialLimit = upSL; downVoteSpecialLimit = downSL; admin = msg.sender; } // create events event eThoughtCreated( uint256 indexed _eThoughtID, string _eThought ); event eThoughtBlocked( uint256 indexed _eThoughtID, address _blockedBy ); event eUpdatedSpecialLimit(uint256 _upVote, uint256 _downVote); // create structure for thoughts struct Thoughts { uint256 thoughtID; uint256 upVote; uint256 downVote; uint256 timeStamp; address createdBy; address ownedBy; string thought; bool specialThought; bool isBlocked; } // create structure for Sale thoughts struct onSale { uint256 thoughtID; uint256 thoughtTokensQuantity; bool isSold; } // map data related to the thoughts mapping( uint256 => Thoughts ) thoughtData; // map data related to the sale mapping( uint256 => onSale ) onSaleData; // modifier for checking admin modifier isAdmin{ require(msg.sender == admin, "You are not allowed to block the thoughts. Do connect with Admin."); _; } // reads thoughts based on thoughtId function readThought(uint256 _thoughtID) view virtual public returns (uint256, uint256, uint256, address, address, string memory ){ return ( thoughtData[_thoughtID].upVote, thoughtData[_thoughtID].downVote, thoughtData[_thoughtID].timeStamp, thoughtData[_thoughtID].createdBy, thoughtData[_thoughtID].ownedBy, thoughtData[_thoughtID].thought ); } // create thoughts based on user input function createThought(string memory _thought) virtual public { thoughtData[globalThoughtID].thoughtID = globalThoughtID; thoughtData[globalThoughtID].upVote = 0; thoughtData[globalThoughtID].downVote = 0; thoughtData[globalThoughtID].timeStamp = block.timestamp ; thoughtData[globalThoughtID].createdBy = msg.sender; thoughtData[globalThoughtID].ownedBy = msg.sender; thoughtData[globalThoughtID].thought = _thought; thoughtData[globalThoughtID].specialThought = false; thoughtData[globalThoughtID].isBlocked = false; emit eThoughtCreated(globalThoughtID, _thought); } // update thought // still need to update the cost part after writing the ThoughtToken SmartContract function updateThought(uint256 _updateThoughtID, string memory _updatedThought) virtual public returns (string memory) { require(thoughtData[_updateThoughtID].ownedBy == msg.sender , "You are not authorised to update the thought"); thoughtData[_updateThoughtID].thought = _updatedThought; return "Thought Updated Successfully"; } // upVote the thought function upVoteThought(uint256 _thoughtID) virtual public { thoughtData[_thoughtID].upVote += 1; if(thoughtData[_thoughtID].upVote >= upVoteSpecialLimit){ thoughtData[_thoughtID].specialThought = true; } } // downVote the thought function downVoteThought(uint256 _thoughtID) virtual public { thoughtData[_thoughtID].downVote += 1; } // block thoughts by admin function blockThought(uint256 _thoughtID) virtual isAdmin public { thoughtData[globalThoughtID].isBlocked = true; emit eThoughtBlocked( _thoughtID, msg.sender ); } // update Special Limit function updateSpecialLimit(uint256 _upVoteSL, uint256 _downVoteSL) virtual isAdmin public { if(_upVoteSL != 0){ upVoteSpecialLimit = _upVoteSL; } if(_downVoteSL != 0){ downVoteSpecialLimit = _downVoteSL; } emit eUpdatedSpecialLimit(upVoteSpecialLimit, downVoteSpecialLimit); } }
block thoughts by admin
function blockThought(uint256 _thoughtID) virtual isAdmin public { thoughtData[globalThoughtID].isBlocked = true; emit eThoughtBlocked( _thoughtID, msg.sender ); }
14,049,062
[ 1, 2629, 286, 83, 9540, 87, 635, 3981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1203, 1315, 83, 9540, 12, 11890, 5034, 389, 451, 83, 9540, 734, 13, 5024, 23467, 1071, 288, 203, 3639, 286, 83, 9540, 751, 63, 6347, 1315, 83, 9540, 734, 8009, 291, 23722, 273, 638, 31, 203, 3639, 3626, 425, 1315, 83, 9540, 23722, 12, 389, 451, 83, 9540, 734, 16, 1234, 18, 15330, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } pragma solidity ^0.6.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. */ 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; } } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // 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() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } pragma solidity ^0.6.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 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"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Interface for Balancer. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract Balancer { function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual returns (uint256 spotPrice); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; abstract contract OneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view virtual returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable virtual returns (uint256 returnAmount); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // This is an interface to interact with a deployed implementation by https://github.com/kleros/action-callback-bots for // batching on-chain transactions. // See deployed implementation here: https://etherscan.io/address/0x82458d1c812d7c930bb3229c9e159cbabd9aa8cb. abstract contract TransactionBatcher { function batchSend( address[] memory targets, uint256[] memory values, bytes[] memory datas ) public payable virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Interface for Uniswap v2. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract Uniswap { // Called after every swap showing the new uniswap "price" for this token pair. event Sync(uint112 reserve0, uint112 reserve1); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/Balancer.sol"; /** * @title Balancer Mock */ contract BalancerMock is Balancer { uint256 price = 0; // these params arent used in the mock, but this is to maintain compatibility with balancer API function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual override returns (uint256 spotPrice) { return price; } // this is not a balancer call, but for testing for changing price. function setPrice(uint256 newPrice) external { price = newPrice; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/OneSplit.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title OneSplit Mock that allows manual price injection. */ contract OneSplitMock is OneSplit { address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(bytes32 => uint256) prices; receive() external payable {} // Sets price of 1 FROM = <PRICE> TO function setPrice( address from, address to, uint256 price ) external { prices[keccak256(abi.encodePacked(from, to))] = price; } function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view override returns (uint256 returnAmount, uint256[] memory distribution) { returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; return (returnAmount, distribution); } function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable override returns (uint256 returnAmount) { uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; require(amountReturn >= minReturn, "Min Amount not reached"); if (destToken == ETH_ADDRESS) { msg.sender.transfer(amountReturn); } else { require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // The Reentrancy Checker causes failures if it is successfully able to re-enter a contract. // How to use: // 1. Call setTransactionData with the transaction data you want the Reentrancy Checker to reenter the calling // contract with. // 2. Get the calling contract to call into the reentrancy checker with any call. The fallback function will receive // this call and reenter the contract with the transaction data provided in 1. If that reentrancy call does not // revert, then the reentrancy checker reverts the initial call, likely causeing the entire transaction to revert. // // Note: the reentrancy checker has a guard to prevent an infinite cycle of reentrancy. Inifinite cycles will run out // of gas in all cases, potentially causing a revert when the contract is adequately protected from reentrancy. contract ReentrancyChecker { bytes public txnData; bool hasBeenCalled; // Used to prevent infinite cycles where the reentrancy is cycled forever. modifier skipIfReentered { if (hasBeenCalled) { return; } hasBeenCalled = true; _; hasBeenCalled = false; } function setTransactionData(bytes memory _txnData) public { txnData = _txnData; } function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } } fallback() external skipIfReentered { // Attampt to re-enter with the set txnData. bool success = _executeCall(msg.sender, 0, txnData); // Fail if the call succeeds because that means the re-entrancy was successful. require(!success, "Re-entrancy was successful"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/Uniswap.sol"; /** * @title Uniswap v2 Mock that allows manual price injection. */ contract UniswapMock is Uniswap { function setPrice(uint112 reserve0, uint112 reserve1) external { emit Sync(reserve0, reserve1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { // Note: set the lastPaymentTime in this case so the contract is credited for paying during periods when it // has no locked collateral. lastPaymentTime = time; return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Only the owner (deployer) of this library can set identifier transformations b) The identifier can't * be set to blank. c) A transformed price can only be set once to prevent the deployer from changing it after the fact. * d) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public onlyOwner nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier regularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public regularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeNewRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPct).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _getLatestFundingRate() internal returns (FixedPoint.Signed memory) { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then return the current funding rate, otherwise // check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.getPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } return fundingRate.rate; } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, _getLatestFundingRate(), fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` 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 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: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function getPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPct; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } /** *Submitted for verification at Etherscan.io on 2017-12-12 */ // Copyright (C) 2015, 2016, 2017 Dapphub // 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/>. // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Copied from the verified code from Etherscan: // https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code // And then updated for Solidity version 0.6. Specific changes: // * Change `function() public` into `receive() external` and `fallback() external` // * Change `this.balance` to `address(this).balance` // * Ran prettier contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; receive() external payable { deposit(); } fallback() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR must be more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn * from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add * logic to this method to account for any such pending fees. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ), "Unresolved oracle price" ); int256 optimisticOraclePrice = optimisticOracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData()); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRate, uint256 proposerBond, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRate, uint256 proposerBond, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPct.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPct.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // TODO: Do we also need to apply some sort of funding rate adjustment to account for multiplier changes // since liquidation time? FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn * from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add * logic to this method to account for any such pending fees. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Used internally by Truffle migrations. * @dev See https://www.trufflesuite.com/docs/truffle/getting-started/running-migrations#initial-migration for details. */ contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingInterface) { return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.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/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } // Event. emit ProposePrice(requester, proposer, identifier, timestamp, ancillaryData, proposedPrice); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; totalBond = request.bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); if (finalFee > 0) { request.currency.safeIncreaseAllowance(address(store), finalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(finalFee)); } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } // Event. emit DisputePrice(requester, request.proposer, disputer, identifier, timestamp, ancillaryData); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function getPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; payout = request.bond.mul(2).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } // Event. emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function getPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.getPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. * stonkbase.org * tw StonkBase */ constructor() public ExpandedERC20("StonkBase", "SBF", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.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. 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)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip15Upgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; constructor( address _governor, address _existingVoting, address _newVoting, address _finder ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); } function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set current Voting contract to migrated. existingVoting.setMigrated(newVoting); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } }
* @notice Proposes a new funding rate. Proposer receives a reward if correct. @param rate funding rate being proposed. @param timestamp time at which the funding rate was computed./ Timestamp must be after the last funding rate update time, within the last 30 minutes. Set the proposal time in order to allow this contract to track this request. Set up optimistic oracle. Note: requestPrice will revert if `timestamp` is less than the current block timestamp. Pull bond from caller and send to optimistic oracle.
function proposeNewRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPct).rawValue ) ); if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); }
591,018
[ 1, 626, 10522, 279, 394, 22058, 4993, 18, 1186, 5607, 17024, 279, 19890, 309, 3434, 18, 225, 4993, 22058, 4993, 3832, 20084, 18, 225, 2858, 813, 622, 1492, 326, 22058, 4993, 1703, 8470, 18, 19, 8159, 1297, 506, 1839, 326, 1142, 22058, 4993, 1089, 813, 16, 3470, 326, 1142, 5196, 6824, 18, 1000, 326, 14708, 813, 316, 1353, 358, 1699, 333, 6835, 358, 3298, 333, 590, 18, 1000, 731, 5213, 5846, 20865, 18, 3609, 30, 590, 5147, 903, 15226, 309, 1375, 5508, 68, 353, 5242, 2353, 326, 783, 1203, 2858, 18, 14899, 8427, 628, 4894, 471, 1366, 358, 5213, 5846, 20865, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 450, 4150, 1908, 4727, 12, 7505, 2148, 18, 12294, 3778, 4993, 16, 2254, 5034, 2858, 13, 203, 3639, 3903, 203, 3639, 1656, 281, 1435, 203, 3639, 1661, 426, 8230, 970, 1435, 203, 3639, 1135, 261, 7505, 2148, 18, 13290, 3778, 2078, 9807, 13, 203, 565, 288, 203, 3639, 2583, 12, 74, 14351, 4727, 18, 685, 8016, 950, 422, 374, 16, 315, 14592, 316, 4007, 8863, 203, 3639, 389, 5662, 42, 14351, 4727, 12, 5141, 1769, 203, 203, 3639, 2254, 5034, 6680, 273, 5175, 950, 5621, 203, 3639, 2254, 5034, 1089, 950, 273, 22058, 4727, 18, 2725, 950, 31, 203, 3639, 2583, 12, 203, 5411, 2858, 405, 1089, 950, 597, 2858, 1545, 6680, 18, 1717, 24899, 588, 809, 7675, 685, 8016, 950, 52, 689, 3039, 3631, 203, 5411, 315, 1941, 14708, 813, 6, 203, 3639, 11272, 203, 203, 3639, 22058, 4727, 18, 685, 8016, 950, 273, 2858, 31, 203, 203, 3639, 19615, 5846, 23601, 1358, 5213, 5846, 23601, 273, 389, 588, 13930, 5846, 23601, 5621, 203, 203, 3639, 1731, 1578, 2756, 273, 22058, 4727, 18, 5644, 31, 203, 3639, 1731, 3778, 392, 71, 737, 814, 751, 273, 389, 588, 979, 71, 737, 814, 751, 5621, 203, 3639, 5213, 5846, 23601, 18, 2293, 5147, 12, 5644, 16, 2858, 16, 392, 71, 737, 814, 751, 16, 4508, 2045, 287, 7623, 16, 374, 1769, 203, 3639, 2078, 9807, 273, 15038, 2148, 18, 13290, 12, 203, 5411, 5213, 5846, 23601, 18, 542, 9807, 12, 203, 7734, 2756, 16, 203, 7734, 2858, 16, 203, 7734, 392, 71, 737, 2 ]
pragma solidity 0.4.24; // File: 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: 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: contracts/token/ERC721/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 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _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; } // File: contracts/token/ERC721/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() public view returns (string _name); function symbol() public 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 { } // File: contracts/token/ERC721/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,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @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. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: contracts/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. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev 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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: contracts/token/ERC721/BikeOwnershipProtocol.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract BikeOwnershipProtocol is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; //Ex-ower emails of a bike token mapping(uint256 => mapping(address => string)) public exOwnerEmails; //Ex-ower addresses mapping (uint256 => address[]) public exOwnerAddresses; //rental prices for bikes mapping (uint256 => uint256) public rentalPrices; //rental recorded time mapping (uint256 => uint256) public rentalStartTime; mapping (uint256 => uint256) public rentalEndTime; //rental owner mapping (uint256 => address) public renters; /** * @dev Constructor function */ function BikeOwnershipProtocol() public { name_ = "BikeOwnershipProtocol"; symbol_ = "BKCOP"; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } function create(string ipfsHash) public { uint256 tokenId = allTokens.length + 1; _mint(msg.sender, tokenId); _setTokenURI(tokenId, ipfsHash); } function setTokenIPFSHash(uint256 _tokenId, string _ipfsHash) public { _setTokenURI(_tokenId,_ipfsHash); } function verifyByExOwner(uint256 tokenId, address exOwner, string email) public { require(bytes(exOwnerEmails[tokenId][exOwner]).length == 0); exOwnerAddresses[tokenId].push(exOwner); exOwnerEmails[tokenId][exOwner] = email; } function getExOwnerAddresses(uint256 tokenId) public returns (address[]){ return exOwnerAddresses[tokenId]; } function getExOwnerEmail(uint256 tokenId, address exOwner) public returns (string){ return exOwnerEmails[tokenId][exOwner]; } function setBikeRentalPrice(uint256 _tokenId, uint256 _price) public{ require(ownerOf(_tokenId) == msg.sender); rentalPrices[_tokenId] = _price; } function getBikeRentalPrice(uint256 _tokenId) public view returns (uint256) { return rentalPrices[_tokenId]; } function rentStart(uint256 _tokenId, uint256 _startTime) public { require(ownerOf(_tokenId) != msg.sender); rentalStartTime[_tokenId] = _startTime; renters[_tokenId] = msg.sender; } function rentEnd(uint256 _tokenId, uint256 _endTime) public{ require(renters[_tokenId] == msg.sender); require(rentalStartTime[_tokenId] != 0x0); uint256 startTime = rentalStartTime[_tokenId]; require(_endTime > startTime); rentalEndTime[_tokenId] = _endTime; renters[_tokenId] = 0x0; } function getRentalStartTime(uint _tokenId) public returns (uint256) { return rentalStartTime[_tokenId]; } function getRenterOfBike(uint _tokenId) public returns (address) { return renters[_tokenId]; } } // File: contracts/token/ERC20/BKCTestToken.sol // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract BKCTestToken is ERC20Interface, Ownable { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BKCMVPTestToken"; name = "BC Network Test Token"; decimals = 18; _totalSupply = 1000000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } // File: contracts/network/BikeCoinUserProfile.sol contract BikeCoinUserProfile is Ownable { using SafeMath for uint256; string ipfsHash; event Forwarded (address destination, uint value, bytes data, uint256 transferAmount, uint256 halfFeeAmount); event Received (address sender, uint value); event Rent(address indexed renter, address indexed bikeOwner, uint256 startTime, uint256 endTime, uint256 feeAmount); function () public payable { Received(msg.sender, msg.value); } function forward(address destination, uint value, bytes data) public onlyOwner { require(executeCall(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) } } function setIPFSHash(string x) public onlyOwner { ipfsHash = x; } function getIPFSHash() public view returns (string x) { return ipfsHash; } function createBike(string ipfsHash, BikeOwnershipProtocol bikeProtocol) public { bikeProtocol.create(ipfsHash); } function startBikeRental(uint256 _tokenId, uint256 _startTime, BikeOwnershipProtocol bikeProtocol) public { bikeProtocol.rentStart(_tokenId,_startTime); } function endBikeRental(uint256 _tokenId, uint256 _endTime, BikeOwnershipProtocol bikeProtocol, BKCTestToken token) public { bikeProtocol.rentEnd(_tokenId,_endTime); address bikeOwner = bikeProtocol.ownerOf(_tokenId); uint256 startTime = bikeProtocol.getRentalStartTime(_tokenId); uint256 pricePerHour = bikeProtocol.getBikeRentalPrice(_tokenId); uint256 feeAmount = _endTime.sub(startTime).mul(pricePerHour).div(3600); //transfer rental fee token.transfer(bikeOwner,feeAmount); emit Rent(msg.sender, bikeOwner, startTime, _endTime, feeAmount); } struct TKN { address sender; uint value; bytes data; bytes4 sig; } //Token receivable function function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; if (_data.length > 0) { uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); } // * tkn variable is analogue of msg variable of Ether transaction // * tkn.sender is person who initiated this token transaction (analogue of msg.sender) // * tkn.value the number of tokens that were sent (analogue of msg.value) // * tkn.data is data of token transaction (analogue of msg.data) // * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution } } // File: contracts/network/BikeCoinNetwork.sol contract BikeCoinNetwork is Ownable { using SafeMath for uint256; address relay; mapping(address => address) owners; uint256 numberOfProfiles = 0; mapping(address => bool) whitelist; modifier onlyAuthorized() { require((msg.sender == relay) || checkMessageData(msg.sender)); _; } modifier onlyOwnerOfProfile(address profile, address sender) { require(isOwnerOfProfile(profile, sender)); _; } modifier validAddress(address addr) { //protects against some weird attacks require(addr != address(0)); _; } modifier validDestination(address destination) { require(whitelist[destination] == true); _; } function BikeCoinNetwork(address _relayAddress) public { relay = _relayAddress; } function createUserProfile(address owner, string ipfsMetaData) public validAddress(owner) onlyAuthorized { require (owners[owner] == address(0)); require (bytes(ipfsMetaData).length > 0); BikeCoinUserProfile userProfile = new BikeCoinUserProfile(); userProfile.setIPFSHash(ipfsMetaData); owners[owner] = userProfile; numberOfProfiles = numberOfProfiles.add(1); } function getUserProfile(address owner) public view returns (address) { return owners[owner]; } function updateUserProfileMetaData(address sender, BikeCoinUserProfile profile, string ipfsHash) public onlyAuthorized onlyOwnerOfProfile(profile, sender) { profile.setIPFSHash(ipfsHash); } function addBikeToNetwork(address sender, string _ipfsMetaData, BikeCoinUserProfile profile, BikeOwnershipProtocol bikeProtocol) onlyAuthorized onlyOwnerOfProfile(profile, sender) { profile.createBike(_ipfsMetaData,bikeProtocol); } function startBikeRental(address sender, uint256 _tokenId, uint256 _startTime, BikeCoinUserProfile profile, BikeOwnershipProtocol bikeProtocol) public onlyAuthorized onlyOwnerOfProfile(profile, sender) { profile.startBikeRental(_tokenId,_startTime,bikeProtocol); } function endBikeRental(address sender , uint256 _tokenId, uint256 _endTime, BikeCoinUserProfile profile, BikeOwnershipProtocol bikeProtocol, BKCTestToken token) public onlyAuthorized onlyOwnerOfProfile(profile, sender) { profile.endBikeRental(_tokenId, _endTime ,bikeProtocol, token); } /// @dev Allows a user to forward a call through their proxy. function forwardTo(address sender, BikeCoinUserProfile profile, address destination, uint value, bytes data) public onlyAuthorized onlyOwnerOfProfile(profile, sender) validDestination(destination) { profile.forward(destination, value, data); } function addToWhitelist(address[] contractAddresses) onlyOwner { updateWhitelist(contractAddresses,true); } function removeFromWhitelist(address[] contractAddresses) onlyOwner { updateWhitelist(contractAddresses,false); } function updateWhitelist(address[] contractAddresses, bool newStatus) private { for (uint i = 0; i < contractAddresses.length; i++) { whitelist[contractAddresses[i]] = newStatus; } } //Checks that address a is the first input in msg.data. //Has very minimal gas overhead. function checkMessageData(address a) internal pure returns (bool t) { if (msg.data.length < 36) return false; assembly { let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF t := eq(a, and(mask, calldataload(4))) } } function isOwnerOfProfile(address profile, address owner) public view returns (bool) { return (owners[owner] == profile); } }
Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
1,018,258
[ 1, 426, 3341, 777, 2430, 526, 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, 202, 202, 11890, 5034, 1147, 1016, 273, 777, 5157, 1016, 63, 67, 2316, 548, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: UNLICENSED //Check before deployment: Hardcoded token contract address, pair address /* Generic presale contract for ERC20 token. Important: Set gas limit to 210000 if sending ether directly! It reserves much but consumes max 80%. Presale allows buying specified ERC20 for rate mentioned in constructor. Allowed amounts: 0.05 ETH to 0.5 ETH. Presale ends once there is no supply left. Once eth is sent to this presale contract sender gets their tokens, eth is wrapped and sent directly to the liquidity pool along with the same amount of tokens. The pool is synced to reflect new ratio right away and calculates token price correctly. Neither ERC20 nor ETH goes to any wallet except token to buyer. Deployer will receive no ether from this presale. This makes liquidity continuously inflating and keeping price near presale price ratio by keeping either the presale or direct uniswap trade cheaper at every moment. Once presale ends there is enough ether liquidity and the price can start going up! */ pragma solidity =0.7.6; interface UNIV2Sync { function sync() external; } interface IERC { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function feeDistributor() external view returns (address); } interface IWETH { function deposit() external payable; function balanceOf(address _owner) external returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function withdraw(uint256 _amount) external; } 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; } } library Address { function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); 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); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // 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); } } } } contract ERC20Presale { using Address for address; address public token; address public pair; address public wethContract; uint256 public rate; uint256 public weiRaised; constructor() { rate = 5e9; //16.5M2e = 8 eth -> 2M2e = 2e8 = 1/5 e9 = 1e18 wei/5e9, 1M2e = 0.5 weiRaised = 0; token = 0x8937041C8C52a78c25aa54051F6a9dAdA23D42A2; //mainnet pair = 0x76d629ebAD7fDf703Ed5923f41F20c472e8F23E3; //mainnet //wethContract = 0xc778417E063141139Fce010982780140Aa0cD5Ab; //ropsten wethContract = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //mainnet } receive() external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { require(msg.sender == tx.origin); //no automated arbitrage require(_beneficiary != address(0)); require(msg.value >= 5e16 wei && msg.value <= 5e17 wei); uint256 tokens = msg.value/rate; weiRaised+=msg.value; IERC(token).transfer(_beneficiary,tokens); IERC(token).transfer(pair,tokens); //Convert any ETH to WETH (always). uint256 amountETH = address(this).balance; if (amountETH > 0) { IWETH(wethContract).deposit{value : amountETH}(); } uint256 amountWETH = IWETH(wethContract).balanceOf(address(this)); //Sends weth to pool if (amountWETH > 0) { IWETH(wethContract).transfer(pair, amountWETH); } UNIV2Sync(pair).sync(); //important to reflect updated price } }
Look for revert reason and bubble it up if present The easiest way to bubble the revert reason is using memory via assembly solhint-disable-next-line no-inline-assembly
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } }
321,184
[ 1, 9794, 364, 15226, 3971, 471, 21577, 518, 731, 309, 3430, 1021, 7264, 77, 395, 4031, 358, 21577, 326, 15226, 3971, 353, 1450, 3778, 3970, 19931, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8705, 1477, 1253, 12, 6430, 2216, 16, 1731, 3778, 327, 892, 16, 533, 3778, 9324, 13, 3238, 16618, 1135, 12, 3890, 3778, 13, 288, 203, 3639, 309, 261, 4768, 13, 288, 203, 5411, 327, 327, 892, 31, 203, 5411, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 2463, 892, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 327, 892, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 12, 1636, 1079, 1769, 203, 5411, 289, 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 ]
./full_match/80001/0x271e7Ba38970356FBbE4b57912b76325F3C8731e/sources/contracts/DoubleDiceProtocol.sol
* @notice For a VF that has been resolved with winners and winner-profits, claim the share of the total ERC-20 winner-profits corresponding to the ERC-1155 balances held by the calling account on the specified `tokenIds`. If a tokenId is included multiple times, it will count only once. @param vfId The VF id. This VF must be in the Claimable_Payouts state. @param tokenIds The ERC-1155 token-ids for which to claim payouts. If a tokenId is included multiple times, it will count only once./
{ VirtualFloor storage vf = _vfs[vfId]; function claimPayouts(uint256 vfId, uint256[] calldata tokenIds) public whenNotPaused { VirtualFloorState state = vf.state(); if (!(state == VirtualFloorState.Claimable_Payouts)) revert WrongVirtualFloorState(state); } address msgSender = _msgSender(); uint256 totalPayout = 0; uint256[] memory amounts = new uint256[](tokenIds.length); uint8 winningOutcomeIndex = vf.winningOutcomeIndex; UFixed256x18 winningOutcomeTotalAmountTimesBeta = vf.outcomeTotals[winningOutcomeIndex].amountTimesBeta_e18; uint256 totalWinnerProfits = vf.winnerProfits; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; (uint256 extractedVfId, uint8 outcomeIndex, UFixed32x6 beta_e6) = tokenId.destructure(); if (!(extractedVfId == vfId)) revert MismatchedVirtualFloorId(tokenId); uint256 amount = _balances[tokenId][msgSender]; amounts[i] = amount; _balances[tokenId][msgSender] = 0; if (outcomeIndex == winningOutcomeIndex) { UFixed256x18 beta = beta_e6.toUFixed256x18(); UFixed256x18 amountTimesBeta = beta.mul0(amount); uint256 profit = amountTimesBeta.mul0(totalWinnerProfits).divToUint256(winningOutcomeTotalAmountTimesBeta); totalPayout += amount + profit; } } emit TransferBatch(msgSender, msgSender, address(0), tokenIds, amounts); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; (uint256 extractedVfId, uint8 outcomeIndex, UFixed32x6 beta_e6) = tokenId.destructure(); if (!(extractedVfId == vfId)) revert MismatchedVirtualFloorId(tokenId); uint256 amount = _balances[tokenId][msgSender]; amounts[i] = amount; _balances[tokenId][msgSender] = 0; if (outcomeIndex == winningOutcomeIndex) { UFixed256x18 beta = beta_e6.toUFixed256x18(); UFixed256x18 amountTimesBeta = beta.mul0(amount); uint256 profit = amountTimesBeta.mul0(totalWinnerProfits).divToUint256(winningOutcomeTotalAmountTimesBeta); totalPayout += amount + profit; } } emit TransferBatch(msgSender, msgSender, address(0), tokenIds, amounts); vf.paymentToken.safeTransfer(msgSender, totalPayout); }
5,639,124
[ 1, 1290, 279, 776, 42, 716, 711, 2118, 4640, 598, 5657, 9646, 471, 5657, 1224, 17, 16121, 1282, 16, 7516, 326, 7433, 434, 326, 2078, 4232, 39, 17, 3462, 5657, 1224, 17, 16121, 1282, 4656, 358, 326, 4232, 39, 17, 2499, 2539, 324, 26488, 15770, 635, 326, 4440, 2236, 603, 326, 1269, 1375, 2316, 2673, 8338, 971, 279, 1147, 548, 353, 5849, 3229, 4124, 16, 518, 903, 1056, 1338, 3647, 18, 225, 28902, 548, 1021, 776, 42, 612, 18, 1220, 776, 42, 1297, 506, 316, 326, 18381, 429, 67, 52, 2012, 87, 919, 18, 225, 1147, 2673, 1021, 4232, 39, 17, 2499, 2539, 1147, 17, 2232, 364, 1492, 358, 7516, 293, 2012, 87, 18, 971, 279, 1147, 548, 353, 5849, 3229, 4124, 16, 518, 903, 1056, 1338, 3647, 18, 19, 2, 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, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 7269, 42, 5807, 2502, 28902, 273, 389, 90, 2556, 63, 90, 74, 548, 15533, 203, 565, 445, 7516, 52, 2012, 87, 12, 11890, 5034, 28902, 548, 16, 2254, 5034, 8526, 745, 892, 1147, 2673, 13, 203, 3639, 1071, 203, 3639, 1347, 1248, 28590, 203, 3639, 288, 203, 5411, 7269, 42, 5807, 1119, 919, 273, 28902, 18, 2019, 5621, 203, 5411, 309, 16051, 12, 2019, 422, 7269, 42, 5807, 1119, 18, 9762, 429, 67, 52, 2012, 87, 3719, 15226, 24668, 6466, 42, 5807, 1119, 12, 2019, 1769, 203, 3639, 289, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 2254, 5034, 2078, 52, 2012, 273, 374, 31, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 394, 2254, 5034, 8526, 12, 2316, 2673, 18, 2469, 1769, 203, 3639, 2254, 28, 5657, 2093, 19758, 1016, 273, 28902, 18, 8082, 2093, 19758, 1016, 31, 203, 3639, 587, 7505, 5034, 92, 2643, 5657, 2093, 19758, 5269, 6275, 10694, 38, 1066, 273, 28902, 18, 21672, 31025, 63, 8082, 2093, 19758, 1016, 8009, 8949, 10694, 38, 1066, 67, 73, 2643, 31, 203, 3639, 2254, 5034, 2078, 59, 7872, 626, 18352, 273, 28902, 18, 91, 7872, 626, 18352, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 1147, 548, 273, 1147, 2673, 63, 77, 15533, 203, 5411, 261, 11890, 5034, 9438, 58, 74, 548, 16, 2254, 28, 12884, 1016, 16, 587, 7505, 1578, 92, 26, 6796, 67, 73, 26, 2 ]
// SPDX-License-Identifier: MIT /* MIT License Copyright (c) 2021 Paladin10 */ pragma solidity ^0.8.0; interface IFeature { function featureByIndex (uint256 id, uint256 fi) external view returns (uint256 what, bytes32 fHash); } interface IERC721 { function totalSupply() external returns (uint256); function mint(address to) external; function ownerOf(uint256 tokenId) external view returns (address owner); function getApproved(uint256 tokenId) external view returns (address operator); function stat(string calldata statId, uint256 id) external view returns (bytes memory); function set (string calldata statId, uint256 id, bytes memory val) external; function add (string calldata statId, uint256 id, uint256 val) external; function sub (string calldata statId, uint256 id, uint256 val) external; } contract ShardAlly { /* * internal view/pure functions */ function _shuffle (bytes32 hash, uint256[6] memory arr) internal pure returns (uint256[6] memory res) { //clone arr for(uint256 i = 0; i < 6; i++){ res[i] = arr[i]; } //swap bytes32 _hash; uint256 j; uint256 val; for(uint256 i = 0; i < 6; i++){ _hash = keccak256(abi.encode(hash, i)); j = uint256(_hash) % (i+1); val = res[i]; res[i] = res[j]; res[j] = val; } } //hash makes each shard unique function nftHash (address _nft, uint256 id) public pure returns (bytes32) { return keccak256(abi.encode("But God...",_nft,id)); } /* * Basic Ally Generation */ uint256 internal constant SEEDMAX = 256 ** 4; string[5] internal BASEFORM = ["Human","Humanoid","Animal","Artificial","Alien"]; uint256[12] internal SIZES = [0,1,1,2,2,2,2,2,2,3,3,4]; uint256[12][5] internal NAPP = [ [0,1,1,1,1,1,1,2,2,2,2,2], [0,0,1,1,1,1,1,1,1,2,2,2], [0,0,0,0,1,1,1,1,1,1,2,2], [0,0,0,0,0,0,0,0,0,1,1,1], [0,0,0,0,0,0,0,0,0,0,0,1] ]; // Size and Number Appearing function SizeAndNApp (uint256 base, uint256 seed) public view returns (uint256 size, uint256 napp) { bytes32 hash = lifeformHash(base, seed); size = 2; if(base != 0) { bytes32 sizeHash = keccak256(abi.encode(hash,"size")); size = SIZES[uint256(sizeHash) % 12]; } bytes32 naHash = keccak256(abi.encode(hash,"nApp")); napp = NAPP[size][uint256(naHash) % 12]; } /* * Stats */ function statMods (bytes32 hash) public pure returns (uint256 b, uint256 p) { //boost b = uint256(keccak256(abi.encode(hash,"stat-boost"))) % 6; //penalty uint256 _p = 1 + (uint256(keccak256(abi.encode(hash,"stat-penalty"))) % 5); p = b+_p > 5 ? b+_p-6 : b+_p; } function baseStats (bytes32 allyId, bytes32 form, bytes32 culture) public pure returns (uint256[6] memory stats) { //basic stat array shuffle stats = _shuffle(keccak256(abi.encode(allyId, "stats")),[uint256(20),25,30,35,40,50]); //mod for culture and people (uint256 fb, uint256 fp) = statMods(form); (uint256 cb, uint256 cp) = statMods(culture); stats[fb] += 10; stats[cb] += 10; stats[fp] -= 10; stats[cp] -= 10; } function baseStatsFromAlly (bytes32 featureHash, bytes32 allyId) public view returns (uint256[6] memory stats) { (uint256 base, uint256 seed) = lifeform(featureHash); return baseStats(allyId, lifeformHash(base, seed), baseCulture(featureHash)); } //Culture and Lifeform function baseCulture (bytes32 hash) public pure returns (bytes32) { return keccak256(abi.encode(hash, "culture")); } function lifeformHash (uint256 base, uint256 seed) public view returns (bytes32) { return keccak256(abi.encode(BASEFORM[base],seed)); } // hash = feature hash function lifeform (bytes32 hash) public pure returns (uint256 base, uint256 seed) { //first is the base form of the creature uint256 bp = uint256(hash) % 100; base = bp < 10 ? 0 : bp < 35 ? 1 : bp < 60 ? 2 : bp < 80 ? 3 : 4; //next is the seed id uint256 rp = uint256(keccak256(abi.encode(hash, "seed-distribution"))) % 100; //seed range is a distribution - 50% < 100; 90% < 1000 uint256 _rangeMax = rp < 50 ? 100 : rp < 90 ? 1000 : SEEDMAX; //get seed based upon range seed = uint256(keccak256(abi.encode(hash, "seed"))) % _rangeMax; } /* * Claim an Ally */ //contracts IERC721 public SHARDS = IERC721(0x8dB24cD8451B133115588ff1350ca47aefE2CB8c); IFeature public FEATURES = IFeature(0x47eC56991f0E456593b7F26897C44b72617C77C4); IERC721 public ALLY = IERC721(0xAe1Ad876f3759eaBcc04733ce32918cBEC5218B5); //feature id uint256 internal constant FID = 0; //pay to claim string internal PAYID = "SRD.COSMIC"; uint256 internal COST = 1 ether; //cost multiplyer based upon # appearing uint256[3] internal COSTM = [10,5,3]; //claim once per day uint256 internal PERIOD = 1 days; mapping (bytes32 => uint256) public lastClaim; //unique id for each claim for traking time function _claimId (uint256 id, uint256 fi) internal pure returns(bytes32) { return keccak256(abi.encode(id, fi)); } //check for approval function _isApprovedOrOwner(uint256 id) internal view returns (bool) { return SHARDS.getApproved(id) == msg.sender || SHARDS.ownerOf(id) == msg.sender; } /* * * Check allow claim */ function _mayClaim (uint256 id, uint256 fi) internal returns (bytes32) { require(_isApprovedOrOwner(id), "ShardAlly: not approved or owner"); //claim period bytes32 _claim = _claimId(id,fi); uint256 _now = block.timestamp; require((_now - lastClaim[_claim]) >= PERIOD, "ShardAlly: wait one day to claim"); //update claim lastClaim[_claim] = _now; //get feature (uint256 fid, bytes32 fHash) = FEATURES.featureByIndex(id, fi); require(fHash != bytes32(0), "ShardAlly: beyond available features"); require(fid == FID, "ShardAlly: incorrect feature type for cliam"); return fHash; } //claim function claim (uint256 _shard, uint256 fi) public { //check claim allowance - get hash of feature bytes32 fHash = _mayClaim(_shard, fi); //get basic data - lifeform and # appearing (uint256 base, uint256 seed) = lifeform(fHash); (, uint256 napp) = SizeAndNApp(base, seed); //cost based upon # uint256 cost = COSTM[napp] * COST; //pull payment, subtract - will throw a error if not enough SHARDS.sub(PAYID, _shard, cost); /* * Mint Token */ //gets id - which will be incremented by mint uint256 _ally = ALLY.totalSupply(); ALLY.mint(msg.sender); bytes32 allyId = nftHash(address(ALLY), _ally); /* * Set Stats */ //home, current shard location bytes memory shardBytes = abi.encode(address(SHARDS),_shard); ALLY.set("home", _ally, shardBytes); ALLY.set("shard", _ally, shardBytes); //lifeform, culture ALLY.set("people", _ally, abi.encode(fHash, baseCulture(fHash))); //base stats ALLY.set("baseStats", _ally, abi.encode(baseStatsFromAlly(fHash, allyId))); } }
hash = feature hashfirst is the base form of the creaturenext is the seed idseed range is a distribution - 50% < 100; 90% < 1000get seed based upon range
function lifeform (bytes32 hash) public pure returns (uint256 base, uint256 seed) { uint256 bp = uint256(hash) % 100; base = bp < 10 ? 0 : bp < 35 ? 1 : bp < 60 ? 2 : bp < 80 ? 3 : 4; uint256 rp = uint256(keccak256(abi.encode(hash, "seed-distribution"))) % 100; uint256 _rangeMax = rp < 50 ? 100 : rp < 90 ? 1000 : SEEDMAX; seed = uint256(keccak256(abi.encode(hash, "seed"))) % _rangeMax; } IFeature public FEATURES = IFeature(0x47eC56991f0E456593b7F26897C44b72617C77C4); IERC721 public ALLY = IERC721(0xAe1Ad876f3759eaBcc04733ce32918cBEC5218B5); uint256 internal COST = 1 ether; mapping (bytes32 => uint256) public lastClaim;
1,035,146
[ 1, 2816, 273, 2572, 1651, 3645, 353, 326, 1026, 646, 434, 326, 1519, 1231, 4285, 353, 326, 5009, 612, 12407, 1048, 353, 279, 7006, 300, 6437, 9, 411, 2130, 31, 8566, 9, 411, 4336, 588, 5009, 2511, 12318, 1048, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 17140, 687, 261, 3890, 1578, 1651, 13, 203, 3639, 1071, 16618, 1135, 261, 11890, 5034, 1026, 16, 2254, 5034, 5009, 13, 7010, 565, 288, 203, 3639, 2254, 5034, 9107, 273, 2254, 5034, 12, 2816, 13, 738, 2130, 31, 203, 3639, 1026, 273, 9107, 411, 1728, 692, 374, 294, 9107, 411, 13191, 692, 404, 294, 9107, 411, 4752, 692, 576, 294, 9107, 411, 8958, 692, 890, 294, 1059, 31, 7010, 540, 203, 3639, 2254, 5034, 8715, 273, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2816, 16, 315, 12407, 17, 16279, 6, 20349, 738, 2130, 31, 203, 3639, 2254, 5034, 389, 3676, 2747, 273, 8715, 411, 6437, 692, 2130, 294, 8715, 411, 8566, 692, 4336, 294, 3174, 2056, 6694, 31, 27699, 3639, 5009, 273, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2816, 16, 315, 12407, 6, 20349, 738, 389, 3676, 2747, 31, 203, 565, 289, 203, 377, 203, 565, 467, 4595, 1071, 25201, 55, 273, 467, 4595, 12, 20, 92, 9462, 73, 39, 4313, 2733, 21, 74, 20, 41, 24, 4313, 6162, 23, 70, 27, 42, 5558, 6675, 27, 39, 6334, 70, 27, 5558, 4033, 39, 4700, 39, 24, 1769, 203, 565, 467, 654, 39, 27, 5340, 1071, 8061, 61, 273, 467, 654, 39, 27, 5340, 12, 20, 21703, 73, 21, 1871, 28, 6669, 74, 23, 5877, 29, 24852, 38, 952, 3028, 27, 3707, 311, 1578, 29, 2643, 71, 5948, 39, 9401, 2643, 38, 25, 1769, 203, 377, 203, 377, 203, 565, 2254, 5034, 2 ]
./partial_match/1/0xa1A7a95d7AD043b356D72b7c5fBE0eF053ba8c13/sources/contracts/Comptroller.sol
hypothetical account shortfall below collateral requirements)/ For each asset the account is in Read the balances and exchange rate from the slToken Calculate effects of interacting with slTokenModify redeem effect sumBorrowPlusEffects += tokensToDenom * redeemTokens
function getHypotheticalAccountLiquidityInternal( address account, SLToken slTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; SLToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { SLToken asset = assets[i]; (oErr, vars.slTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == slTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } }
11,022,808
[ 1, 76, 879, 10370, 278, 1706, 2236, 3025, 25602, 5712, 4508, 2045, 287, 8433, 13176, 2457, 1517, 3310, 326, 2236, 353, 316, 2720, 326, 324, 26488, 471, 7829, 4993, 628, 326, 2020, 1345, 9029, 16605, 434, 16592, 310, 598, 2020, 1345, 11047, 283, 24903, 5426, 2142, 38, 15318, 13207, 29013, 1011, 2430, 774, 8517, 362, 225, 283, 24903, 5157, 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, 7628, 879, 10370, 278, 1706, 3032, 48, 18988, 24237, 3061, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 348, 48, 1345, 2020, 1345, 11047, 16, 203, 3639, 2254, 283, 24903, 5157, 16, 203, 3639, 2254, 29759, 6275, 13, 2713, 1476, 1135, 261, 668, 16, 2254, 16, 2254, 13, 288, 203, 203, 3639, 2254, 320, 2524, 31, 203, 3639, 2361, 668, 312, 2524, 31, 203, 203, 3639, 348, 48, 1345, 8526, 3778, 7176, 273, 2236, 10726, 63, 4631, 15533, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 7176, 18, 2469, 31, 277, 27245, 288, 203, 5411, 348, 48, 1345, 3310, 273, 7176, 63, 77, 15533, 203, 203, 5411, 261, 83, 2524, 16, 4153, 18, 2069, 1345, 13937, 16, 4153, 18, 70, 15318, 13937, 16, 4153, 18, 16641, 4727, 49, 970, 21269, 13, 273, 3310, 18, 588, 3032, 4568, 12, 4631, 1769, 203, 7734, 327, 261, 668, 18, 13653, 31667, 67, 3589, 16, 374, 16, 374, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 4699, 18, 280, 16066, 5147, 49, 970, 21269, 422, 374, 13, 288, 203, 7734, 327, 261, 668, 18, 7698, 1441, 67, 3589, 16, 374, 16, 374, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 81, 2524, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 7734, 327, 261, 668, 18, 49, 3275, 67, 3589, 16, 374, 16, 374, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 81, 2524, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 7734, 327, 261, 668, 18, 2 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @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 Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; uint32 constant PPM_RESOLUTION = 1000000; // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { ERC1967Proxy } from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import { AccessDenied, Utils } from "./Utils.sol"; /** * @dev this contract is a slightly optimized version of the original TransparentUpgradeableProxy solely designed to * work with the ProxyAdmin contract: * * - the address of the admin is stored as an immutable state variables and as the result: * - the address of the admin can't be change, so the changeAdmin() function was subsequently removed */ contract TransparentUpgradeableProxyImmutable is ERC1967Proxy, Utils { address internal immutable _admin; /** * @dev initializes an upgradeable proxy managed by `initAdmin`, backed by the implementation at `logic`, and * optionally initialized with `data` as explained in {ERC1967Proxy-constructor} */ constructor( address logic, address initAdmin, bytes memory data ) payable ERC1967Proxy(logic, data) validAddress(initAdmin) { _admin = initAdmin; // still store it to work with EIP-1967 _changeAdmin(initAdmin); } modifier ifAdmin() { if (msg.sender == _admin) { _; } else { _fallback(); } } /** * @dev returns the current admin * * requirements: * * - the caller must be the admin of the contract */ function admin() external ifAdmin returns (address) { return _admin; } /** * @dev returns the current implementation. * * requirements: * * - the caller must be the admin of the contract */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev upgrades the implementation of the proxy * * requirements: * * - the caller must be the admin of the contract */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev upgrade the implementation of the 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 * * requirements: * * - the caller must be the admin of the contract */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev makes sure the admin cannot access the fallback function */ function _beforeFallback() internal virtual override { if (msg.sender == _admin) { revert AccessDenied(); } super._beforeFallback(); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { PPM_RESOLUTION } from "./Constants.sol"; error AccessDenied(); error AlreadyExists(); error DoesNotExist(); error InvalidAddress(); error InvalidExternalAddress(); error InvalidFee(); error InvalidPool(); error InvalidPoolCollection(); error InvalidStakedBalance(); error InvalidToken(); error InvalidType(); error InvalidParam(); error NotEmpty(); error NotPayable(); error ZeroValue(); /** * @dev common utilities */ contract Utils { // allows execution by the caller only modifier only(address caller) { _only(caller); _; } function _only(address caller) internal view { if (msg.sender != caller) { revert AccessDenied(); } } // verifies that a value is greater than zero modifier greaterThanZero(uint256 value) { _greaterThanZero(value); _; } // error message binary size optimization function _greaterThanZero(uint256 value) internal pure { if (value == 0) { revert ZeroValue(); } } // validates an address - currently only checks that it isn't null modifier validAddress(address addr) { _validAddress(addr); _; } // error message binary size optimization function _validAddress(address addr) internal pure { if (addr == address(0)) { revert InvalidAddress(); } } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address addr) { _validExternalAddress(addr); _; } // error message binary size optimization function _validExternalAddress(address addr) internal view { if (addr == address(0) || addr == address(this)) { revert InvalidExternalAddress(); } } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { if (fee > PPM_RESOLUTION) { revert InvalidFee(); } } }
* @dev initializes an upgradeable proxy managed by `initAdmin`, backed by the implementation at `logic`, and optionally initialized with `data` as explained in {ERC1967Proxy-constructor}/ still store it to work with EIP-1967
) payable ERC1967Proxy(logic, data) validAddress(initAdmin) { _admin = initAdmin; _changeAdmin(initAdmin); }
285,250
[ 1, 6769, 3128, 392, 8400, 429, 2889, 7016, 635, 1375, 2738, 4446, 9191, 20732, 635, 326, 4471, 622, 1375, 28339, 9191, 471, 8771, 6454, 598, 1375, 892, 68, 487, 19765, 329, 316, 288, 654, 39, 3657, 9599, 3886, 17, 12316, 4004, 4859, 1707, 518, 358, 1440, 598, 512, 2579, 17, 3657, 9599, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 8843, 429, 4232, 39, 3657, 9599, 3886, 12, 28339, 16, 501, 13, 923, 1887, 12, 2738, 4446, 13, 288, 203, 3639, 389, 3666, 273, 1208, 4446, 31, 203, 203, 3639, 389, 3427, 4446, 12, 2738, 4446, 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 ]
./full_match/1/0xE13c0Ec78D283eb8Cca72Edd018a9c13AD0E002a/sources/MasterChefMod.sol
@notice Updates rewards for all pools by adding pending rewards. Can spend a lot of gas.
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { _updatePool(pid); } }
8,397,039
[ 1, 5121, 283, 6397, 364, 777, 16000, 635, 6534, 4634, 283, 6397, 18, 4480, 17571, 279, 17417, 434, 16189, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8039, 1891, 16639, 1435, 1071, 288, 203, 565, 2254, 5034, 769, 273, 2845, 966, 18, 2469, 31, 203, 565, 364, 261, 11890, 5034, 4231, 273, 374, 31, 4231, 411, 769, 31, 965, 6610, 13, 288, 203, 1377, 389, 2725, 2864, 12, 6610, 1769, 203, 565, 289, 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 ]
// SPDX-License-Identifier: Apache-2.0 /////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018-2021 Crossbar.io Technologies GmbH and contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; // import "openzeppelin-solidity/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * XBR Network (and XBR Network Proxies) SCs inherit from this base contract * to manage network administration and maintenance via Role-based Access * Control (RBAC). * The implementation for management comes from the OpenZeppelin RBAC library. */ contract XBRMaintained is AccessControl { // Create a new role identifier for the minter role bytes32 public constant MAINTAINER_ROLE = keccak256("MAINTAINER_ROLE"); /** * Event fired when a maintainer was added. * * @param account The account that was added as a maintainer. */ event MaintainerAdded(address indexed account); /** * Event fired when a maintainer was removed. * * @param account The account that was removed as a maintainer. */ event MaintainerRemoved(address indexed account); /// The constructor is internal (roles are managed by the OpenZeppelin base class). constructor () internal { _setupRole(MAINTAINER_ROLE, msg.sender); } /** * Modifier to require maintainer-role for the sender when calling a SC. */ modifier onlyMaintainer () { require(isMaintainer(msg.sender)); _; } /** * Check if the given address is currently a maintainer. * * @param account The account to check. * @return `true` if the account is maintainer, otherwise `false`. */ function isMaintainer (address account) public view returns (bool) { return hasRole(MAINTAINER_ROLE, account); } /** * Add a new maintainer to the list of maintainers. * * @param account The account to grant maintainer rights to. */ function addMaintainer (address account) public onlyMaintainer { _addMaintainer(account); } /** * Give away maintainer rights. */ function renounceMaintainer () public { _removeMaintainer(msg.sender); } function _addMaintainer (address account) internal { grantRole(MAINTAINER_ROLE, account); emit MaintainerAdded(account); } function _removeMaintainer (address account) internal { revokeRole(MAINTAINER_ROLE, account); emit MaintainerRemoved(account); } }
* Check if the given address is currently a maintainer. @param account The account to check. @return `true` if the account is maintainer, otherwise `false`./
function isMaintainer (address account) public view returns (bool) { return hasRole(MAINTAINER_ROLE, account); }
5,492,627
[ 1, 1564, 309, 326, 864, 1758, 353, 4551, 279, 11566, 1521, 18, 225, 2236, 1021, 2236, 358, 866, 18, 327, 1375, 3767, 68, 309, 326, 2236, 353, 11566, 1521, 16, 3541, 1375, 5743, 8338, 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, 445, 15707, 1598, 1521, 261, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28335, 12, 5535, 3217, 16843, 67, 16256, 16, 2236, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xC3174657977dc03360499Df3bc51f7e7a2a49daF/sources/DiscoverSpaceX.sol
FBTToken with Governance.
contract FBTToken is ERC20("FBT", "FBT"), Ownable { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } }
8,628,841
[ 1, 22201, 56, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 478, 38, 56, 1345, 353, 4232, 39, 3462, 2932, 22201, 56, 3113, 315, 22201, 56, 6, 3631, 14223, 6914, 288, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.7.3; pragma experimental ABIEncoderV2; import "./binary.sol"; import "./keccak512.sol"; import "./Prime.sol"; import "@openzeppelin/contracts-upgradeable/cryptography/MerkleProofUpgradeable.sol"; import "./MerkelRoot.sol"; // npm run merkelInit contract Ethash is MerkelRoots { using LittleEndian for bytes; using Keccak512 for bytes; using Prime for uint256; uint32 constant hashWords = 16; uint32 constant hashBytes = 64; uint32 constant datasetParents = 256; uint32 constant mixBytes = 128; // Width of mix uint32 constant loopAccesses = 64; // Number of accesses in hashimoto loop uint256 constant MAX256 = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant DATASET_BYTES_INIT = 1073741824; uint256 constant DATASET_BYTES_GROWTH = 8388608; // 2 ^ 23 uint256 constant EPOCH_LENGTH = 30000; function getFullSize(uint256 epoc) private pure returns (uint256) { uint256 sz = DATASET_BYTES_INIT + (DATASET_BYTES_GROWTH) * epoc; sz -= mixBytes; while (!(sz / mixBytes).probablyPrime(2)) { sz -= 2 * mixBytes; } return sz; } // fnv is an algorithm inspired by the FNV hash, which in some cases is used as // a non-associative substitute for XOR. Note that we multiply the prime with // the full 32-bit input, in contrast with the FNV-1 spec which multiplies the // prime with one byte (octet) in turn. function fnv(uint32 a, uint32 b) internal pure returns (uint32) { return (a * 0x01000193) ^ b; } // fnvHash mixes in data into mix using the ethash fnv method. function fnvHash32(uint32[] memory mix, uint32[] memory data) internal pure { assembly { let mixOffset := add(mix, 0x20) let mixValue := mload(mixOffset) let dataOffset := add(data, 0x20) let dataValue := mload(dataOffset) // fnv = return ((v1*0x01000193) ^ v2) & 0xFFFFFFFF; let fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 2 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 3 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 4 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 5 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 6 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 7 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 2 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 3 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 4 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 5 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 6 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 7 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) // ---- 1 dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) } } // hashimoto aggregates data from the full dataset in order to produce our final // value for a particular header hash and nonce. function hashimoto( bytes32 hash, uint64 nonce, uint64 size, bytes32[4][loopAccesses] memory cache, bytes32 rootHash, bytes32[][loopAccesses] memory proofs ) private pure returns (bytes32, bytes32) { // Calculate the number of theoretical rows (we use one buffer nonetheless) uint32 rows = uint32(size / mixBytes); // Combine header+nonce into a 64 byte seed bytes memory seed = new bytes(40); seed.copyBytes32(0, hash); seed.PutUint64(32, nonce); seed = seed.sha3_512(); uint32 seedHead = seed.Uint32(0); // Start the mix with replicated seed uint32[] memory mix = new uint32[](mixBytes / 4); for (uint32 i = 0; i < mix.length; i++) { mix[i] = seed.Uint32((i % 16) * 4); } // Mix in random dataset nodes uint32[] memory temp = new uint32[](mix.length); bytes32 root = rootHash; for (uint32 i = 0; i < loopAccesses; i++) { uint32 parent = fnv(i ^ seedHead, mix[i % mix.length]) % rows; //bytes32[4] memory dag = cache[2*parent]; bytes32[4] memory dag = cache[i]; uint256 dagIndex = 2 * parent; bytes32[] memory proof = proofs[i]; bytes32 leafHash = keccak256(abi.encodePacked(dagIndex, dag)); MerkleProofUpgradeable.verify(proof, root, leafHash); for (uint32 j = 0; j < dag.length; j++) { uint32 k = j * 8; uint256 data = uint256(dag[j]); temp[k] = LittleEndian.reverse(uint32(data >> (7 * 32))); temp[k + 1] = LittleEndian.reverse(uint32(data >> (6 * 32))); temp[k + 2] = LittleEndian.reverse(uint32(data >> (5 * 32))); temp[k + 3] = LittleEndian.reverse(uint32(data >> (4 * 32))); temp[k + 4] = LittleEndian.reverse(uint32(data >> (3 * 32))); temp[k + 5] = LittleEndian.reverse(uint32(data >> (2 * 32))); temp[k + 6] = LittleEndian.reverse(uint32(data >> (1 * 32))); temp[k + 7] = LittleEndian.reverse(uint32(data >> (0 * 32))); } fnvHash32(mix, temp); } // Compress mix for (uint32 i = 0; i < mix.length; i += 4) { mix[i / 4] = fnv( fnv(fnv(mix[i], mix[i + 1]), mix[i + 2]), mix[i + 3] ); } //mix = mix[:len(mix)/4]; uint256 digest = 0; for (uint32 i = 0; i < mix.length / 4; i++) { //binary.LittleEndian.PutUint32(digest[i*4:], val) digest <<= 32; uint32 val = mix[i]; digest |= uint256( ((val & 0xff) << 24) | (((val >> 8) & 0xff) << 16) | (((val >> 16) & 0xff) << 8) | (val >> 24) ); } return (bytes32(digest), keccak256(abi.encodePacked(seed, digest))); } function verifyEthash( bytes32 hash, uint64 nonce, uint64 number, bytes32[4][loopAccesses] memory cache, bytes32[][loopAccesses] memory proofs, uint256 difficulty, uint256 mixHash ) public pure returns (bool) { uint256 epoch = number / EPOCH_LENGTH; bytes32 rootHash = getRootHash(uint64(epoch)); uint256 size = getFullSize(epoch); (bytes32 mix, bytes32 _diff) = hashimoto( hash, nonce, uint64(size), cache, rootHash, proofs ); uint256 target = MAX256 / difficulty; // target = (2**256)/difficult; target += ((MAX256 % difficulty) + 1) / difficulty; return mix == bytes32(mixHash) && difficulty > 1 && target > uint256(_diff); } }
fnvHash mixes in data into mix using the ethash fnv method. fnv = return ((v1*0x01000193) ^ v2) & 0xFFFFFFFF; ---- 1 ---- 2 ---- 3 ---- 4 ---- 5 ---- 6 ---- 7 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 2 ---- 3 ---- 4 ---- 5 ---- 6 ---- 7 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1 ---- 1
function fnvHash32(uint32[] memory mix, uint32[] memory data) internal pure { assembly { let mixOffset := add(mix, 0x20) let mixValue := mload(mixOffset) let dataOffset := add(data, 0x20) let dataValue := mload(dataOffset) let fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) dataOffset := add(dataOffset, 0x20) dataValue := mload(dataOffset) mixOffset := add(mixOffset, 0x20) mixValue := mload(mixOffset) fnvValue := and( xor(mul(mixValue, 0x01000193), dataValue), 0xFFFFFFFF ) mstore(mixOffset, fnvValue) } }
7,281,369
[ 1, 4293, 90, 2310, 6843, 281, 316, 501, 1368, 6843, 1450, 326, 13750, 961, 2295, 90, 707, 18, 2295, 90, 273, 327, 14015, 90, 2163, 92, 1611, 13304, 11180, 13, 3602, 331, 22, 13, 473, 374, 28949, 31, 27927, 404, 27927, 576, 27927, 890, 27927, 1059, 27927, 1381, 27927, 1666, 27927, 2371, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 576, 27927, 890, 27927, 1059, 27927, 1381, 27927, 1666, 27927, 2371, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 27927, 404, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2295, 90, 2310, 1578, 12, 11890, 1578, 8526, 3778, 6843, 16, 2254, 1578, 8526, 3778, 501, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 565, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 6843, 2335, 519, 527, 12, 14860, 16, 374, 92, 3462, 13, 203, 5411, 2231, 6843, 620, 519, 312, 945, 12, 14860, 2335, 13, 203, 5411, 2231, 501, 2335, 519, 527, 12, 892, 16, 374, 92, 3462, 13, 203, 5411, 2231, 29965, 519, 312, 945, 12, 892, 2335, 13, 203, 203, 5411, 2231, 2295, 90, 620, 519, 471, 12, 203, 7734, 17586, 12, 16411, 12, 14860, 620, 16, 374, 92, 1611, 13304, 11180, 3631, 29965, 3631, 203, 7734, 374, 28949, 203, 5411, 262, 203, 5411, 312, 2233, 12, 14860, 2335, 16, 2295, 90, 620, 13, 203, 203, 5411, 501, 2335, 519, 527, 12, 892, 2335, 16, 374, 92, 3462, 13, 203, 5411, 29965, 519, 312, 945, 12, 892, 2335, 13, 203, 5411, 6843, 2335, 519, 527, 12, 14860, 2335, 16, 374, 92, 3462, 13, 203, 5411, 6843, 620, 519, 312, 945, 12, 14860, 2335, 13, 203, 5411, 2295, 90, 620, 519, 471, 12, 203, 7734, 17586, 12, 16411, 12, 14860, 620, 16, 374, 92, 1611, 13304, 11180, 3631, 29965, 3631, 203, 7734, 374, 28949, 203, 5411, 262, 203, 5411, 312, 2233, 12, 14860, 2335, 16, 2295, 90, 620, 13, 203, 203, 5411, 501, 2335, 519, 527, 12, 892, 2335, 16, 374, 92, 3462, 13, 203, 5411, 29965, 519, 312, 945, 12, 892, 2335, 13, 203, 5411, 6843, 2335, 519, 527, 2 ]
pragma solidity 0.5.6; // --------------------------------------------------------------------------- // Message_Transport // --------------------------------------------------------------------------- //import './SafeMath.sol'; /* Overflow protected math functions */ contract SafeMath { /** constructor */ constructor() public { } /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) pure internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) pure internal returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) pure internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } //import './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; } } contract MessageTransport is SafeMath, Ownable { // ------------------------------------------------------------------------- // events // etherscan.io's Event Log API does not have an option to match multiple values // in an individual topic. so in order to match any one of three message id's we // duplicate the message id into 3 topic position. // ------------------------------------------------------------------------- event InviteEvent(address indexed _toAddr, address indexed _fromAddr); event MessageEvent(uint indexed _id1, uint indexed _id2, uint indexed _id3, address _fromAddr, address _toAddr, address _via, uint _txCount, uint _rxCount, uint _attachmentIdx, uint _ref, bytes message); event MessageTxEvent(address indexed _fromAddr, uint indexed _txCount, uint _id); event MessageRxEvent(address indexed _toAddr, uint indexed _rxCount, uint _id); // ------------------------------------------------------------------------- // Account structure // there is a single account structure for all account types // ------------------------------------------------------------------------- struct Account { bool isValid; uint messageFee; // pay this much for every non-spam message sent to this account uint spamFee; // pay this much for every spam message sent to this account uint feeBalance; // includes spam and non-spam fees uint recvMessageCount; // total messages received uint sentMessageCount; // total messages sent bytes publicKey; // encryption parameter bytes encryptedPrivateKey; // encryption parameter mapping (address => uint256) peerRecvMessageCount; mapping (uint256 => uint256) recvIds; mapping (uint256 => uint256) sentIds; } // ------------------------------------------------------------------------- // data storage // ------------------------------------------------------------------------- bool public isLocked; address public tokenAddr; uint public messageCount; uint public retainedFeesBalance; mapping (address => bool) public trusted; mapping (address => Account) public accounts; // ------------------------------------------------------------------------- // modifiers // ------------------------------------------------------------------------- modifier trustedOnly { require(trusted[msg.sender] == true, "trusted only"); _; } // ------------------------------------------------------------------------- // MessageTransport constructor // ------------------------------------------------------------------------- constructor(address _tokenAddr) public { tokenAddr = _tokenAddr; } function setTrust(address _trustedAddr, bool _trust) public onlyOwner { trusted[_trustedAddr] = _trust; } // ------------------------------------------------------------------------- // register a message account // the decryption key for the encryptedPrivateKey should be guarded with the // same secrecy and caution as the ethereum private key. in fact the decryption // key should never be tranmitted or stored at all -- but always derived from a // message signature; that is, through metamask. // ------------------------------------------------------------------------- function register(uint256 _messageFee, uint256 _spamFee, bytes memory _publicKey, bytes memory _encryptedPrivateKey) public { Account storage _account = accounts[msg.sender]; require(_account.isValid == false, "account already registered"); _account.publicKey = _publicKey; _account.encryptedPrivateKey = _encryptedPrivateKey; _account.isValid = true; _modifyAccount(_account, _messageFee, _spamFee); } function modifyAccount(uint256 _messageFee, uint256 _spamFee) public { Account storage _account = accounts[msg.sender]; require(_account.isValid == true, "not registered"); _modifyAccount(_account, _messageFee, _spamFee); } function _modifyAccount(Account storage _account, uint256 _messageFee, uint256 _spamFee) internal { _account.messageFee = _messageFee; _account.spamFee = _spamFee; } // ------------------------------------------------------------------------- // get the number of messages that have been sent from one peer to another // ------------------------------------------------------------------------- function getPeerMessageCount(address _from, address _to) public view returns(uint256 _messageCount) { Account storage _account = accounts[_to]; _messageCount = _account.peerRecvMessageCount[_from]; } // ------------------------------------------------------------------------- // get _maxResults message id's of received messages // note that array will always have _maxResults entries. ignore messageID = 0 // ------------------------------------------------------------------------- function getRecvMsgs(address _to, uint256 _startIdx, uint256 _maxResults) public view returns(uint256 _idx, uint256[] memory _messageIds) { uint _count = 0; Account storage _recvAccount = accounts[_to]; uint256 _recvMessageCount = _recvAccount.recvMessageCount; _messageIds = new uint256[](_maxResults); mapping(uint256 => uint256) storage _recvIds = _recvAccount.recvIds; //first messageID is at recvIds[0]; for (_idx = _startIdx; _idx < _recvMessageCount; ++_idx) { _messageIds[_count] = _recvIds[_idx]; if (block.gaslimit >= _maxResults) //injected CONTRACT AFFECTED BY MINERS break; } } // ------------------------------------------------------------------------- // get _maxResults message id's of sent messages // note that array will always have _maxResults entries. ignore messageID = 0 // ------------------------------------------------------------------------- function getSentMsgs(address _from, uint256 _startIdx, uint256 _maxResults) public view returns(uint256 _idx, uint256[] memory _messageIds) { uint _count = 0; Account storage _sentAccount = accounts[_from]; uint256 _sentMessageCount = _sentAccount.sentMessageCount; _messageIds = new uint256[](_maxResults); mapping(uint256 => uint256) storage _sentIds = _sentAccount.sentIds; //note first messageID is at recvIds[0]; for (_idx = _startIdx; _idx < _sentMessageCount; ++_idx) { _messageIds[_count] = _sentIds[_idx]; if (block.timestamp >= _maxResults) //injected CONTRACT AFFECTED BY MINERS break; } } // ------------------------------------------------------------------------- // get the required fee in order to send a message (or spam message) // the second version is handy for calls from partner contract(s) // ------------------------------------------------------------------------- function getFee(address _toAddr) public view returns(uint256 _fee) { Account storage _sendAccount = accounts[msg.sender]; Account storage _recvAccount = accounts[_toAddr]; if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS _fee = _recvAccount.spamFee; else _fee = _recvAccount.messageFee; } function getFee(address _fromAddr, address _toAddr) public view trustedOnly returns(uint256 _fee) { Account storage _sendAccount = accounts[_fromAddr]; Account storage _recvAccount = accounts[_toAddr]; if (block.gaslimit == 0) //injected CONTRACT AFFECTED BY MINERS _fee = _recvAccount.spamFee; else _fee = _recvAccount.messageFee; } // ------------------------------------------------------------------------- // send message // the via address is set to the address of the trusted contract (or zero in // case the fromAddr is msg.sender). in this way a DApp can indicate the via // address to the recipient when the message was not sent directly from the // sender. // ------------------------------------------------------------------------- function sendMessage(address _toAddr, uint attachmentIdx, uint _ref, bytes memory _message) public payable returns (uint _messageId) { uint256 _noDataLength = 4 + 32 + 32 + 32 + 64; _messageId = doSendMessage(_noDataLength, msg.sender, _toAddr, address(0), attachmentIdx, _ref, _message); } function sendMessage(address _fromAddr, address _toAddr, uint attachmentIdx, uint _ref, bytes memory _message) public payable trustedOnly returns (uint _messageId) { uint256 _noDataLength = 4 + 32 + 32 + 32 + 32 + 64; _messageId = doSendMessage(_noDataLength, _fromAddr, _toAddr, msg.sender, attachmentIdx, _ref, _message); } function doSendMessage(uint256 _noDataLength, address _fromAddr, address _toAddr, address _via, uint attachmentIdx, uint _ref, bytes memory _message) internal returns (uint _messageId) { Account storage _sendAccount = accounts[_fromAddr]; Account storage _recvAccount = accounts[_toAddr]; require(_sendAccount.isValid == true, "sender not registered"); require(_recvAccount.isValid == true, "recipient not registered"); //if message text is empty then no fees are necessary, and we don't create a log entry. //after you introduce yourself to someone this way their subsequent message to you won't //incur your spamFee. if (block.timestamp > _noDataLength) { //injected CONTRACT AFFECTED BY MINERS if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS require(msg.value >= _recvAccount.spamFee, "spam fee is insufficient"); else require(msg.value >= _recvAccount.messageFee, "fee is insufficient"); messageCount = safeAdd(messageCount, 1); _recvAccount.recvIds[_recvAccount.recvMessageCount] = messageCount; _sendAccount.sentIds[_sendAccount.sentMessageCount] = messageCount; _recvAccount.recvMessageCount = safeAdd(_recvAccount.recvMessageCount, 1); _sendAccount.sentMessageCount = safeAdd(_sendAccount.sentMessageCount, 1); emit MessageEvent(messageCount, messageCount, messageCount, _fromAddr, _toAddr, _via, _sendAccount.sentMessageCount, _recvAccount.recvMessageCount, attachmentIdx, _ref, _message); emit MessageTxEvent(_fromAddr, _sendAccount.sentMessageCount, messageCount); emit MessageRxEvent(_toAddr, _recvAccount.recvMessageCount, messageCount); //return message id, which a calling function might want to log _messageId = messageCount; } else { emit InviteEvent(_toAddr, _fromAddr); _messageId = 0; } uint _retainAmount = safeMul(msg.value, 30) / 100; retainedFeesBalance = safeAdd(retainedFeesBalance, _retainAmount); _recvAccount.feeBalance = safeAdd(_recvAccount.feeBalance, safeSub(msg.value, _retainAmount)); _recvAccount.peerRecvMessageCount[_fromAddr] = safeAdd(_recvAccount.peerRecvMessageCount[_fromAddr], 1); } // ------------------------------------------------------------------------- // withdraw accumulated message & spam fees // ------------------------------------------------------------------------- function withdraw() public { Account storage _account = accounts[msg.sender]; uint _amount = _account.feeBalance; _account.feeBalance = 0; msg.sender.transfer(_amount); } // ------------------------------------------------------------------------- // pay retained fees funds to token contract; burn half. // ------------------------------------------------------------------------- function withdrawRetainedFees() public { uint _amount = retainedFeesBalance / 2; address(0).transfer(_amount); _amount = safeSub(retainedFeesBalance, _amount); retainedFeesBalance = 0; (bool paySuccess, ) = tokenAddr.call.value(_amount)(""); require(paySuccess, "failed to transfer fees"); } }
------------------------------------------------------------------------- MessageTransport constructor -------------------------------------------------------------------------
constructor(address _tokenAddr) public { tokenAddr = _tokenAddr; }
14,043,791
[ 1, 5802, 8567, 225, 2350, 6568, 3885, 8879, 788, 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, 225, 3885, 12, 2867, 389, 2316, 3178, 13, 1071, 288, 203, 565, 1147, 3178, 273, 389, 2316, 3178, 31, 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, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-03 */ // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.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; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap/lib/contracts/libraries/Babylonian.sol pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // File: @uniswap/lib/contracts/libraries/FixedPoint.sol pragma solidity >=0.4.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // File: contracts/external/UniswapV2OracleLibrary.sol pragma solidity >=0.5.0; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices(address pair) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp, uint112 reserve0, uint112 reserve1) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values uint32 blockTimestampLast; (reserve0, reserve1, blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File: contracts/external/UniswapV2Library.sol pragma solidity >=0.5.0; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } } // File: contracts/external/Require.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // File: contracts/oracle/IOracle.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract IOracle { function capture() public returns (Decimal.D256 memory, bool); } // File: contracts/oracle/IUSDC.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract IUSDC { function isBlacklisted(address _account) external view returns (bool); } // File: contracts/Constants.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 5; /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e22; // 10,000 VSD address private constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant CURRENT_EPOCH_OFFSET = 0; uint256 private constant CURRENT_EPOCH_START = 1612324800; uint256 private constant CURRENT_EPOCH_PERIOD = 28800; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 9; // 9 epochs uint256 private constant GOVERNANCE_EXPIRATION = 2; // 2 + 1 epochs uint256 private constant GOVERNANCE_QUORUM = 10e16; // 10% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE = 1e20; // 100 VSD uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 15; // 15 epochs fluid /* Market */ uint256 private constant COUPON_EXPIRATION = 30; // 10 days uint256 private constant DEBT_RATIO_CAP = 15e16; // 15% /* Regulator */ uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 6e16; // 6% uint256 private constant SUPPLY_INCREASE_FUND_RATIO = 1500; // 15% uint256 private constant SUPPLY_INCREASE_PRICE_THRESHOLD = 105e16; // 1.05 uint256 private constant SUPPLY_INCREASE_PRICE_TARGET = 105e16; // 1.05 uint256 private constant SUPPLY_DECREASE_PRICE_THRESHOLD = 95e16; // 0.95 uint256 private constant SUPPLY_DECREASE_PRICE_TARGET = 95e16; // 0.95 /* Collateral */ uint256 private constant REDEMPTION_RATE = 9500; // 95% uint256 private constant FUND_DEV_PCT = 70; // 70% uint256 private constant COLLATERAL_RATIO = 9000; // 90% /* Deployed */ address private constant TREASURY_ADDRESS = address(0x4b23854ed531f82Dfc9888aF54076aeC5F92DE07); address private constant DEV_ADDRESS = address(0x5bC47D40F69962d1a9Db65aC88f4b83537AF5Dc2); address private constant MINTER_ADDRESS = address(0x6Ff1DbcF2996D8960E24F16C193EA42853995d32); address private constant GOVERNOR = address(0xB64A5630283CCBe0C3cbF887a9f7B9154aEf38c3); /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getDaiAddress() internal pure returns (address) { return DAI; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getCurrentEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: CURRENT_EPOCH_OFFSET, start: CURRENT_EPOCH_START, period: CURRENT_EPOCH_PERIOD }); } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceExpiration() internal pure returns (uint256) { return GOVERNANCE_EXPIRATION; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_QUORUM}); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_PROPOSAL_THRESHOLD}); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_SUPER_MAJORITY}); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentive() internal pure returns (uint256) { return ADVANCE_INCENTIVE; } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getCouponExpiration() internal pure returns (uint256) { return COUPON_EXPIRATION; } function getDebtRatioCap() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: DEBT_RATIO_CAP}); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: COUPON_SUPPLY_CHANGE_LIMIT}); } function getSupplyIncreaseFundRatio() internal pure returns (uint256) { return SUPPLY_INCREASE_FUND_RATIO; } function getSupplyIncreasePriceThreshold() internal pure returns (uint256) { return SUPPLY_INCREASE_PRICE_THRESHOLD; } function getSupplyIncreasePriceTarget() internal pure returns (uint256) { return SUPPLY_INCREASE_PRICE_TARGET; } function getSupplyDecreasePriceThreshold() internal pure returns (uint256) { return SUPPLY_DECREASE_PRICE_THRESHOLD; } function getSupplyDecreasePriceTarget() internal pure returns (uint256) { return SUPPLY_DECREASE_PRICE_TARGET; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } function getDevAddress() internal pure returns (address) { return DEV_ADDRESS; } function getMinterAddress() internal pure returns (address) { return MINTER_ADDRESS; } function getFundDevPct() internal pure returns (uint256) { return FUND_DEV_PCT; } function getRedemptionRate() internal pure returns (uint256) { return REDEMPTION_RATE; } function getGovernor() internal pure returns (address) { return GOVERNOR; } function getCollateralRatio() internal pure returns (uint256) { return COLLATERAL_RATIO; } } // File: contracts/oracle/Oracle.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; /* Only works for stablecoin at the monent */ contract Oracle is IOracle { struct PairData { uint256 _cumulative; uint256 _index; uint256 _reserve; uint256 _decMultiplier; uint32 _timestamp; bool _initialized; } using Decimal for Decimal.D256; using SafeMath for uint256; bytes32 private constant FILE = "Oracle"; mapping(address => PairData) _poolMap; address[] _poolList; address _dollar; address _owner; constructor(address dollar) public { _owner = msg.sender; _dollar = dollar; } /** * Owner */ function addPool(address pool, uint256 decMultiplier) onlyOwner public { uint256 len = _poolList.length; for (uint256 i = 0; i < len; i++) { Require.that( pool != _poolList[i], FILE, "Must not in the pool" ); } _poolList.push(pool); _poolMap[pool]._decMultiplier = decMultiplier; } function transferOwner(address newOwner) onlyOwner public { _owner = newOwner; } /** * Trades/Liquidity: (1) Initializes reserve and blockTimestampLast (can calculate a price) * (2) Has non-zero cumulative prices * * Steps: (1) Captures a reference blockTimestampLast * (2) First reported value */ function capture() public onlyOwner returns (Decimal.D256 memory, bool) { uint256 length = _poolList.length; uint256 totalReserve = 0; uint256 prevTotalReserve = 0; Decimal.D256 memory totalPriceRerseve = Decimal.zero(); bool valid = false; for (uint256 i = 0; i < length; i++) { address pair = _poolList[i]; if (_poolMap[pair]._initialized) { ( Decimal.D256 memory price, uint256 prevReserve, uint256 reserve, bool valid0 ) = updateOracleFor(IUniswapV2Pair(pair)); if (valid0) { totalReserve = totalReserve.add(reserve); totalPriceRerseve = totalPriceRerseve.add(price.mul(reserve)); prevTotalReserve = prevTotalReserve.add(prevReserve); valid = true; } } else { initializeOracleFor(IUniswapV2Pair(pair)); } } if (valid && totalReserve >= Constants.getOracleReserveMinimum() && prevTotalReserve >= Constants.getOracleReserveMinimum()) { return (totalPriceRerseve.div(totalReserve), true); } return (Decimal.one(), false); } function getPrice() public view returns (Decimal.D256 memory, bool) { uint256 length = _poolList.length; uint256 totalReserve = 0; uint256 prevTotalReserve = 0; Decimal.D256 memory totalPriceRerseve = Decimal.zero(); bool valid = false; for (uint256 i = 0; i < length; i++) { address pair = _poolList[i]; if (_poolMap[pair]._initialized) { ( Decimal.D256 memory price, , , uint256 reserve ) = getPriceFor(IUniswapV2Pair(pair)); totalReserve = totalReserve.add(reserve); totalPriceRerseve = totalPriceRerseve.add(price.mul(reserve)); prevTotalReserve = prevTotalReserve.add(_poolMap[pair]._reserve); valid = true; } } if (valid && totalReserve >= Constants.getOracleReserveMinimum() && prevTotalReserve >= Constants.getOracleReserveMinimum()) { return (totalPriceRerseve.div(totalReserve), true); } return (Decimal.one(), false); } function initializeOracleFor(IUniswapV2Pair pair) private { uint256 index = pair.token0() == address(_dollar) ? 0 : 1; uint256 priceCumulative = index == 0 ? pair.price0CumulativeLast() : pair.price1CumulativeLast(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = pair.getReserves(); if(reserve0 != 0 && reserve1 != 0 && blockTimestampLast != 0) { PairData storage data = _poolMap[address(pair)]; data._cumulative = priceCumulative; data._timestamp = blockTimestampLast; data._initialized = true; data._reserve = index == 0 ? reserve0 : reserve1; data._index = index; } } function updateOracleFor(IUniswapV2Pair pair) private returns (Decimal.D256 memory, uint256, uint256, bool) { (Decimal.D256 memory price, uint32 blockTimestamp, uint256 priceCumulative, uint112 reserve) = getPriceFor(pair); PairData storage data = _poolMap[address(pair)]; // Make sure the timestamp diff is large enough to avoid price manipulation. if (blockTimestamp <= Constants.getCurrentEpochStrategy().period.div(2).add(data._timestamp)) { return (Decimal.one(), 0, 0, false); } uint256 prevReserve = data._reserve; data._reserve = reserve; data._timestamp = blockTimestamp; data._cumulative = priceCumulative; return (price, prevReserve, reserve, true); } function getPriceFor(IUniswapV2Pair pair) private view returns (Decimal.D256 memory, uint32, uint256, uint112) { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp, uint112 reserve0, uint112 reserve1) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); PairData storage data = _poolMap[address(pair)]; uint32 timeElapsed = blockTimestamp - data._timestamp; // overflow is desired uint256 priceCumulative = data._index == 0 ? price0Cumulative : price1Cumulative; uint112 reserve = data._index == 0 ? reserve0 : reserve1; Decimal.D256 memory price = Decimal.ratio((priceCumulative - data._cumulative) / timeElapsed, 2**112); return (price.mul(data._decMultiplier), blockTimestamp, priceCumulative, reserve); } modifier onlyOwner() { Require.that( msg.sender == address(_owner), FILE, "Not owner" ); _; } }
overflow is desired
uint32 timeElapsed = blockTimestamp - data._timestamp;
6,752,228
[ 1, 11512, 353, 6049, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1578, 813, 28827, 273, 1203, 4921, 300, 501, 6315, 5508, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * 彡(^)(^) * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * 彡(゚)(゚) * @title AidEvaCoin * @author AidEvaCoin * @dev AidEvaCoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract AidEvaCoin is ERC223, Ownable { using SafeMath for uint256; string public name = "AidEvaCoin"; string public symbol = "AIVA"; uint8 public decimals = 8; uint256 public totalSupply = 30e9 * 1e18; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function AidEvaCoin() public { balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e18); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e18); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn't work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(owner, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } } /* *(`・ω・)(`・ω・´)(・ω・´) * Created by Tsuchinoko *(´・ω・)(´・ω・`)(・ω・`) */
* 彡(゚)(゚) @title AidEvaCoin @author AidEvaCoin @dev AidEvaCoin is an ERC223 Token with ERC20 functions and events Fully backward compatible with ERC20/
contract AidEvaCoin is ERC223, Ownable { using SafeMath for uint256; string public name = "AidEvaCoin"; string public symbol = "AIVA"; uint8 public decimals = 8; uint256 public totalSupply = 30e9 * 1e18; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); function AidEvaCoin() public { balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; return transferToAddress(_to, _value, _data); } } } else { function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); return transferToAddress(_to, _value, _data); } } } else { function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); return transferToAddress(_to, _value, empty); } } function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); return transferToAddress(_to, _value, empty); } } } else { function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e18); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e18); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e18); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e18); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e18); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(owner, msg.sender, distributeAmount); } function() payable public { autoDistribute(); } }
14,454,065
[ 1, 166, 126, 99, 12, 176, 127, 258, 21433, 176, 127, 258, 13, 225, 432, 350, 41, 15304, 27055, 225, 432, 350, 41, 15304, 27055, 225, 432, 350, 41, 15304, 27055, 353, 392, 4232, 39, 3787, 23, 3155, 598, 4232, 39, 3462, 4186, 471, 2641, 1377, 11692, 93, 12555, 7318, 598, 4232, 39, 3462, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 432, 350, 41, 15304, 27055, 353, 4232, 39, 3787, 23, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 1071, 508, 273, 315, 37, 350, 41, 15304, 27055, 14432, 203, 565, 533, 1071, 3273, 273, 315, 37, 8188, 37, 14432, 203, 565, 2254, 28, 1071, 15105, 273, 1725, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 273, 5196, 73, 29, 380, 404, 73, 2643, 31, 203, 565, 2254, 5034, 1071, 25722, 6275, 273, 374, 31, 203, 565, 1426, 1071, 312, 474, 310, 10577, 273, 629, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 12, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 12810, 3032, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 7186, 18729, 950, 31, 203, 377, 203, 565, 871, 478, 9808, 42, 19156, 12, 2867, 8808, 1018, 16, 1426, 12810, 1769, 203, 565, 871, 3488, 329, 42, 19156, 12, 2867, 8808, 1018, 16, 2254, 5034, 8586, 1769, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 490, 474, 12, 2867, 8808, 358, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 490, 474, 10577, 5621, 203, 203, 203, 565, 445, 432, 350, 41, 15304, 27055, 1435, 1071, 288, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 565, 289, 203, 203, 2 ]
pragma solidity ^0.5.16; import "../interfaces/IBlockRewardHbbft.sol"; import "../interfaces/IStakingHbbft.sol"; import "../interfaces/IValidatorSetHbbft.sol"; import "../upgradeability/UpgradeableOwned.sol"; import "../libs/SafeMath.sol"; /// @dev Implements staking and withdrawal logic. contract StakingHbbftBase is UpgradeableOwned, IStakingHbbft { using SafeMath for uint256; // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables and do not change their types! address[] internal _pools; address[] internal _poolsInactive; address[] internal _poolsToBeElected; address[] internal _poolsToBeRemoved; uint256[] internal _poolsLikelihood; uint256 internal _poolsLikelihoodSum; mapping(address => address[]) internal _poolDelegators; mapping(address => address[]) internal _poolDelegatorsInactive; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch; /// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). uint256 public candidateMinStake; /// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). uint256 public delegatorMinStake; /// @dev The snapshot of the amount staked into the specified pool by the specified delegator /// before the specified staking epoch. Used by the `claimReward` function. /// The first parameter is the pool staking address, the second one is delegator's address, /// the third one is staking epoch number. mapping(address => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot; /// @dev The current amount of staking coins ordered for withdrawal from the specified /// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions. /// The first parameter is the pool staking address, the second one is the staker address. mapping(address => mapping(address => uint256)) public orderedWithdrawAmount; /// @dev The current total amount of staking coins ordered for withdrawal from /// the specified pool by all of its stakers. Pool staking address is accepted as a parameter. mapping(address => uint256) public orderedWithdrawAmountTotal; /// @dev The number of the staking epoch during which the specified staker ordered /// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function /// to allow the ordered amount to be claimed only in future staking epochs. The first parameter /// is the pool staking address, the second one is the staker address. mapping(address => mapping(address => uint256)) public orderWithdrawEpoch; /// @dev The delegator's index in the array returned by the `poolDelegators` getter. /// Used by the `_removePoolDelegator` internal function. The first parameter is a pool staking address. /// The second parameter is delegator's address. /// If the value is zero, it may mean the array doesn't contain the delegator. /// Check if the delegator is in the array using the `poolDelegators` getter. mapping(address => mapping(address => uint256)) public poolDelegatorIndex; /// @dev The delegator's index in the `poolDelegatorsInactive` array. /// Used by the `_removePoolDelegatorInactive` internal function. /// A delegator is considered inactive if they have withdrawn their stake from /// the specified pool but haven't yet claimed an ordered amount. /// The first parameter is a pool staking address. The second parameter is delegator's address. mapping(address => mapping(address => uint256)) public poolDelegatorInactiveIndex; /// @dev The pool's index in the array returned by the `getPoolsInactive` getter. /// Used by the `_removePoolInactive` internal function. The pool staking address is accepted as a parameter. mapping(address => uint256) public poolInactiveIndex; /// @dev The pool's index in the array returned by the `getPools` getter. /// Used by the `_removePool` internal function. A pool staking address is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `isPoolActive` getter. mapping(address => uint256) public poolIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter. /// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions. /// The pool staking address is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeElected` getter. mapping(address => uint256) public poolToBeElectedIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter. /// Used by the `_deletePoolToBeRemoved` internal function. /// The pool staking address is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeRemoved` getter. mapping(address => uint256) public poolToBeRemovedIndex; /// @dev A boolean flag indicating whether the reward was already taken /// from the specified pool by the specified staker for the specified staking epoch. /// The first parameter is the pool staking address, the second one is staker's address, /// the third one is staking epoch number. mapping(address => mapping(address => mapping(uint256 => bool))) public rewardWasTaken; /// @dev The amount of coins currently staked into the specified pool by the specified /// staker. Doesn't include the amount ordered for withdrawal. /// The first parameter is the pool staking address, the second one is the staker address. mapping(address => mapping(address => uint256)) public stakeAmount; /// @dev The number of staking epoch before which the specified delegator placed their first /// stake into the specified pool. If this is equal to zero, it means the delegator never /// staked into the specified pool. The first parameter is the pool staking address, /// the second one is delegator's address. mapping(address => mapping(address => uint256)) public stakeFirstEpoch; /// @dev The number of staking epoch before which the specified delegator withdrew their stake /// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means /// the delegator still has some stake in the specified pool. The first parameter is the pool /// staking address, the second one is delegator's address. mapping(address => mapping(address => uint256)) public stakeLastEpoch; /// @dev The duration period (in blocks) at the end of staking epoch during which /// participants are not allowed to stake/withdraw/order/claim their staking coins. uint256 public stakingWithdrawDisallowPeriod; /// @dev The serial number of the current staking epoch. uint256 public stakingEpoch; /// @dev The fixed duration of each staking epoch before KeyGen starts i.e. /// before the upcoming ("pending") validators are selected. uint256 public stakingFixedEpochDuration; /// @dev Length of the timeframe in seconds for the transition to the new validator set. uint256 public stakingTransitionTimeframeLength; /// @dev The timestamp of the last block of the the previous epoch. /// The timestamp of the current epoch must be '>=' than this. uint256 public stakingEpochStartTime; /// @dev the blocknumber of the first block in this epoch. /// this is mainly used for a historic lookup in the key gen history to read out the /// ACKS and PARTS so a client is able to verify an epoch, even in the case that /// the transition to the next epoch has already started, /// and the information of the old keys is not available anymore. uint256 public stakingEpochStartBlock; /// @dev the extra time window pending validators have to write /// to write their honey badger key shares. /// this value is increased in response to a failed key generation event, /// if one or more validators miss out writing their key shares. uint256 public currentKeyGenExtraTimeWindow; /// @dev Returns the total amount of staking coins currently staked into the specified pool. /// Doesn't include the amount ordered for withdrawal. /// The pool staking address is accepted as a parameter. mapping(address => uint256) public stakeAmountTotal; /// @dev The address of the `ValidatorSetHbbft` contract. IValidatorSetHbbft public validatorSetContract; struct PoolInfo { bytes publicKey; bytes16 internetAddress; } mapping (address => PoolInfo) public poolInfo; // ============================================== Constants ======================================================= /// @dev The max number of candidates (including validators). This limit was determined through stress testing. uint256 public constant MAX_CANDIDATES = 3000; // ================================================ Events ======================================================== /// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified /// amount of requested coins from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` withdrew the `amount`. /// @param staker The address of the staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the claim was made. /// @param amount The withdrawal amount. event ClaimedOrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); /// @dev Emitted by the `moveStake` function to signal the staker moved the specified /// amount of stake from one pool to another during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` moved the stake. /// @param toPoolStakingAddress The destination pool where the `staker` moved the stake. /// @param staker The address of the staker who moved the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved. /// @param amount The stake amount which was moved. event MovedStake( address fromPoolStakingAddress, address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); /// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the /// specified amount of their stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` ordered a withdrawal of the `amount`. /// @param staker The address of the staker that ordered the withdrawal of the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the order was made. /// @param amount The ordered withdrawal amount. Can be either positive or negative. /// See the `orderWithdraw` function. event OrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, int256 amount ); /// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified /// amount for the specified pool during the specified staking epoch. /// @param toPoolStakingAddress The pool in which the `staker` placed the stake. /// @param staker The address of the staker that placed the stake. /// @param stakingEpoch The serial number of the staking epoch during which the stake was made. /// @param amount The stake amount. event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); /// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified /// amount of a stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` withdrew the `amount`. /// @param staker The address of staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made. /// @param amount The withdrawal amount. event WithdrewStake( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); // ============================================== Modifiers ======================================================= /// @dev Ensures the transaction gas price is not zero. modifier gasPriceIsValid() { require(tx.gasprice != 0, "GasPrice is 0"); _; } /// @dev Ensures the caller is the BlockRewardHbbft contract address. modifier onlyBlockRewardContract() { require(msg.sender == validatorSetContract.blockRewardContract(), "Only BlockReward"); _; } /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized(), "Contract not initialized"); _; } /// @dev Ensures the caller is the ValidatorSetHbbft contract address. modifier onlyValidatorSetContract() { require(msg.sender == address(validatorSetContract), "Only ValidatorSet"); _; } // =============================================== Setters ======================================================== /// @dev Fallback function. Prevents direct sending native coins to this contract. function () payable external { revert("Not payable"); } /// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter) and /// moves the specified amount of staking coins from the candidate's staking address /// to the candidate's pool. A participant calls this function using their staking address when /// they want to create a pool. This is a wrapper for the `stake` function. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `msg.sender`. function addPool(address _miningAddress, bytes calldata _publicKey, bytes16 _ip) external payable gasPriceIsValid { address stakingAddress = msg.sender; uint256 amount = msg.value; validatorSetContract.setStakingAddress(_miningAddress, stakingAddress); // The staking address and the staker are the same. _stake(stakingAddress, stakingAddress, amount); poolInfo[stakingAddress].publicKey = _publicKey; poolInfo[stakingAddress].internetAddress = _ip; } /// @dev set's the pool info for a specific ethereum address. /// @param _publicKey public key of the (future) signing address. /// @param _ip (optional) IPV4 address of a running Node Software or Proxy. /// Stores the supplied data for a staking (pool) address. /// This function is external available without security checks, /// since no array operations are used in the implementation, /// this allows the flexibility to set the pool information before /// adding the stake to the pool. function setPoolInfo(bytes calldata _publicKey, bytes16 _ip) external { poolInfo[msg.sender].publicKey = _publicKey; poolInfo[msg.sender].internetAddress = _ip; } /// @dev Increments the serial number of the current staking epoch. /// Called by the `ValidatorSetHbbft.newValidatorSet` at the last block of the finished staking epoch. function incrementStakingEpoch() external onlyValidatorSetContract { stakingEpoch++; currentKeyGenExtraTimeWindow = 0; } /// @dev Initializes the network parameters. /// Can only be called by the constructor of the `InitializerHbbft` contract or owner. /// @param _validatorSetContract The address of the `ValidatorSetHbbft` contract. /// @param _initialStakingAddresses The array of initial validators' staking addresses. /// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei. /// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei. /// @param _stakingFixedEpochDuration The fixed duration of each epoch before keyGen starts. /// @param _stakingTransitionTimeframeLength Length of the timeframe in seconds for the transition /// to the new validator set. /// @param _stakingWithdrawDisallowPeriod The duration period at the end of a staking epoch /// during which participants cannot stake/withdraw/order/claim their staking coins function initialize( address _validatorSetContract, address[] calldata _initialStakingAddresses, uint256 _delegatorMinStake, uint256 _candidateMinStake, uint256 _stakingFixedEpochDuration, uint256 _stakingTransitionTimeframeLength, uint256 _stakingWithdrawDisallowPeriod, bytes32[] calldata _publicKeys, bytes16[] calldata _internetAddresses ) external { require(_stakingFixedEpochDuration != 0, "FixedEpochDuration is 0"); require(_stakingFixedEpochDuration > _stakingWithdrawDisallowPeriod, "FixedEpochDuration must be longer than withdrawDisallowPeriod"); require(_stakingWithdrawDisallowPeriod != 0, "WithdrawDisallowPeriod is 0"); require(_stakingTransitionTimeframeLength != 0, "The transition timeframe must be longer than 0"); require(_stakingTransitionTimeframeLength < _stakingFixedEpochDuration, "The transition timeframe must be shorter then the epoch duration"); _initialize( _validatorSetContract, _initialStakingAddresses, _delegatorMinStake, _candidateMinStake, _publicKeys, _internetAddresses ); stakingFixedEpochDuration = _stakingFixedEpochDuration; stakingWithdrawDisallowPeriod = _stakingWithdrawDisallowPeriod; //note: this might be still 0 when created in the genesis block. stakingEpochStartTime = validatorSetContract.getCurrentTimestamp(); stakingTransitionTimeframeLength = _stakingTransitionTimeframeLength; } /// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the /// `getPools` getter). Called by the `ValidatorSetHbbft._removeMaliciousValidator` internal function, /// and the `ValidatorSetHbbft.handleFailedKeyGeneration` function /// when a pool must be removed by the algorithm. /// @param _stakingAddress The staking address of the pool to be removed. function removePool(address _stakingAddress) external onlyValidatorSetContract { _removePool(_stakingAddress); } /// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array. /// Called by the `ValidatorSetHbbft.newValidatorSet` function when a pool must be removed by the algorithm. function removePools() external onlyValidatorSetContract { address[] memory poolsToRemove = _poolsToBeRemoved; for (uint256 i = 0; i < poolsToRemove.length; i++) { _removePool(poolsToRemove[i]); } } /// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which /// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool, /// they should call this function from their staking address. function removeMyPool() external gasPriceIsValid onlyInitialized { address stakingAddress = msg.sender; address miningAddress = validatorSetContract.miningByStakingAddress(stakingAddress); // initial validator cannot remove their pool during the initial staking epoch require(stakingEpoch > 0 || !validatorSetContract.isValidator(miningAddress), "Can't remove pool during 1st staking epoch"); _removePool(stakingAddress); } /// @dev Sets the timetamp of the current epoch's last block as the start time of the upcoming staking epoch. /// Called by the `ValidatorSetHbbft.newValidatorSet` function at the last block of a staking epoch. /// @param _timestamp The starting time of the very first block in the upcoming staking epoch. function setStakingEpochStartTime(uint256 _timestamp) external onlyValidatorSetContract { stakingEpochStartTime = _timestamp; stakingEpochStartBlock = block.number; } /// @dev Moves staking coins from one pool to another. A staker calls this function when they want /// to move their coins from one pool to another without withdrawing their coins. /// @param _fromPoolStakingAddress The staking address of the source pool. /// @param _toPoolStakingAddress The staking address of the target pool. /// @param _amount The amount of staking coins to be moved. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function moveStake( address _fromPoolStakingAddress, address _toPoolStakingAddress, uint256 _amount ) external gasPriceIsValid onlyInitialized { require(_fromPoolStakingAddress != _toPoolStakingAddress, "MoveStake: src and dst pool is the same"); address staker = msg.sender; _withdraw(_fromPoolStakingAddress, staker, _amount); _stake(_toPoolStakingAddress, staker, _amount); emit MovedStake(_fromPoolStakingAddress, _toPoolStakingAddress, staker, stakingEpoch, _amount); } /// @dev Moves the specified amount of staking coins from the staker's address to the staking address of /// the specified pool. Actually, the amount is stored in a balance of this StakingHbbft contract. /// A staker calls this function when they want to make a stake into a pool. /// @param _toPoolStakingAddress The staking address of the pool where the coins should be staked. function stake(address _toPoolStakingAddress) external payable gasPriceIsValid { address staker = msg.sender; uint256 amount = msg.value; _stake(_toPoolStakingAddress, staker, amount); } /// @dev Moves the specified amount of staking coins from the staking address of /// the specified pool to the staker's address. A staker calls this function when they want to withdraw /// their coins. /// @param _fromPoolStakingAddress The staking address of the pool from which the coins should be withdrawn. /// @param _amount The amount of coins to be withdrawn. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function withdraw(address _fromPoolStakingAddress, uint256 _amount) external gasPriceIsValid onlyInitialized { address payable staker = msg.sender; _withdraw(_fromPoolStakingAddress, staker, _amount); _sendWithdrawnStakeAmount(staker, _amount); emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount); } /// @dev Orders coins withdrawal from the staking address of the specified pool to the /// staker's address. The requested coins can be claimed after the current staking epoch is complete using /// the `claimOrderedWithdraw` function. /// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn. /// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or /// increase their withdrawal amount. A negative value means the staker wants to decrease a /// withdrawal amount that was previously set. The amount cannot exceed the value returned by the /// `maxWithdrawOrderAllowed` getter. function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized { require(_poolStakingAddress != address(0), "poolStakingAddress must not be 0x0"); require(_amount != 0, "ordered withdraw amount must not be 0"); address staker = msg.sender; require(_isWithdrawAllowed( validatorSetContract.miningByStakingAddress(_poolStakingAddress), staker != _poolStakingAddress), "OrderWithdraw: not allowed" ); uint256 newOrderedAmount = orderedWithdrawAmount[_poolStakingAddress][staker]; uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[_poolStakingAddress]; uint256 newStakeAmount = stakeAmount[_poolStakingAddress][staker]; uint256 newStakeAmountTotal = stakeAmountTotal[_poolStakingAddress]; if (_amount > 0) { uint256 amount = uint256(_amount); // How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment? require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker), "OrderWithdraw: maxWithdrawOrderAllowed exceeded"); newOrderedAmount = newOrderedAmount.add(amount); newOrderedAmountTotal = newOrderedAmountTotal.add(amount); newStakeAmount = newStakeAmount.sub(amount); newStakeAmountTotal = newStakeAmountTotal.sub(amount); orderWithdrawEpoch[_poolStakingAddress][staker] = stakingEpoch; } else { uint256 amount = uint256(-_amount); newOrderedAmount = newOrderedAmount.sub(amount); newOrderedAmountTotal = newOrderedAmountTotal.sub(amount); newStakeAmount = newStakeAmount.add(amount); newStakeAmountTotal = newStakeAmountTotal.add(amount); } orderedWithdrawAmount[_poolStakingAddress][staker] = newOrderedAmount; orderedWithdrawAmountTotal[_poolStakingAddress] = newOrderedAmountTotal; stakeAmount[_poolStakingAddress][staker] = newStakeAmount; stakeAmountTotal[_poolStakingAddress] = newStakeAmountTotal; if (staker == _poolStakingAddress) { // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `candidateMinStake` require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake, "newStake Amount must be greater than the min stake."); if (_amount > 0) { // if the validator orders the `_amount` for withdrawal if (newStakeAmount == 0) { // If the validator orders their entire stake, // mark their pool as `to be removed` _addPoolToBeRemoved(_poolStakingAddress); } } else { // If the validator wants to reduce withdrawal value, // add their pool as `active` if it hasn't been already done. _addPoolActive(_poolStakingAddress, true); } } else { // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `delegatorMinStake` require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake, "newStake Amount must be greater than the min stake."); if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal if (newStakeAmount == 0) { // If the delegator orders their entire stake, // remove the delegator from delegator list of the pool _removePoolDelegator(_poolStakingAddress, staker); } } else { // If the delegator wants to reduce withdrawal value, // add them to delegator list of the pool if it hasn't already done _addPoolDelegator(_poolStakingAddress, staker); } // Remember stake movement to use it later in the `claimReward` function _snapshotDelegatorStake(_poolStakingAddress, staker); } _setLikelihood(_poolStakingAddress); emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount); } /// @dev Withdraws the staking coins from the specified pool ordered during the previous staking epochs with /// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter. /// @param _poolStakingAddress The staking address of the pool from which the ordered coins are withdrawn. function claimOrderedWithdraw(address _poolStakingAddress) external gasPriceIsValid onlyInitialized { address payable staker = msg.sender; require(stakingEpoch > orderWithdrawEpoch[_poolStakingAddress][staker], "cannot claim ordered withdraw in the same epoch it was ordered."); require(_isWithdrawAllowed( validatorSetContract.miningByStakingAddress(_poolStakingAddress), staker != _poolStakingAddress), "ClaimOrderedWithdraw: Withdraw not allowed" ); uint256 claimAmount = orderedWithdrawAmount[_poolStakingAddress][staker]; require(claimAmount != 0, "claim amount must not be 0"); orderedWithdrawAmount[_poolStakingAddress][staker] = 0; orderedWithdrawAmountTotal[_poolStakingAddress] = orderedWithdrawAmountTotal[_poolStakingAddress].sub(claimAmount); if (stakeAmount[_poolStakingAddress][staker] == 0) { _withdrawCheckPool(_poolStakingAddress, staker); } _sendWithdrawnStakeAmount(staker, claimAmount); emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount); } /// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized { candidateMinStake = _minStake; } /// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized { delegatorMinStake = _minStake; } /// @dev Notifies hbbft staking contract that the /// key generation has failed, and a new round /// of keygeneration starts. function notifyKeyGenFailed() public onlyValidatorSetContract { // we allow a extra time window for the current key generation // equal in the size of the usual transition timeframe. currentKeyGenExtraTimeWindow += stakingTransitionTimeframeLength; } /// @dev Notifies hbbft staking contract about a detected /// network offline time. /// if there is no handling for this, /// validators got chosen outside the transition timewindow /// and get banned immediatly, since they never got their chance /// to write their keys. /// more about: https://github.com/DMDcoin/hbbft-posdao-contracts/issues/96 function notifyNetworkOfftimeDetected(uint256 detectedOfflineTime) public onlyValidatorSetContract { currentKeyGenExtraTimeWindow = currentKeyGenExtraTimeWindow + detectedOfflineTime + stakingTransitionTimeframeLength; } /// @dev Notifies hbbft staking contract that a validator /// asociated with the given `_stakingAddress` became /// available again and can be put on to the list /// of available nodes again. function notifyAvailability(address _stakingAddress) public onlyValidatorSetContract { if (stakeAmount[_stakingAddress][_stakingAddress] >= candidateMinStake) { _addPoolActive(_stakingAddress, true); _setLikelihood(_stakingAddress); } } // =============================================== Getters ======================================================== /// @dev Returns an array of the current active pools (the staking addresses of candidates and validators). /// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive` /// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active /// if its address has at least the minimum stake and this stake is not ordered to be withdrawn. function getPools() external view returns(address[] memory) { return _pools; } /// @dev Return the Public Key used by a Node to send targeted HBBFT Consensus Messages. /// @param _poolAddress The Pool Address to query the public key for. /// @return the public key for the given pool address. /// Note that the public key does not convert to the ethereum address of the pool address. /// The pool address is used for stacking, and not for signing HBBFT messages. function getPoolPublicKey(address _poolAddress) external view returns (bytes memory) { return poolInfo[_poolAddress].publicKey; } /// @dev Returns the registered IPv4 Address for the node. /// @param _poolAddress The Pool Address to query the IPv4Address for. /// @return IPv4 Address for the given pool address. function getPoolInternetAddress(address _poolAddress) external view returns (bytes16) { return poolInfo[_poolAddress].internetAddress; } /// @dev Returns an array of the current inactive pools (the staking addresses of former candidates). /// A pool can be added to this array with the `_addPoolInactive` internal function which is called /// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address /// has zero stake, or if its entire stake is ordered to be withdrawn. function getPoolsInactive() external view returns(address[] memory) { return _poolsInactive; } /// @dev Returns the array of stake amounts for each corresponding /// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts. /// Used by the `ValidatorSetHbbft.newValidatorSet` function when randomly selecting new validators at the last /// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool /// (see the `_setLikelihood` internal function). /// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length /// of the `poolsToBeElected` array. /// `uint256 sum` - The total sum of the amounts. function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) { return (_poolsLikelihood, _poolsLikelihoodSum); } /// @dev Returns the list of pools (their staking addresses) which will participate in a new validator set /// selection process in the `ValidatorSetHbbft.newValidatorSet` function. This is an array of pools /// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch). /// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions. function getPoolsToBeElected() external view returns(address[] memory) { return _poolsToBeElected; } /// @dev Returns the list of pools (their staking addresses) which will be removed by the /// `ValidatorSetHbbft.newValidatorSet` function from the active `pools` array (at the last block /// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved` /// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's /// address withdraws (or orders) all of its own staking coins from the pool, inactivating the pool. function getPoolsToBeRemoved() external view returns(address[] memory) { return _poolsToBeRemoved; } /// @dev Determines whether staking/withdrawal operations are allowed at the moment. /// Used by all staking/withdrawal functions. function areStakeAndWithdrawAllowed() public view returns(bool) { //experimental change to always allow to stake withdraw. //see https://github.com/DMDcoin/hbbft-posdao-contracts/issues/14 for discussion. return true; // used for testing // if (stakingFixedEpochDuration == 0){ // return true; // } // uint256 currentTimestamp = _validatorSetContract.getCurrentTimestamp(); // uint256 allowedDuration = stakingFixedEpochDuration - stakingWithdrawDisallowPeriod; // return currentTimestamp - stakingEpochStartTime > allowedDuration; //TODO: should be < not <=? } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetHbbft(0); } /// @dev Returns a flag indicating whether a specified address is in the `pools` array. /// See the `getPools` getter. /// @param _stakingAddress The staking address of the pool. function isPoolActive(address _stakingAddress) public view returns(bool) { uint256 index = poolIndex[_stakingAddress]; return index < _pools.length && _pools[index] == _stakingAddress; } /// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker /// at the moment. Used by the `withdraw` and `moveStake` functions. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be made. /// @param _staker The staker address that is going to withdraw. function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); if (!_isWithdrawAllowed(miningAddress, _poolStakingAddress != _staker)) { return 0; } uint256 canWithdraw = stakeAmount[_poolStakingAddress][_staker]; if (!validatorSetContract.isValidatorOrPending(miningAddress)) { // The pool is not a validator and is not going to become one, // so the staker can only withdraw staked amount minus already // ordered amount return canWithdraw; } // The pool is a validator (active or pending), so the staker can only // withdraw staked amount minus already ordered amount but // no more than the amount staked during the current staking epoch uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker); if (canWithdraw > stakedDuringEpoch) { canWithdraw = stakedDuringEpoch; } return canWithdraw; } /// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the /// specified staker at the moment. Used by the `orderWithdraw` function. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered. /// @param _staker The staker address that is going to order the withdrawal. function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); if (!_isWithdrawAllowed(miningAddress, _poolStakingAddress != _staker)) { return 0; } if (!validatorSetContract.isValidatorOrPending(miningAddress)) { // If the pool is a candidate (not an active validator and not pending one), // no one can order withdrawal from the `_poolStakingAddress`, but // anyone can withdraw immediately (see the `maxWithdrawAllowed` getter) return 0; } // If the pool is an active or pending validator, the staker can order withdrawal // up to their total staking amount minus an already ordered amount // minus an amount staked during the current staking epoch return stakeAmount[_poolStakingAddress][_staker].sub(stakeAmountByCurrentEpoch(_poolStakingAddress, _staker)); } /// @dev Returns an array of the current active delegators of the specified pool. /// A delegator is considered active if they have staked into the specified /// pool and their stake is not ordered to be withdrawn. /// @param _poolStakingAddress The pool staking address. function poolDelegators(address _poolStakingAddress) public view returns(address[] memory) { return _poolDelegators[_poolStakingAddress]; } /// @dev Returns an array of the current inactive delegators of the specified pool. /// A delegator is considered inactive if their entire stake is ordered to be withdrawn /// but not yet claimed. /// @param _poolStakingAddress The pool staking address. function poolDelegatorsInactive(address _poolStakingAddress) public view returns(address[] memory) { return _poolDelegatorsInactive[_poolStakingAddress]; } /// @dev Returns the amount of staking coins staked into the specified pool by the specified staker /// during the current staking epoch (see the `stakingEpoch` getter). /// Used by the `stake`, `withdraw`, and `orderWithdraw` functions. /// @param _poolStakingAddress The pool staking address. /// @param _staker The staker's address. function stakeAmountByCurrentEpoch(address _poolStakingAddress, address _staker) public view returns(uint256) { return _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch]; } /// @dev indicates the time when the new validatorset for the next epoch gets chosen. /// this is the start of a timeframe before the end of the epoch, /// that is long enough for the validators /// to create a new shared key. function startTimeOfNextPhaseTransition() public view returns(uint256) { return stakingEpochStartTime + stakingFixedEpochDuration - stakingTransitionTimeframeLength; } /// @dev Returns an indicative time of the last block of the current staking epoch before key generation starts. function stakingFixedEpochEndTime() public view returns(uint256) { uint256 startTime = stakingEpochStartTime; return startTime + stakingFixedEpochDuration + currentKeyGenExtraTimeWindow - (stakingFixedEpochDuration == 0 ? 0 : 1); } // ============================================== Internal ======================================================== /// @dev Adds the specified staking address to the array of active pools returned by /// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions. /// @param _stakingAddress The pool added to the array of active pools. /// @param _toBeElected The boolean flag which defines whether the specified address should be /// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. function _addPoolActive(address _stakingAddress, bool _toBeElected) internal { if (!isPoolActive(_stakingAddress)) { poolIndex[_stakingAddress] = _pools.length; _pools.push(_stakingAddress); require(_pools.length <= _getMaxCandidates(), "MAX_CANDIDATES pools exceeded"); } _removePoolInactive(_stakingAddress); if (_toBeElected) { _addPoolToBeElected(_stakingAddress); } } /// @dev Adds the specified staking address to the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by the `_removePool` internal function. /// @param _stakingAddress The pool added to the array of inactive pools. function _addPoolInactive(address _stakingAddress) internal { uint256 index = poolInactiveIndex[_stakingAddress]; uint256 length = _poolsInactive.length; if (index >= length || _poolsInactive[index] != _stakingAddress) { poolInactiveIndex[_stakingAddress] = length; _poolsInactive.push(_stakingAddress); } } /// @dev Adds the specified staking address to the array of pools returned by the `getPoolsToBeElected` /// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter. /// @param _stakingAddress The pool added to the `poolsToBeElected` array. function _addPoolToBeElected(address _stakingAddress) internal { uint256 index = poolToBeElectedIndex[_stakingAddress]; uint256 length = _poolsToBeElected.length; if (index >= length || _poolsToBeElected[index] != _stakingAddress) { poolToBeElectedIndex[_stakingAddress] = length; _poolsToBeElected.push(_stakingAddress); _poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter } _deletePoolToBeRemoved(_stakingAddress); } /// @dev Adds the specified staking address to the array of pools returned by the `getPoolsToBeRemoved` /// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter. /// @param _stakingAddress The pool added to the `poolsToBeRemoved` array. function _addPoolToBeRemoved(address _stakingAddress) internal { uint256 index = poolToBeRemovedIndex[_stakingAddress]; uint256 length = _poolsToBeRemoved.length; if (index >= length || _poolsToBeRemoved[index] != _stakingAddress) { poolToBeRemovedIndex[_stakingAddress] = length; _poolsToBeRemoved.push(_stakingAddress); } _deletePoolToBeElected(_stakingAddress); } /// @dev Deletes the specified staking address from the array of pools returned by the /// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions. /// See the `getPoolsToBeElected` getter. /// @param _stakingAddress The pool deleted from the `poolsToBeElected` array. function _deletePoolToBeElected(address _stakingAddress) internal { if (_poolsToBeElected.length != _poolsLikelihood.length) return; uint256 indexToDelete = poolToBeElectedIndex[_stakingAddress]; if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _stakingAddress) { if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) { _poolsLikelihoodSum -= _poolsLikelihood[indexToDelete]; } else { _poolsLikelihoodSum = 0; } uint256 lastPoolIndex = _poolsToBeElected.length - 1; address lastPool = _poolsToBeElected[lastPoolIndex]; _poolsToBeElected[indexToDelete] = lastPool; _poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex]; poolToBeElectedIndex[lastPool] = indexToDelete; poolToBeElectedIndex[_stakingAddress] = 0; _poolsToBeElected.length--; _poolsLikelihood.length--; } } /// @dev Deletes the specified staking address from the array of pools returned by the /// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions. /// See the `getPoolsToBeRemoved` getter. /// @param _stakingAddress The pool deleted from the `poolsToBeRemoved` array. function _deletePoolToBeRemoved(address _stakingAddress) internal { uint256 indexToDelete = poolToBeRemovedIndex[_stakingAddress]; if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _stakingAddress) { address lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1]; _poolsToBeRemoved[indexToDelete] = lastPool; poolToBeRemovedIndex[lastPool] = indexToDelete; poolToBeRemovedIndex[_stakingAddress] = 0; _poolsToBeRemoved.length--; } } /// @dev Removes the specified staking address from the array of active pools returned by /// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions. /// @param _stakingAddress The pool removed from the array of active pools. function _removePool(address _stakingAddress) internal { uint256 indexToRemove = poolIndex[_stakingAddress]; if (_pools.length > indexToRemove && _pools[indexToRemove] == _stakingAddress) { address lastPool = _pools[_pools.length - 1]; _pools[indexToRemove] = lastPool; poolIndex[lastPool] = indexToRemove; poolIndex[_stakingAddress] = 0; _pools.length--; } if (_isPoolEmpty(_stakingAddress)) { _removePoolInactive(_stakingAddress); } else { _addPoolInactive(_stakingAddress); } _deletePoolToBeElected(_stakingAddress); _deletePoolToBeRemoved(_stakingAddress); } /// @dev Removes the specified staking address from the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and /// `_removePool` internal functions. /// @param _stakingAddress The pool removed from the array of inactive pools. function _removePoolInactive(address _stakingAddress) internal { uint256 indexToRemove = poolInactiveIndex[_stakingAddress]; if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _stakingAddress) { address lastPool = _poolsInactive[_poolsInactive.length - 1]; _poolsInactive[indexToRemove] = lastPool; poolInactiveIndex[lastPool] = indexToRemove; poolInactiveIndex[_stakingAddress] = 0; _poolsInactive.length--; } } /// @dev Initializes the network parameters. Used by the `initialize` function. /// @param _validatorSetContract The address of the `ValidatorSetHbbft` contract. /// @param _initialStakingAddresses The array of initial validators' staking addresses. /// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei. /// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei. function _initialize( address _validatorSetContract, address[] memory _initialStakingAddresses, uint256 _delegatorMinStake, uint256 _candidateMinStake, bytes32[] memory _publicKeys, bytes16[] memory _internetAddresses ) internal { require(msg.sender == _admin() || tx.origin == _admin() || address(0) == _admin() || block.number == 0, "Initialization only on genesis block or by admin"); require(!isInitialized(), "Already initialized"); // initialization can only be done once require(_validatorSetContract != address(0),"ValidatorSet can't be 0"); require(_initialStakingAddresses.length > 0, "Must provide initial mining addresses"); require(_initialStakingAddresses.length.mul(2) == _publicKeys.length, "Must provide correct number of publicKeys"); require(_initialStakingAddresses.length == _internetAddresses.length, "Must provide correct number of IP adresses"); require(_delegatorMinStake != 0, "DelegatorMinStake is 0"); require(_candidateMinStake != 0, "CandidateMinStake is 0"); validatorSetContract = IValidatorSetHbbft(_validatorSetContract); for (uint256 i = 0; i < _initialStakingAddresses.length; i++) { require(_initialStakingAddresses[i] != address(0), "InitialStakingAddresses can't be 0"); _addPoolActive(_initialStakingAddresses[i], false); _addPoolToBeRemoved(_initialStakingAddresses[i]); poolInfo[_initialStakingAddresses[i]].publicKey = abi.encodePacked(_publicKeys[i*2],_publicKeys[i*2+1]); poolInfo[_initialStakingAddresses[i]].internetAddress = _internetAddresses[i]; } delegatorMinStake = _delegatorMinStake; candidateMinStake = _candidateMinStake; } /// @dev Adds the specified address to the array of the current active delegators of the specified pool. /// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _addPoolDelegator(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolStakingAddress]; uint256 index = poolDelegatorIndex[_poolStakingAddress][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorIndex[_poolStakingAddress][_delegator] = length; delegators.push(_delegator); } _removePoolDelegatorInactive(_poolStakingAddress, _delegator); } /// @dev Adds the specified address to the array of the current inactive delegators of the specified pool. /// Used by the `_removePoolDelegator` internal function. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _addPoolDelegatorInactive(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolStakingAddress]; uint256 index = poolDelegatorInactiveIndex[_poolStakingAddress][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorInactiveIndex[_poolStakingAddress][_delegator] = length; delegators.push(_delegator); } } /// @dev Removes the specified address from the array of the current active delegators of the specified pool. /// Used by the withdrawal functions. See the `poolDelegators` getter. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _removePoolDelegator(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolStakingAddress]; uint256 indexToRemove = poolDelegatorIndex[_poolStakingAddress][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorIndex[_poolStakingAddress][lastDelegator] = indexToRemove; poolDelegatorIndex[_poolStakingAddress][_delegator] = 0; delegators.length--; } if (orderedWithdrawAmount[_poolStakingAddress][_delegator] != 0) { _addPoolDelegatorInactive(_poolStakingAddress, _delegator); } else { _removePoolDelegatorInactive(_poolStakingAddress, _delegator); } } /// @dev Removes the specified address from the array of the inactive delegators of the specified pool. /// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _removePoolDelegatorInactive(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolStakingAddress]; uint256 indexToRemove = poolDelegatorInactiveIndex[_poolStakingAddress][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorInactiveIndex[_poolStakingAddress][lastDelegator] = indexToRemove; poolDelegatorInactiveIndex[_poolStakingAddress][_delegator] = 0; delegators.length--; } } function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal; /// @dev Calculates (updates) the probability of being selected as a validator for the specified pool /// and updates the total sum of probability coefficients. Actually, the probability is equal to the /// amount totally staked into the pool. See the `getPoolsLikelihood` getter. /// Used by the staking and withdrawal functions. /// @param _poolStakingAddress The address of the pool for which the probability coefficient must be updated. function _setLikelihood(address _poolStakingAddress) internal { (bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolStakingAddress); if (!isToBeElected) return; uint256 oldValue = _poolsLikelihood[index]; uint256 newValue = stakeAmountTotal[_poolStakingAddress]; _poolsLikelihood[index] = newValue; if (newValue >= oldValue) { _poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue); } else { _poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue); } } /// @dev Makes a snapshot of the amount currently staked by the specified delegator /// into the specified pool (staking address). Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions. /// @param _poolStakingAddress The staking address of the pool. /// @param _delegator The address of the delegator. function _snapshotDelegatorStake(address _poolStakingAddress, address _delegator) internal { uint256 nextStakingEpoch = stakingEpoch + 1; uint256 newAmount = stakeAmount[_poolStakingAddress][_delegator]; delegatorStakeSnapshot[_poolStakingAddress][_delegator][nextStakingEpoch] = (newAmount != 0) ? newAmount : uint256(-1); if (stakeFirstEpoch[_poolStakingAddress][_delegator] == 0) { stakeFirstEpoch[_poolStakingAddress][_delegator] = nextStakingEpoch; } stakeLastEpoch[_poolStakingAddress][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0; } /// @dev The internal function used by the `_stake` and `moveStake` functions. /// See the `stake` public function for more details. /// @param _poolStakingAddress The staking address of the pool where the coins should be staked. /// @param _staker The staker's address. /// @param _amount The amount of coins to be staked. function _stake(address _poolStakingAddress, address _staker, uint256 _amount) internal { address poolMiningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); require(poolMiningAddress != address(0), "Pool does not exist. miningAddress for that staking address is 0"); require(_poolStakingAddress != address(0), "Stake: stakingAddress is 0"); require(_amount != 0, "Stake: stakingAmount is 0"); require(!validatorSetContract.isValidatorBanned(poolMiningAddress), "Stake: Mining address is banned"); //require(areStakeAndWithdrawAllowed(), "Stake: disallowed period"); uint256 newStakeAmount = stakeAmount[_poolStakingAddress][_staker].add(_amount); if (_staker == _poolStakingAddress) { // The staked amount must be at least CANDIDATE_MIN_STAKE require(newStakeAmount >= candidateMinStake, "Stake: candidateStake less than candidateMinStake"); } else { // The staked amount must be at least DELEGATOR_MIN_STAKE require(newStakeAmount >= delegatorMinStake, "Stake: delegatorStake is less than delegatorMinStake"); // The delegator cannot stake into the pool of the candidate which hasn't self-staked. // Also, that candidate shouldn't want to withdraw all their funds. require(stakeAmount[_poolStakingAddress][_poolStakingAddress] != 0, "Stake: can't delegate in empty pool"); } stakeAmount[_poolStakingAddress][_staker] = newStakeAmount; _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch] = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker).add(_amount); stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].add(_amount); if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate // Add `_poolStakingAddress` to the array of pools _addPoolActive(_poolStakingAddress, true); } else { // Add `_staker` to the array of pool's delegators _addPoolDelegator(_poolStakingAddress, _staker); // Save amount value staked by the delegator _snapshotDelegatorStake(_poolStakingAddress, _staker); } _setLikelihood(_poolStakingAddress); emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount); } /// @dev The internal function used by the `withdraw` and `moveStake` functions. /// See the `withdraw` public function for more details. /// @param _poolStakingAddress The staking address of the pool from which the coins should be withdrawn. /// @param _staker The staker's address. /// @param _amount The amount of coins to be withdrawn. function _withdraw(address _poolStakingAddress, address _staker, uint256 _amount) internal { require(_poolStakingAddress != address(0), "Withdraw pool staking address must not be null"); require(_amount != 0, "amount to withdraw must not be 0"); // How much can `staker` withdraw from `_poolStakingAddress` at the moment? require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker), "Withdraw: maxWithdrawAllowed exceeded"); uint256 newStakeAmount = stakeAmount[_poolStakingAddress][_staker].sub(_amount); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and MIN_STAKE uint256 minAllowedStake = (_poolStakingAddress == _staker) ? candidateMinStake : delegatorMinStake; require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake, "newStake amount must be greater equal than the min stake."); stakeAmount[_poolStakingAddress][_staker] = newStakeAmount; uint256 amountByEpoch = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker); _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch] = amountByEpoch >= _amount ? amountByEpoch - _amount : 0; stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].sub(_amount); if (newStakeAmount == 0) { _withdrawCheckPool(_poolStakingAddress, _staker); } if (_staker != _poolStakingAddress) { _snapshotDelegatorStake(_poolStakingAddress, _staker); } _setLikelihood(_poolStakingAddress); } /// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions. /// Contains a common logic for these functions. /// @param _poolStakingAddress The staking address of the pool from which the coins are withdrawn. /// @param _staker The staker's address. function _withdrawCheckPool(address _poolStakingAddress, address _staker) internal { if (_staker == _poolStakingAddress) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); if (validatorSetContract.isValidator(miningAddress)) { _addPoolToBeRemoved(_poolStakingAddress); } else { _removePool(_poolStakingAddress); } } else { _removePoolDelegator(_poolStakingAddress, _staker); if (_isPoolEmpty(_poolStakingAddress)) { _removePoolInactive(_poolStakingAddress); } } } /// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter. /// Finds the stake amount made by a specified delegator into a specified pool before a specified /// staking epoch. function _getDelegatorStake( uint256 _epoch, uint256 _firstEpoch, uint256 _prevDelegatorStake, address _poolStakingAddress, address _delegator ) internal view returns(uint256 delegatorStake) { while (true) { delegatorStake = delegatorStakeSnapshot[_poolStakingAddress][_delegator][_epoch]; if (delegatorStake != 0) { delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake; break; } else if (_epoch == _firstEpoch) { delegatorStake = _prevDelegatorStake; break; } _epoch--; } } /// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant. /// Needed mostly for unit tests. function _getMaxCandidates() internal pure returns(uint256) { return MAX_CANDIDATES; } /// @dev Returns a boolean flag indicating whether the specified pool is fully empty /// (all stakes are withdrawn including ordered withdrawals). /// @param _poolStakingAddress The staking address of the pool function _isPoolEmpty(address _poolStakingAddress) internal view returns(bool) { return stakeAmountTotal[_poolStakingAddress] == 0 && orderedWithdrawAmountTotal[_poolStakingAddress] == 0; } /// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. /// Used by the `_setLikelihood` internal function. /// @param _stakingAddress The staking address of the pool. /// @return `bool toBeElected` - The boolean flag indicating whether the `_stakingAddress` is in the /// `poolsToBeElected` array. /// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`. function _isPoolToBeElected(address _stakingAddress) internal view returns(bool toBeElected, uint256 index) { index = poolToBeElectedIndex[_stakingAddress]; if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _stakingAddress) { return (true, index); } return (false, 0); } /// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment. /// Used by all withdrawal functions. /// @param _miningAddress The mining address of the validator's pool. /// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator. function _isWithdrawAllowed(address _miningAddress, bool _isDelegator) internal view returns(bool) { if (_isDelegator) { if (validatorSetContract.areDelegatorsBanned(_miningAddress)) { // The delegator cannot withdraw from the banned validator pool until the ban is expired return false; } } else { if (validatorSetContract.isValidatorBanned(_miningAddress)) { // The banned validator cannot withdraw from their pool until the ban is expired return false; } } if (!areStakeAndWithdrawAllowed()) { return false; } return true; } }
@dev Notifies hbbft staking contract that a validator asociated with the given `_stakingAddress` became available again and can be put on to the list of available nodes again.
{ function setCandidateMinStake(uint256 _minStake) external onlyOwner } function setDelegatorMinStake(uint256 _minStake) external onlyOwner } function notifyKeyGenFailed() public onlyValidatorSetContract } function notifyNetworkOfftimeDetected(uint256 detectedOfflineTime) public } function notifyAvailability(address _stakingAddress) public onlyValidatorSetContract if (stakeAmount[_stakingAddress][_stakingAddress] >= candidateMinStake) { _addPoolActive(_stakingAddress, true); _setLikelihood(_stakingAddress); } }
927,122
[ 1, 1248, 5032, 366, 9897, 1222, 384, 6159, 6835, 716, 279, 4213, 487, 1882, 690, 598, 326, 864, 1375, 67, 334, 6159, 1887, 68, 506, 71, 339, 2319, 3382, 471, 848, 506, 1378, 603, 358, 326, 666, 434, 2319, 2199, 3382, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 565, 445, 11440, 8824, 2930, 510, 911, 12, 11890, 5034, 389, 1154, 510, 911, 13, 203, 565, 3903, 203, 565, 1338, 5541, 203, 565, 289, 203, 203, 565, 445, 444, 15608, 639, 2930, 510, 911, 12, 11890, 5034, 389, 1154, 510, 911, 13, 203, 565, 3903, 203, 565, 1338, 5541, 203, 565, 289, 203, 203, 203, 565, 445, 5066, 653, 7642, 2925, 1435, 203, 565, 1071, 203, 565, 1338, 5126, 694, 8924, 203, 565, 289, 203, 203, 565, 445, 5066, 3906, 7210, 957, 22614, 12, 11890, 5034, 8316, 23106, 950, 13, 203, 565, 1071, 203, 565, 289, 203, 203, 565, 445, 5066, 10427, 12, 2867, 389, 334, 6159, 1887, 13, 203, 565, 1071, 203, 565, 1338, 5126, 694, 8924, 203, 3639, 309, 261, 334, 911, 6275, 63, 67, 334, 6159, 1887, 6362, 67, 334, 6159, 1887, 65, 1545, 5500, 2930, 510, 911, 13, 288, 203, 5411, 389, 1289, 2864, 3896, 24899, 334, 6159, 1887, 16, 638, 1769, 203, 5411, 389, 542, 30248, 11318, 24899, 334, 6159, 1887, 1769, 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 ]
contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract ISncToken { function mintTokens(address _to, uint256 _amount); function totalSupply() constant returns (uint256 totalSupply); } contract SunContractIco is owned{ uint256 public startBlock; uint256 public endBlock; uint256 public minEthToRaise; uint256 public maxEthToRaise; uint256 public totalEthRaised; address public multisigAddress; ISncToken sncTokenContract; mapping (address => bool) presaleContributorAllowance; uint256 nextFreeParticipantIndex; mapping (uint => address) participantIndex; mapping (address => uint256) participantContribution; bool icoHasStarted; bool minTresholdReached; bool icoHasSucessfulyEnded; uint256 blocksInWeek; bool ownerHasClaimedTokens; uint256 lastEthReturnIndex; mapping (address => bool) hasClaimedEthWhenFail; event ICOStarted(uint256 _blockNumber); event ICOMinTresholdReached(uint256 _blockNumber); event ICOEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised); event ICOFailed(uint256 _blockNumber, uint256 _ammountRaised); event ErrorSendingETH(address _from, uint256 _amount); function SunContractIco(uint256 _startBlock, address _multisigAddress) { blocksInWeek = 4 * 60 * 24 * 7; startBlock = _startBlock; endBlock = _startBlock + blocksInWeek * 4; minEthToRaise = 5000 * 10**18; maxEthToRaise = 100000 * 10**18; multisigAddress = _multisigAddress; } // /* User accessible methods */ // /* Users send ETH and enter the token sale*/ function () payable { if (msg.value == 0) throw; // Throw if the value is 0 if (icoHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the ICO has ended if (!icoHasStarted){ // Check if this is the first ICO transaction if (block.number >= startBlock){ // Check if the ICO should start icoHasStarted = true; // Set that the ICO has started ICOStarted(block.number); // Raise ICOStarted event } else{ throw; } } if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index nextFreeParticipantIndex += 1; } if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH participantContribution[msg.sender] += msg.value; // Add contribution totalEthRaised += msg.value;// Add to total eth Raised sncTokenContract.mintTokens(msg.sender, getSncTokenIssuance(block.number, msg.value)); if (!minTresholdReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time ICOMinTresholdReached(block.number); // Raise ICOMinTresholdReached event minTresholdReached = true; // Set that the min treshold has been reached } }else{ // If user sent to much eth uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account totalEthRaised += maxContribution; sncTokenContract.mintTokens(msg.sender, getSncTokenIssuance(block.number, maxContribution)); uint toReturn = msg.value - maxContribution; // Calculate how much should be returned icoHasSucessfulyEnded = true; // Set that ICO has successfully ended ICOEndedSuccessfuly(block.number, totalEthRaised); if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws } } } /* Users can claim ETH by themselves if they want to in case of ETH failure*/ function claimEthIfFailed(){ if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if ICO has failed if (participantContribution[msg.sender] == 0) throw; // Check if user has participated if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution hasClaimedEthWhenFail[msg.sender] = true; if (!msg.sender.send(ethContributed)){ ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually } } // /* Only owner methods */ // /* Adds addresses that are allowed to take part in presale */ function addPresaleContributors(address[] _presaleContributors) onlyOwner { for (uint cnt = 0; cnt < _presaleContributors.length; cnt++){ presaleContributorAllowance[_presaleContributors[cnt]] = true; } } /* Owner can return eth for multiple users in one call*/ function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{ if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if ICO failed address currentParticipantAddress; uint256 contribution; for (uint cnt = 0; cnt < _numberOfReturns; cnt++){ currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back if (!currentParticipantAddress.send(contribution)){ // Send fund back to account ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually } } lastEthReturnIndex += 1; } } /* Owner sets new address of SunContractToken */ function changeMultisigAddress(address _newAddress) onlyOwner { multisigAddress = _newAddress; } /* Owner can claim reserved tokens on the end of crowsale */ function claimCoreTeamsTokens(address _to) onlyOwner{ if (!icoHasSucessfulyEnded) throw; if (ownerHasClaimedTokens) throw; sncTokenContract.mintTokens(_to, sncTokenContract.totalSupply() * 25 / 100); ownerHasClaimedTokens = true; } /* Owner can remove allowance of designated presale contributor */ function removePresaleContributor(address _presaleContributor) onlyOwner { presaleContributorAllowance[_presaleContributor] = false; } /* Set token contract where mints will be done (tokens will be issued)*/ function setTokenContract(address _sncTokenContractAddress) onlyOwner { sncTokenContract = ISncToken(_sncTokenContractAddress); } /* Withdraw funds from contract */ function withdrawEth() onlyOwner{ if (this.balance == 0) throw; // Check if there is balance on the contract if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address } function endIco() onlyOwner { if (totalEthRaised < minEthToRaise) throw; if (block.number < endBlock) throw; icoHasSucessfulyEnded = true; ICOEndedSuccessfuly(block.number, totalEthRaised); } /* Withdraw remaining balance to manually return where contract send has failed */ function withdrawRemainingBalanceForManualRecovery() onlyOwner{ if (this.balance == 0) throw; // Check if there is balance on the contract if (block.number < endBlock) throw; // Check if ICO failed if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed } // /* Getters */ // function getSncTokenAddress() constant returns(address _tokenAddress){ return address(sncTokenContract); } function icoInProgress() constant returns (bool answer){ return icoHasStarted && !icoHasSucessfulyEnded; } function isAddressAllowedInPresale(address _querryAddress) constant returns (bool answer){ return presaleContributorAllowance[_querryAddress]; } function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){ return participantContribution[_querryAddress]; } function getSncTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){ if (_blockNumber >= startBlock && _blockNumber < blocksInWeek + startBlock) { if (presaleContributorAllowance[msg.sender]) return _ethSent * 11600; else return _ethSent * 11500; } if (_blockNumber >= blocksInWeek + startBlock && _blockNumber < blocksInWeek * 2 + startBlock) return _ethSent * 11000; if (_blockNumber >= blocksInWeek * 2 + startBlock && _blockNumber < blocksInWeek * 3 + startBlock) return _ethSent * 10500; if (_blockNumber >= blocksInWeek * 3 + startBlock && _blockNumber <= blocksInWeek * 4 + startBlock) return _ethSent * 10000; } // /* This part is here only for testing and will not be included into final version */ // //function killContract() onlyOwner{ // selfdestruct(msg.sender); //} }
Check if user has manually recovered ETH
if (!hasClaimedEthWhenFail[currentParticipantAddress]) {
1,752,702
[ 1, 1564, 309, 729, 711, 10036, 24616, 512, 2455, 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, 1377, 309, 16051, 5332, 9762, 329, 41, 451, 9434, 3754, 63, 2972, 22540, 1887, 5717, 288, 1171, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; interface IJoeTraderRouter02 { function addLiquidityAVAX( address token, uint amountTokenDesired, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountAVAX, uint liquidity); function swapExactTokensForAVAXSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function WAVAX() external pure returns (address); } contract JPEGvaultDAOTokenV3AVAX is ERC20SnapshotUpgradeable, OwnableUpgradeable { // // Don't touch this if you want to upgrade - BEGIN // using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; EnumerableSetUpgradeable.AddressSet private excludedRedistribution; // exclure de la redistribution mapping(address => bool) private excludedTax; IJoeTraderRouter02 private dexRouter; address private uniswapV2Pair; address private WAVAXAddr; address private growthAddress; // Should no longer be used since v3 address private vaultAddress; // Should no longer be used since v3 address private liquidityAddress; // Should no longer be used since v3 address private redistributionContract; uint8 private growthFees; // Should no longer be used since v3 uint8 private vaultFees; // Should no longer be used since v3 uint8 private liquidityFees; // Should no longer be used since v3 uint8 private autoLiquidityFees; // Autoselling ratio between 0 and 100 uint8 private autoSellingRatio; uint216 private minAmountForSwap; // Stores tokens waiting for the next swap uint private autoSellGrowthStack; uint private autoSellVaultStack; uint private autoSellLiquidityStack; // // Don't touch this if you want to upgrade - END // // v3 uint8 public purchaseTax; uint8 public sellTax; uint8 public walletTax; address private treasuryAddress; uint16 public minimumBlockDelay; bool private migrated2v3; address private bridgeAddress; uint private autoSellStack; mapping(address => uint256) private lastTransfer; function initialize(address _growthAddress, address _router) external initializer { __Ownable_init(); __ERC20_init("JPEG", "JPEG"); __ERC20Snapshot_init(); dexRouter = IJoeTraderRouter02(_router); WAVAXAddr = dexRouter.WAVAX(); growthAddress = _growthAddress; _transferOwnership(growthAddress); excludedRedistribution.add(address(this)); excludedRedistribution.add(growthAddress); excludedTax[address(this)] = true; excludedTax[growthAddress] = true; purchaseTax = 10; sellTax = 10; walletTax = 10; treasuryAddress = 0x73d6F7de9e9Ba999088B691b72b7291e7738e0eD; excludedTax[treasuryAddress] = true; minAmountForSwap = 1_000; migrated2v3 = true; _mint(growthAddress, 1_000_000_000 * 10 ** 18); } receive() external payable {} function _transfer( address sender, address recipient, uint256 amount ) internal override { if (!excludedTax[sender] && !excludedTax[recipient]) { if (recipient == uniswapV2Pair) { amount = applyTaxes(sender, amount, sellTax); checkLastTransfer(sender); } else if (sender == uniswapV2Pair) { amount = applyTaxes(sender, amount, purchaseTax); checkLastTransfer(recipient); } else { amount = applyTaxes(sender, amount, walletTax); } } super._transfer(sender, recipient, amount); } function checkLastTransfer(address trader) internal { if (minimumBlockDelay > 0) { require ((block.number - lastTransfer[trader]) >= minimumBlockDelay, "Transfer too close from previous one"); lastTransfer[trader] = block.number; } } function applyTaxes(address sender, uint amount, uint8 tax) internal returns (uint newAmountTransfer) { uint amountTax = amount * tax; uint amountAutoLiquidity = amount * autoLiquidityFees; // Cheaper without "no division by 0" check unchecked { amountTax /= 100; amountAutoLiquidity /= 100; } newAmountTransfer = amount - amountTax - amountAutoLiquidity; // Apply autoselling ratio uint autoSell = amountTax * autoSellingRatio; // Cheaper without "no division by 0" check unchecked { autoSell /= 100; } // Transfer the remaining tokens to wallets super._transfer(sender, treasuryAddress, amountTax - autoSell); // Transfer all autoselling + autoLP to the contract super._transfer(sender, address(this), autoSell + amountAutoLiquidity); uint tokenBalance = balanceOf(address(this)); // Only swap if it's worth it if (tokenBalance >= (minAmountForSwap * 1 ether) && uniswapV2Pair != address(0) && uniswapV2Pair != msg.sender) { swapAndLiquify(tokenBalance, autoSell); } else { // Stack tokens to be swapped for autoselling autoSellStack = autoSellStack + autoSell; } } function swapAndLiquify(uint tokenBalance, uint autoSell) internal { uint finalAutoSell = autoSellStack + autoSell; uint amountToLiquifiy = tokenBalance - finalAutoSell; // Stack tokens for autoliquidity pool uint tokensToBeSwappedForLP; unchecked { tokensToBeSwappedForLP = amountToLiquifiy / 2; } uint tokensForLP = amountToLiquifiy - tokensToBeSwappedForLP; uint totalToSwap = finalAutoSell + tokensToBeSwappedForLP; // Swap all in one call uint balanceInAVAX = address(this).balance; swapTokensForAVAX(totalToSwap); uint totalAVAXswaped = address(this).balance - balanceInAVAX; // Redistribute according to weigth uint autosellAVAX = totalAVAXswaped * finalAutoSell / totalToSwap; AddressUpgradeable.sendValue(payable(treasuryAddress), autosellAVAX); uint availableAVAXForLP = totalAVAXswaped - autosellAVAX; addLiquidity(tokensForLP, availableAVAXForLP); autoSellStack = 0; } function addLiquidity(uint tokenAmount, uint avaxAmount) internal { if (tokenAmount >0) { // add liquidity with token and AVAX _approve(address(this), address(dexRouter), tokenAmount); dexRouter.addLiquidityAVAX{value: avaxAmount}( address(this), tokenAmount, 0, 0, owner(), block.timestamp ); } } function swapTokensForAVAX(uint256 amount) private { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = address(WAVAXAddr); _approve(address(this), address(dexRouter), amount); dexRouter.swapExactTokensForAVAXSupportingFeeOnTransferTokens( amount, 0, _path, address(this), block.timestamp ); } function createRedistribution() public returns (uint, uint) { require(msg.sender == redistributionContract, "Bad caller"); uint newSnapshotId = _snapshot(); return (newSnapshotId, calcSupplyHolders()); } function calcSupplyHolders() internal view returns (uint) { uint balanceExcluded = 0; for (uint i = 0; i < excludedRedistribution.length(); i++) balanceExcluded += balanceOf(excludedRedistribution.at(i)); return totalSupply() - balanceExcluded; } function setMinimumBlockDelay(uint16 blockCount) external onlyOwner { minimumBlockDelay = blockCount; } function setPurchaseTax(uint8 _tax) external onlyOwner { purchaseTax = _tax; } function setSellTax(uint8 _tax) external onlyOwner { sellTax = _tax; } function setWalletTax(uint8 _tax) external onlyOwner { walletTax = _tax; } function setTreasuryAddress(address _address) external onlyOwner { treasuryAddress = _address; excludedTax[_address] = true; } function setBridgeAddress(address _address) external onlyOwner { bridgeAddress = _address; excludedTax[_address] = true; } function excludeTaxAddress(address _address) external onlyOwner { excludedTax[_address] = true; } function removeTaxAddress(address _address) external onlyOwner { require(_address != address(this), "Not authorized to remove the contract from tax"); excludedTax[_address] = false; } // Bridging feature function mint(address to, uint256 amount) external { require(msg.sender == bridgeAddress, "Only bridge can mint"); _mint(to, amount); } function burn(address to, uint256 amount) external { require(msg.sender == bridgeAddress, "Only bridge can mint"); _burn(to, amount); } // Liquidity settings function setAutoLiquidityFees(uint8 _fees) external onlyOwner { autoLiquidityFees = _fees; } function setMinAmountForSwap(uint216 _amount) external onlyOwner { minAmountForSwap = _amount; } function setUniswapV2Pair(address _pair) external onlyOwner { uniswapV2Pair = _pair; excludedRedistribution.add(_pair); } function setAutoSellingRatio(uint8 ratio) external onlyOwner{ require(autoSellingRatio <= 100, "autoSellingRatio should be lower than 100"); autoSellingRatio = ratio; } // Redistribution management function setRedistributionContract(address _address) external onlyOwner { redistributionContract = _address; excludedRedistribution.add(_address); excludedTax[_address] =true; } function removeRedistributionAddress(address _address) external onlyOwner { excludedRedistribution.remove(_address); } function excludedRedistributionAddress(address _address) external onlyOwner { excludedRedistribution.add(_address); } }
Swap all in one call
uint balanceInAVAX = address(this).balance;
5,382,529
[ 1, 12521, 777, 316, 1245, 745, 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, 11013, 382, 5856, 2501, 273, 1758, 12, 2211, 2934, 12296, 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 ]
./partial_match/1/0x1201FAa7258A48b820619dD57Cd8FdEb25D49b2c/sources/contracts/managed/vendor/BasePool.sol
* @notice "Dry run" `onExitPool`. @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the Vault with the same arguments, along with the number of tokens `recipient` would receive. This function is not meant to be called directly, but rather from a helper contract that fetches current Vault data, such as the protocol swap fee percentage and Pool balances. Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must explicitly use eth_call instead of eth_sendTransaction./ The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, and we don't need to return anything here - it just silences compiler warnings.
function queryExit( bytes32, address sender, address, uint256[] memory balances, uint256, uint256, bytes memory userData ) external override returns (uint256 bptIn, uint256[] memory amountsOut) { _queryAction(sender, balances, userData, _onExitPool); return (bptIn, amountsOut); }
4,227,948
[ 1, 6, 40, 1176, 1086, 6, 1375, 265, 6767, 2864, 8338, 225, 2860, 326, 3844, 434, 605, 1856, 716, 4102, 506, 18305, 329, 628, 1375, 15330, 68, 309, 326, 1375, 265, 6767, 2864, 68, 3953, 4591, 2566, 635, 326, 17329, 598, 326, 1967, 1775, 16, 7563, 598, 326, 1300, 434, 2430, 1375, 20367, 68, 4102, 6798, 18, 1220, 445, 353, 486, 20348, 358, 506, 2566, 5122, 16, 1496, 9178, 628, 279, 4222, 6835, 716, 17675, 783, 17329, 501, 16, 4123, 487, 326, 1771, 7720, 14036, 11622, 471, 8828, 324, 26488, 18, 23078, 1375, 8188, 3714, 18, 2271, 4497, 12521, 9191, 333, 445, 353, 486, 1476, 6541, 358, 2713, 4471, 3189, 30, 326, 4894, 1297, 8122, 999, 13750, 67, 1991, 3560, 434, 13750, 67, 4661, 3342, 18, 19, 1021, 1375, 2463, 68, 11396, 353, 7120, 5122, 4832, 1375, 67, 2271, 1803, 9191, 1427, 4588, 5903, 30093, 333, 3021, 16, 471, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 843, 6767, 12, 203, 3639, 1731, 1578, 16, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 8526, 3778, 324, 26488, 16, 203, 3639, 2254, 5034, 16, 203, 3639, 2254, 5034, 16, 203, 3639, 1731, 3778, 13530, 203, 565, 262, 3903, 3849, 1135, 261, 11890, 5034, 324, 337, 382, 16, 2254, 5034, 8526, 3778, 30980, 1182, 13, 288, 203, 3639, 389, 2271, 1803, 12, 15330, 16, 324, 26488, 16, 13530, 16, 389, 265, 6767, 2864, 1769, 203, 203, 3639, 327, 261, 70, 337, 382, 16, 30980, 1182, 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 ]
pragma solidity ^0.4.19; pragma experimental ABIEncoderV2; library alt_bn128 { uint256 public constant q = 21888242871839275222246405745257275088548364400416034343698204186575808495617; // curve order uint256 public constant n = 21888242871839275222246405745257275088696311157297823662689037894645226208583; // prime field order struct G1Point { uint256 X; uint256 Y; } function add(G1Point p1, G1Point p2) internal view returns (G1Point r) { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; assembly { if iszero(staticcall(not(0), 6, input, 0x80, r, 0x40)) { revert(0, 0) } } } function mul(G1Point p, uint256 s) internal view returns (G1Point r) { uint256[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; assembly { if iszero(staticcall(not(0), 7, input, 0x60, r, 0x40)) { revert(0, 0) } } } function neg(G1Point p) internal returns (G1Point) { // uint n = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.X == 0 && p.Y == 0) return G1Point(0, 0); return G1Point(p.X, n - (p.Y % n)); } function eq(G1Point p1, G1Point p2) internal pure returns (bool) { return p1.X == p2.X && p1.Y == p2.Y; } function add(uint256 x, uint256 y) internal pure returns (uint256) { return addmod(x, y, q); } function mul(uint256 x, uint256 y) internal pure returns (uint256) { return mulmod(x, y, q); } function inv(uint256 x) internal view returns (uint256) { return exp(x, q - 2); } function mod(uint256 x) internal pure returns (uint256) { return x % q; } function sub(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x - y : q - y + x; } function neg(uint256 x) internal pure returns (uint256) { return q - x; } function exp(uint256 base, uint256 exponent) internal view returns (uint256) { uint256[6] memory input; uint256[1] memory output; input[0] = 0x20; // length_of_BASE input[1] = 0x20; // length_of_EXPONENT input[2] = 0x20; // length_of_MODULUS input[3] = base; input[4] = exponent; input[5] = q; assembly { if iszero(staticcall(not(0), 5, input, 0xc0, output, 0x20)) { revert(0, 0) } } return output[0]; } } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); owner = newOwner; newOwner = address(0); OwnershipTransferred(owner, newOwner); } } contract KnowledgeProofVerifier{ function verify(uint256[8] coords) public view returns(bool); } // Verifying one at a time. Not batched contract RangeProofVerifier{ function verify(uint256[10] coords, uint256[5] scalars, uint256[4] ls_coords, uint256[4] rs_coords) public view returns(bool); } contract BulletCoin is Owned { using alt_bn128 for uint256; using alt_bn128 for alt_bn128.G1Point; string public symbol; string public name; address public knowledgeProofVerifierAddress; address public rangeProofVerifierAddress; uint public n = 2; mapping(address => alt_bn128.G1Point) balances; mapping(address => mapping(address =>alt_bn128.G1Point)) pendingTransactions; event Transfer(address indexed _from, address indexed _to, uint X, uint Y); event Receive(address indexed _from, address indexed _to, uint X, uint Y); event Mint(address indexed _from, address indexed _to, uint X, uint Y); function BulletCoin(string _symbol, string _name, address _knowledgeProofVerifierAddress, address _rangeproofVerifierAddress) public{ symbol = _symbol; name = _name; knowledgeProofVerifierAddress = _knowledgeProofVerifierAddress; rangeProofVerifierAddress = _rangeproofVerifierAddress; } function getXOfCommitBalance(address _user) public constant returns(uint256){ return balances[_user].X; } function getYOfCommitBalance(address _user) public constant returns(uint256){ return balances[_user].Y; } function transfer(address _to, uint256[20] coords, uint256[10] scalars, uint256[8] ls_coords, uint256[8] rs_coords) external returns(bool){ address to = address(_to); require(pendingTransactions[msg.sender][to].eq(alt_bn128.G1Point(0,0))); alt_bn128.G1Point memory transferAmount = alt_bn128.G1Point(coords[0], coords[1]); alt_bn128.G1Point memory endBalance = alt_bn128.G1Point(coords[10], coords[11]); require(endBalance.eq(balances[msg.sender].add(transferAmount.neg()))); uint256[10] memory coordsTemp; uint256[5] memory scalarsTemp; uint256[4] memory lstemp; uint256[4] memory rstemp; for(uint8 i = 0 ; i < 2; i++){ uint8 j = 0; for(j = 0; j < coordsTemp.length; j++){ coordsTemp[j] = coords[i*10+j]; } for(j = 0; j < scalarsTemp.length;j++){ scalarsTemp[j] = scalars[i*5+j]; } for(j = 0; j < lstemp.length; j++){ lstemp[j] = ls_coords[i*4+j]; rstemp[j] = rs_coords[i*4+j]; } require(RangeProofVerifier(rangeProofVerifierAddress).verify(coordsTemp, scalarsTemp, lstemp, rstemp)); } balances[msg.sender] = endBalance; pendingTransactions[msg.sender][to] = transferAmount; emit Transfer(msg.sender, to, transferAmount.X, transferAmount.Y); } function recieve(address _from, uint256[6] coords) public returns(bool){ require(!pendingTransactions[_from][msg.sender].eq(alt_bn128.G1Point(0,0))); alt_bn128.G1Point memory endBalance = balances[msg.sender].add(pendingTransactions[_from][msg.sender]); uint256[8] memory passOn; passOn[0] = endBalance.X; passOn[1] = endBalance.Y; uint8 j; for(j = 0; j < 6; j++){ passOn[j+2] = coords[j]; } require(KnowledgeProofVerifier(knowledgeProofVerifierAddress).verify(passOn)); uint256 X = pendingTransactions[_from][msg.sender].X; uint256 Y = pendingTransactions[_from][msg.sender].Y; pendingTransactions[_from][msg.sender] = alt_bn128.G1Point(0,0); balances[msg.sender] = endBalance; emit Receive(_from, msg.sender, X, Y); } function mint(address _to, uint256 _x, uint256 _y) onlyOwner public returns(bool){ require(pendingTransactions[msg.sender][_to].eq(alt_bn128.G1Point(0,0))); alt_bn128.G1Point memory transferAmount = alt_bn128.G1Point(_x, _y); pendingTransactions[msg.sender][_to] = transferAmount; emit Mint(msg.sender, _to, transferAmount.X, transferAmount.Y); } function () public payable{ revert(); } }
Verifying one at a time. Not batched
contract RangeProofVerifier{ function verify(uint256[10] coords, uint256[5] scalars, uint256[4] ls_coords, uint256[4] rs_coords) public view returns(bool); }
1,776,685
[ 1, 8097, 310, 1245, 622, 279, 813, 18, 2288, 2581, 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, 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, 8086, 20439, 17758, 95, 203, 565, 445, 3929, 12, 11890, 5034, 63, 2163, 65, 6074, 16, 2254, 5034, 63, 25, 65, 23743, 16, 2254, 5034, 63, 24, 65, 7180, 67, 9076, 16, 2254, 5034, 63, 24, 65, 3597, 67, 9076, 13, 1071, 1476, 1135, 12, 6430, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity >= 0.4.0; contract DirectRegistry{ enum RegistryStatus { Unknown, Active, OffLine, Decommissioned } struct RegistryInfo { bytes32 orgId; string uri; bytes32 scAddr; bytes32[] appTypeIds; RegistryStatus status; } event RegistryAddEvent( bytes32 orgId, string uri, bytes32 scAddr, bytes32[] appTypeIds, RegistryStatus status ); event RegistryUpdateEvent( bytes32 orgId, string uri, bytes32 scAddr, bytes32[] appTypeIds ); event RegistrySetStatusEvent( bytes32 orgId, RegistryStatus status ); // To know the contractor owner address private contractOwner; // Map of registryInfo identified by key registryId mapping (bytes32 => RegistryInfo) private registryMap; // Map of index to wokerId mapping (uint => bytes32) private registryList; // Total number of registries uint private registryCount; constructor() public { contractOwner = msg.sender; registryCount = 0; } // Restrict to call registryRegister by authorised contract owner or // is registry is of known organization. modifier onlyOwner() { require( msg.sender == contractOwner, "Sender not authorized" ); _; } function registryAdd ( bytes32 orgId, string memory uri, bytes32 scAddr, bytes32[] memory appTypeIds) public onlyOwner() { // Add a new registry entry to registry list // with registry list organization id, uri, smart contract // address of worker registry contract and application type ids require(orgId.length != 0, "Empty org id"); require(bytes(uri).length != 0, "Empty uri"); require(scAddr.length != 0, "Empty address"); // Check if registry exists, if yes then error RegistryInfo memory registry = registryMap[orgId]; require(registry.orgId != orgId && registry.scAddr != scAddr, "Registry exists with these details"); registryMap[orgId] = RegistryInfo( orgId, uri, scAddr, appTypeIds, RegistryStatus.Active); // Insert to registryList with current registryCount as key and registryId as value. registryList[registryCount] = orgId; // Increment registry count registryCount++; emit RegistryAddEvent(orgId, uri, scAddr, appTypeIds, RegistryStatus.Active); } function registryUpdate(bytes32 orgId, string memory uri, bytes32 scAddr, bytes32[] memory appTypeIds) public { // Update registry with identified by organization id require(orgId.length != 0, "Empty org id"); require(bytes(uri).length != 0, "Empty uri"); require(scAddr.length != 0, "Empty address"); // Check if registry already exists, if yes then update the registryMap RegistryInfo memory registry = registryMap[orgId]; require(registry.orgId == orgId, "Registry doesn't exist with these details"); registryMap[orgId].uri = uri; registryMap[orgId].scAddr = scAddr; for (uint i = 0; i < appTypeIds.length; i++) { bool exists = false; for (uint j = 0; j < registry.appTypeIds.length; j++) { if (registry.appTypeIds[j] == appTypeIds[i]) { exists = true; break; } } if (!exists) { registryMap[orgId].appTypeIds.push(appTypeIds[i]); } } emit RegistryUpdateEvent(orgId, uri, scAddr, appTypeIds); } function registrySetStatus(bytes32 orgId, RegistryStatus status) public { // Set the registry status identified by organization id require(orgId.length != 0, "Empty org id"); require(registryMap[orgId].orgId == orgId, "orgId doesn't exist"); registryMap[orgId].status = status; emit RegistrySetStatusEvent(orgId, status); } function registryLookUp(bytes32 appTypeId) public view returns( uint totalCount, string memory lookUpTag, bytes32[] memory orgIds) { uint wCount = 0; // lookUpTag is empty now, need to implement with specific content // to be used to get the next available registries. string memory lookUpString = ""; // Since solidity doesn't support returning dynamic array of memory storage, // allocate the array with registry count. bytes32[] memory wList = new bytes32[](registryCount); for (uint i = 0; i < registryCount; i++) { // Do lookup in registryList with an index and get the registry id // and use it to lookup in registryMap RegistryInfo memory registry = registryMap[registryList[i]]; if (appTypeId != 0) { for(uint j = 0; j < registry.appTypeIds.length; j++) { if (registry.appTypeIds[j] == appTypeId) { //If match, update registry list and registry count wList[wCount] = registry.orgId; wCount ++; } } } else { wList[wCount] = registry.orgId; wCount ++; } } // If array size is smaller than registry count then return only required size array. if (wCount < registryCount) { bytes32[] memory result = new bytes32[](wCount); for (uint k = 0; k < wCount; k++) { result[k] = wList[k]; } return (wCount, lookUpString, result); } return (wCount, lookUpString, wList); } function registryRetrieve(bytes32 orgId) public view returns ( string memory _uri, bytes32 _scAddr, bytes32[] memory _appTypeIds, RegistryStatus status) { // Retrieve registry details identified by orgId require(orgId.length != 0, "Empty org id"); require(registryMap[orgId].orgId == orgId, "orgId doesn't exist"); // Do lookup with the given registryId from registryMap RegistryInfo memory registry = registryMap[orgId]; return (registry.uri, registry.scAddr, registry.appTypeIds, registry.status); } //stub for registryLookUpNext function registryLookUpNext( bytes32 appTypeId, string memory lookUpTag) public pure returns( int totalCount, string memory newLookupTag, bytes32[] memory registryIds) { require(appTypeId.length != 0, "Empty Application id"); require(bytes(lookUpTag).length != 0, "lookUpTag is empty"); bytes32[] memory wIds; string memory newTag = ""; int count = 0; return (count, newTag, wIds); } }
Map of registryInfo identified by key registryId
mapping (bytes32 => RegistryInfo) private registryMap;
931,536
[ 1, 863, 434, 4023, 966, 9283, 635, 498, 4023, 548, 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, 2874, 261, 3890, 1578, 516, 5438, 966, 13, 225, 3238, 4023, 863, 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 ]
pragma solidity ^0.4.24; /* * ZETHR PRESENTS: SLOTS * * Written August 2018 by the Zethr team for zethr.io. * * Code framework written by Norsefire. * EV calculations written by TropicalRogue. * Audit and edits written by Klob. * Multiroll framework written by Etherguy. * * Rolling Odds: * 49.31% Lose / 50.69% Win * 35.64% Two Matching Icons * - 10.00% : 2.50x Multiplier [Two Rockets] * - 15.00% : 1.33x Multiplier [Two Gold Pyramids] * - 15.00% : 1.00x Multiplier [Two 'Z' Symbols] * - 15.00% : 1.00x Multiplier [Two 'T' Symbols] * - 15.00% : 1.00x Multiplier [Two 'H' Symbols] * - 15.00% : 1.25x Multiplier [Two Purple Pyramids] * - 15.00% : 2.00x Multiplier [Two Ether Icons] * 6.79% One Of Each Pyramid * - 1.50x Multiplier * 2.94% One Moon Icon * - 2.50x Multiplier * 5.00% Three Matching Icons * - 03.00% : 13.00x Multiplier [Three Rockets] * - 05.00% : 09.00x Multiplier [Three Gold Pyramids] * - 27.67% : 03.00x Multiplier [Three 'Z' Symbols] * - 27.67% : 03.00x Multiplier [Three 'T' Symbols] * - 27.67% : 03.00x Multiplier [Three 'H' Symbols] * - 05.00% : 07.50x Multiplier [Three Purple Pyramids] * - 04.00% : 11.00x Multiplier [Three Ether Icons] * 0.28% Z T H Prize * - 20x Multiplier * 0.03% Two Moon Icons * - 50x Multiplier * 0.0001% Three Moon Grand Jackpot * - Jackpot Amount (variable) * * From all of us at Zethr, thank you for playing! * */ // Zethr Token Bankroll interface contract ZethrTokenBankroll{ // Game request token transfer to player function gameRequestTokens(address target, uint tokens) public; function gameTokenAmount(address what) public returns (uint); } // Zether Main Bankroll interface contract ZethrMainBankroll{ function gameGetTokenBankrollList() public view returns (address[7]); } // Zethr main contract interface contract ZethrInterface{ function withdraw() public; } // Library for figuring out the "tier" (1-7) of a dividend rate library ZethrTierLibrary{ function getTier(uint divRate) internal pure returns (uint) { // Tier logic // Returns the index of the UsedBankrollAddresses which should be used to call into to withdraw tokens // We can divide by magnitude // Remainder is removed so we only get the actual number we want uint actualDiv = divRate; if (actualDiv >= 30){ return 6; } else if (actualDiv >= 25){ return 5; } else if (actualDiv >= 20){ return 4; } else if (actualDiv >= 15){ return 3; } else if (actualDiv >= 10){ return 2; } else if (actualDiv >= 5){ return 1; } else if (actualDiv >= 2){ return 0; } else{ // Impossible revert(); } } } // Contract that contains the functions to interact with the ZlotsJackpotHoldingContract contract ZlotsJackpotHoldingContract { function payOutWinner(address winner) public; function getJackpot() public view returns (uint); } // Contract that contains the functions to interact with the bankroll system contract ZethrBankrollBridge { // Must have an interface with the main Zethr token contract ZethrInterface Zethr; // Store the bankroll addresses // address[0] is tier1: 2-5% // address[1] is tier2: 5-10, etc address[7] UsedBankrollAddresses; // Mapping for easy checking mapping(address => bool) ValidBankrollAddress; // Set up the tokenbankroll stuff function setupBankrollInterface(address ZethrMainBankrollAddress) internal { // Instantiate Zethr Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D); // Get the bankroll addresses from the main bankroll UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); for(uint i=0; i<7; i++){ ValidBankrollAddress[UsedBankrollAddresses[i]] = true; } } // Require a function to be called from a *token* bankroll modifier fromBankroll() { require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); _; } // Request a payment in tokens to a user FROM the appropriate tokenBankroll // Figure out the right bankroll via divRate function RequestBankrollPayment(address to, uint tokens, uint tier) internal { address tokenBankrollAddress = UsedBankrollAddresses[tier]; ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); } function getZethrTokenBankroll(uint divRate) public constant returns (ZethrTokenBankroll) { return ZethrTokenBankroll(UsedBankrollAddresses[ZethrTierLibrary.getTier(divRate)]); } } // Contract that contains functions to move divs to the main bankroll contract ZethrShell is ZethrBankrollBridge { // Dump ETH balance to main bankroll function WithdrawToBankroll() public { address(UsedBankrollAddresses[0]).transfer(address(this).balance); } // Dump divs and dump ETH into bankroll function WithdrawAndTransferToBankroll() public { Zethr.withdraw(); WithdrawToBankroll(); } } // Zethr game data setup // Includes all necessary to run with Zethr contract ZlotsMulti is ZethrShell { using SafeMath for uint; // ---------------------- Events // Might as well notify everyone when the house takes its cut out. event HouseRetrievedTake( uint timeTaken, uint tokensWithdrawn ); // Fire an event whenever someone places a bet. event TokensWagered( address _wagerer, uint _wagered ); event LogResult( address _wagerer, uint _result, uint _profit, uint _wagered, uint _category, bool _win ); // Result announcement events (to dictate UI output!) event Loss(address _wagerer, uint _block); // Category 0 event ThreeMoonJackpot(address _wagerer, uint _block); // Category 1 event TwoMoonPrize(address _wagerer, uint _block); // Category 2 event ZTHPrize(address _wagerer, uint _block); // Category 3 event ThreeZSymbols(address _wagerer, uint _block); // Category 4 event ThreeTSymbols(address _wagerer, uint _block); // Category 5 event ThreeHSymbols(address _wagerer, uint _block); // Category 6 event ThreeEtherIcons(address _wagerer, uint _block); // Category 7 event ThreePurplePyramids(address _wagerer, uint _block); // Category 8 event ThreeGoldPyramids(address _wagerer, uint _block); // Category 9 event ThreeRockets(address _wagerer, uint _block); // Category 10 event OneMoonPrize(address _wagerer, uint _block); // Category 11 event OneOfEachPyramidPrize(address _wagerer, uint _block); // Category 12 event TwoZSymbols(address _wagerer, uint _block); // Category 13 event TwoTSymbols(address _wagerer, uint _block); // Category 14 event TwoHSymbols(address _wagerer, uint _block); // Category 15 event TwoEtherIcons(address _wagerer, uint _block); // Category 16 event TwoPurplePyramids(address _wagerer, uint _block); // Category 17 event TwoGoldPyramids(address _wagerer, uint _block); // Category 18 event TwoRockets(address _wagerer, uint _block); // Category 19 event SpinConcluded(address _wagerer, uint _block); // Debug event // ---------------------- Modifiers // Makes sure that player porfit can't exceed a maximum amount // We use the max win here - 50x modifier betIsValid(uint _betSize, uint divRate, uint8 spins) { require(_betSize.div(spins).mul(50) <= getMaxProfit(divRate)); require(_betSize.div(spins) >= minBet); _; } // Requires the game to be currently active modifier gameIsActive { require(gamePaused == false); _; } // Require msg.sender to be owner modifier onlyOwner { require(msg.sender == owner); _; } // Requires msg.sender to be bankroll modifier onlyBankroll { require(msg.sender == bankroll); _; } // Requires msg.sender to be owner or bankroll modifier onlyOwnerOrBankroll { require(msg.sender == owner || msg.sender == bankroll); _; } // ---------------------- Variables // Configurables uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; mapping (uint => uint) public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet = 1e18; address public zlotsJackpot; address private owner; address private bankroll; bool gamePaused; // Trackers uint public totalSpins; uint public totalZTHWagered; mapping (uint => uint) public contractBalance; // Is betting allowed? (Administrative function, in the event of unforeseen bugs) bool public gameActive; // Bankroll & token addresses address private ZTHTKNADDR; address private ZTHBANKROLL; // ---------------------- Functions // Constructor; must supply bankroll address constructor(address BankrollAddress) public { // Set up the bankroll interface setupBankrollInterface(BankrollAddress); // Owner is deployer owner = msg.sender; // Default max profit to 5% of contract balance ownerSetMaxProfitAsPercentOfHouse(50000); // Set starting variables bankroll = ZTHBANKROLL; gameActive = true; // Init min bet (1 ZTH) ownerSetMinBet(1e18); } // Zethr dividends gained are accumulated and sent to bankroll manually function() public payable { } // If the contract receives tokens, bundle them up in a struct and fire them over to _spinTokens for validation. struct TKN { address sender; uint value; } function execute(address _from, uint _value, uint divRate, bytes _data) public fromBankroll returns (bool) { TKN memory _tkn; _tkn.sender = _from; _tkn.value = _value; _spinTokens(_tkn, divRate, uint8(_data[0])); return true; } struct playerSpin { uint192 tokenValue; // Token value in uint uint48 blockn; // Block number 48 bits uint8 tier; uint8 spins; uint divRate; } // Mapping because a player can do one spin at a time mapping(address => playerSpin) public playerSpins; // Execute spin. function _spinTokens(TKN _tkn, uint divRate, uint8 spins) private betIsValid(_tkn.value, divRate, spins) { require(gameActive); require(block.number <= ((2 ** 48) - 1)); // Current block number smaller than storage of 1 uint56 require(_tkn.value <= ((2 ** 192) - 1)); address _customerAddress = _tkn.sender; uint _wagered = _tkn.value; playerSpin memory spin = playerSpins[_tkn.sender]; // We update the contract balance *before* the spin is over, not after // This means that we don't have to worry about unresolved rolls never resolving // (we also update it when a player wins) addContractBalance(divRate, _wagered); // Cannot spin twice in one block require(block.number != spin.blockn); // If there exists a spin, finish it if (spin.blockn != 0) { _finishSpin(_tkn.sender); } // Set struct block number and token value spin.blockn = uint48(block.number); spin.tokenValue = uint192(_wagered.div(spins)); spin.tier = uint8(ZethrTierLibrary.getTier(divRate)); spin.divRate = divRate; spin.spins = spins; // Store the roll struct - 40k gas. playerSpins[_tkn.sender] = spin; // Increment total number of spins totalSpins += spins; // Total wagered totalZTHWagered += _wagered; emit TokensWagered(_customerAddress, _wagered); } // Finish the current spin of a player, if they have one function finishSpin() public gameIsActive returns (uint[]) { return _finishSpin(msg.sender); } // Stores the data for the roll (spin) struct rollData { uint win; uint loss; uint jp; } // Pay winners, update contract balance, send rewards where applicable. function _finishSpin(address target) private returns (uint[]) { playerSpin memory spin = playerSpins[target]; require(spin.tokenValue > 0); // No re-entrancy require(spin.blockn != block.number); uint[] memory output = new uint[](spin.spins); rollData memory outcomeTrack = rollData(0,0,0); uint category = 0; uint profit; uint playerDivrate = spin.divRate; for(uint i=0; i<spin.spins; i++) { // If the block is more than 255 blocks old, we can't get the result // Also, if the result has already happened, fail as well uint result; if (block.number - spin.blockn > 255) { result = 1000000; // Can't win: default to largest number output[i] = 1000000; } else { // Generate a result - random based ONLY on a past block (future when submitted). // Case statement barrier numbers defined by the current payment schema at the top of the contract. result = random(1000000, spin.blockn, target, i) + 1; output[i] = result; } if (result > 506856) { // Player has lost. Womp womp. // Add one percent of player loss to the jackpot // (do this by requesting a payout to the jackpot) outcomeTrack.loss += spin.tokenValue/100; emit Loss(target, spin.blockn); emit LogResult(target, result, profit, spin.tokenValue, category, false); } else if (result < 2) { // Player has won the three-moon mega jackpot! // Get profit amount via jackpot profit = ZlotsJackpotHoldingContract(zlotsJackpot).getJackpot(); category = 1; // Emit events emit ThreeMoonJackpot(target, spin.blockn); emit LogResult(target, result, profit, spin.tokenValue, category, true); outcomeTrack.jp += 1; } else { if (result < 299) { // Player has won a two-moon prize! profit = SafeMath.mul(spin.tokenValue, 50); category = 2; emit TwoMoonPrize(target, spin.blockn); } else if (result < 3128) { // Player has won the Z T H prize! profit = SafeMath.mul(spin.tokenValue, 20); category = 3; emit ZTHPrize(target, spin.blockn); } else if (result < 16961) { // Player has won a three Z symbol prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); category = 4; emit ThreeZSymbols(target, spin.blockn); } else if (result < 30794) { // Player has won a three T symbol prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); category = 5; emit ThreeTSymbols(target, spin.blockn); } else if (result < 44627) { // Player has won a three H symbol prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); category = 6; emit ThreeHSymbols(target, spin.blockn); } else if (result < 46627) { // Player has won a three Ether icon prize! profit = SafeMath.mul(spin.tokenValue, 11); category = 7; emit ThreeEtherIcons(target, spin.blockn); } else if (result < 49127) { // Player has won a three purple pyramid prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); category = 8; emit ThreePurplePyramids(target, spin.blockn); } else if (result < 51627) { // Player has won a three gold pyramid prize! profit = SafeMath.mul(spin.tokenValue, 9); category = 9; emit ThreeGoldPyramids(target, spin.blockn); } else if (result < 53127) { // Player has won a three rocket prize! profit = SafeMath.mul(spin.tokenValue, 13); category = 10; emit ThreeRockets(target, spin.blockn); } else if (result < 82530) { // Player has won a one moon prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25),10); category = 11; emit OneMoonPrize(target, spin.blockn); } else if (result < 150423) { // Player has won a each-coloured-pyramid prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); category = 12; emit OneOfEachPyramidPrize(target, spin.blockn); } else if (result < 203888) { // Player has won a two Z symbol prize! profit = spin.tokenValue; category = 13; emit TwoZSymbols(target, spin.blockn); } else if (result < 257353) { // Player has won a two T symbol prize! profit = spin.tokenValue; category = 14; emit TwoTSymbols(target, spin.blockn); } else if (result < 310818) { // Player has won a two H symbol prize! profit = spin.tokenValue; category = 15; emit TwoHSymbols(target, spin.blockn); } else if (result < 364283) { // Player has won a two Ether icon prize! profit = SafeMath.mul(spin.tokenValue, 2); category = 16; emit TwoEtherIcons(target, spin.blockn); } else if (result < 417748) { // Player has won a two purple pyramid prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125), 100); category = 17; emit TwoPurplePyramids(target, spin.blockn); } else if (result < 471213) { // Player has won a two gold pyramid prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133), 100); category = 18; emit TwoGoldPyramids(target, spin.blockn); } else { // Player has won a two rocket prize! profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25), 10); category = 19; emit TwoRockets(target, spin.blockn); } uint newMaxProfit = getNewMaxProfit(playerDivrate, outcomeTrack.win); if (profit > newMaxProfit){ profit = newMaxProfit; } emit LogResult(target, result, profit, spin.tokenValue, category, true); outcomeTrack.win += profit; } } playerSpins[target] = playerSpin(uint192(0), uint48(0), uint8(0), uint8(0), uint(0)); if (outcomeTrack.jp > 0) { for (i = 0; i < outcomeTrack.jp; i++) { // In the weird case a player wins two jackpots, we of course pay them twice ZlotsJackpotHoldingContract(zlotsJackpot).payOutWinner(target); } } if (outcomeTrack.win > 0) { RequestBankrollPayment(target, outcomeTrack.win, spin.tier); } if (outcomeTrack.loss > 0) { // This loss is the loss to pay to the jackpot account // The delta in contractBalance is already updated in a pending bet. RequestBankrollPayment(zlotsJackpot, outcomeTrack.loss, spin.tier); } emit SpinConcluded(target, spin.blockn); return output; } // Returns a random number using a specified block number // Always use a FUTURE block number. function maxRandom(uint blockn, address entropy, uint index) private view returns (uint256 randomNumber) { return uint256(keccak256( abi.encodePacked( blockhash(blockn), entropy, index ))); } // Random helper function random(uint256 upper, uint256 blockn, address entropy, uint index) internal view returns (uint256 randomNumber) { return maxRandom(blockn, entropy, index) % upper; } // Sets max profit (internal) function setMaxProfit(uint divRate) internal { maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; } // Gets max profit function getMaxProfit(uint divRate) public view returns (uint) { return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; } function getNewMaxProfit(uint divRate, uint currentWin) public view returns (uint) { return ((contractBalance[divRate] - currentWin) * maxProfitAsPercentOfHouse) / maxProfitDivisor; } // Subtracts from the contract balance tracking var function subContractBalance(uint divRate, uint sub) internal { contractBalance[divRate] = contractBalance[divRate].sub(sub); } // Adds to the contract balance tracking var function addContractBalance(uint divRate, uint add) internal { contractBalance[divRate] = contractBalance[divRate].add(add); } // An EXTERNAL update of tokens should be handled here // This is due to token allocation // The game should handle internal updates itself (e.g. tokens are betted) function bankrollExternalUpdateTokens(uint divRate, uint newBalance) public fromBankroll { contractBalance[divRate] = newBalance; setMaxProfit(divRate); } // Set the new max profit as percent of house - can be as high as 20% // (1,000,000 = 100%) function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { // Restricts each bet to a maximum profit of 50% contractBalance require(newMaxProfitAsPercent <= 500000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(2); setMaxProfit(5); setMaxProfit(10); setMaxProfit(15); setMaxProfit(20); setMaxProfit(25); setMaxProfit(33); } // Only owner can set minBet function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } // Only owner can set zlotsJackpot address function ownerSetZlotsAddress(address zlotsAddress) public onlyOwner { zlotsJackpot = zlotsAddress; } // If, for any reason, betting needs to be paused (very unlikely), this will freeze all bets. function pauseGame() public onlyOwnerOrBankroll { gameActive = false; } // The converse of the above, resuming betting if a freeze had been put in place. function resumeGame() public onlyOwnerOrBankroll { gameActive = true; } // Administrative function to change the owner of the contract. function changeOwner(address _newOwner) public onlyOwnerOrBankroll { owner = _newOwner; } // Administrative function to change the Zethr bankroll contract, should the need arise. function changeBankroll(address _newBankroll) public onlyOwnerOrBankroll { bankroll = _newBankroll; } // Is the address that the token has come from actually ZTH? function _zthToken(address _tokenContract) private view returns (bool) { return _tokenContract == ZTHTKNADDR; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint) { uint c = a / b; return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } }
Is betting allowed? (Administrative function, in the event of unforeseen bugs)
bool public gameActive;
10,460,886
[ 1, 2520, 2701, 1787, 2935, 35, 261, 4446, 3337, 1535, 445, 16, 316, 326, 871, 434, 640, 1405, 15156, 22398, 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 ]
[ 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, 1426, 1071, 7920, 3896, 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, -100 ]
./full_match/3/0xcd1A015321B183cB5Ea046a4C80dd6E88B89F3b5/sources/browser/DePayPaymentProcessorV1.sol
Executes processors in the order provided. Calls itself's _pay function if the payment processor contract itself is part of processors.
function _process( address[] calldata path, uint[] calldata amounts, address[] calldata addresses, address[] calldata processors, string[] calldata data ) internal { for (uint i = 0; i < processors.length; i++) { if(processors[i] == address(this)) { _pay(payable(addresses[addresses.length-1]), path[path.length-1], amounts[1]); require(_isApproved(processors[i]), 'DePay: Processor not approved!'); address processor = approvedProcessors[processors[i]]; (bool success, bytes memory returnData) = processor.delegatecall(abi.encodeWithSelector( IDePayPaymentProcessorV1Processor(processor).process.selector, path, amounts, addresses, data )); require(success, string(returnData)); } } }
8,162,621
[ 1, 9763, 13399, 316, 326, 1353, 2112, 18, 23665, 6174, 1807, 389, 10239, 445, 309, 326, 5184, 6659, 6835, 6174, 353, 1087, 434, 13399, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 2567, 12, 203, 565, 1758, 8526, 745, 892, 589, 16, 203, 565, 2254, 8526, 745, 892, 30980, 16, 203, 565, 1758, 8526, 745, 892, 6138, 16, 203, 565, 1758, 8526, 745, 892, 13399, 16, 203, 565, 533, 8526, 745, 892, 501, 203, 225, 262, 2713, 288, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 13399, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 12, 22962, 63, 77, 65, 422, 1758, 12, 2211, 3719, 288, 203, 3639, 389, 10239, 12, 10239, 429, 12, 13277, 63, 13277, 18, 2469, 17, 21, 65, 3631, 589, 63, 803, 18, 2469, 17, 21, 6487, 30980, 63, 21, 19226, 203, 3639, 2583, 24899, 291, 31639, 12, 22962, 63, 77, 65, 3631, 296, 758, 9148, 30, 15476, 486, 20412, 5124, 1769, 203, 3639, 1758, 6659, 273, 20412, 18155, 63, 22962, 63, 77, 13563, 31, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 751, 13, 273, 6659, 18, 22216, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 203, 5411, 467, 758, 9148, 6032, 5164, 58, 21, 5164, 12, 8700, 2934, 2567, 18, 9663, 16, 589, 16, 30980, 16, 6138, 16, 501, 203, 3639, 262, 1769, 203, 3639, 2583, 12, 4768, 16, 533, 12, 2463, 751, 10019, 203, 1377, 289, 203, 565, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @author Alchemy Team /// @title Alchemy /// @notice The Alchemy Governance Token contract ALCH { /// @notice EIP-20 token name for this token string public constant name = "Alchemy"; /// @notice EIP-20 token symbol for this token string public constant symbol = "ALCH"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Address which may mint new tokens address public minter; /// @notice The timestamp after which minting may occur uint256 public mintingAllowedAfter; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 10; /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 90 days; /// @notice Total number of tokens in circulation uint256 public totalSupply = 10_000_000e18; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; mapping(address => address) public delegates; struct Checkpoint { uint32 fromBlock; uint96 votes; } mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; mapping(address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" ); bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); mapping(address => uint256) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); constructor(address account, address minter_, uint256 mintingAllowedAfter_) { require( mintingAllowedAfter_ >= block.timestamp, "Alch::constructor: minting can only begin after deployment" ); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); mintingAllowedAfter = mintingAllowedAfter_; } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Alch::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Alch::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "Alch::mint: minting not allowed yet"); require(dst != address(0), "Alch::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(rawAmount, "Alch::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "Alch::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "Alch::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Alch::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Alch::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Alch::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline ) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Alch::permit: invalid signature"); require(signatory == owner, "Alch::permit: unauthorized"); require(block.timestamp <= deadline, "Alch::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function balanceOf(address account) external view returns (uint256) { return balances[account]; } function nonceOf(address account) external view returns (uint256) { return nonces[account]; } function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Alch::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Alch::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Alch::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Alch::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Alch::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "Alch::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require( blockNumber < block.number, "Alch::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require( src != address(0), "Alch::_transferTokens: cannot transfer from the zero address" ); require( dst != address(0), "Alch::_transferTokens: cannot transfer to the zero address" ); balances[src] = sub96( balances[src], amount, "Alch::_transferTokens: transfer amount exceeds balance" ); balances[dst] = add96( balances[dst], amount, "Alch::_transferTokens: transfer amount overflows" ); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96( srcRepOld, amount, "Alch::_moveVotes: vote amount underflows" ); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96( dstRepOld, amount, "Alch::_moveVotes: vote amount overflows" ); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, "Alch::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
@notice EIP-20 token name for this token @notice EIP-20 token symbol for this token @notice EIP-20 token decimals for this token @notice Address which may mint new tokens @notice The timestamp after which minting may occur @notice Cap on the percentage of totalSupply that can be minted at each mint @notice Minimum time between mints @notice Total number of tokens in circulation
struct Checkpoint { uint32 fromBlock; uint96 votes; } mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; mapping(address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" ); bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); mapping(address => uint256) public nonces; event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount );
1,075,236
[ 1, 41, 2579, 17, 3462, 1147, 508, 364, 333, 1147, 225, 512, 2579, 17, 3462, 1147, 3273, 364, 333, 1147, 225, 512, 2579, 17, 3462, 1147, 15105, 364, 333, 1147, 225, 5267, 1492, 2026, 312, 474, 394, 2430, 225, 1021, 2858, 1839, 1492, 312, 474, 310, 2026, 3334, 225, 11200, 603, 326, 11622, 434, 2078, 3088, 1283, 716, 848, 506, 312, 474, 329, 622, 1517, 312, 474, 225, 23456, 813, 3086, 312, 28142, 225, 10710, 1300, 434, 2430, 316, 5886, 1934, 367, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 10525, 19588, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 203, 3639, 315, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 203, 565, 11272, 203, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 2689, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 203, 3639, 315, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 203, 565, 11272, 203, 203, 565, 1731, 1578, 1071, 5381, 10950, 6068, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 203, 3639, 315, 9123, 305, 12, 2867, 3410, 16, 2867, 17571, 264, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 203, 565, 11272, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1661, 764, 31, 203, 203, 203, 565, 871, 27687, 5033, 12, 203, 3639, 1758, 8808, 11158, 639, 16, 203, 3639, 1758, 8808, 628, 9586, 16, 203, 3639, 1758, 8808, 358, 9586, 203, 565, 11272, 203, 203, 565, 871, 27687, 29637, 5033, 12, 203, 3639, 1758, 8808, 7152, 16, 203, 3639, 2254, 5034, 2416, 13937, 16, 203, 3639, 2254, 5034, 394, 13937, 203, 565, 11272, 2 ]
./full_match/5/0x6bdB254F033d597EEB1caee9548F7C88aBE54D35/sources/contracts/CrowdFunding.sol
(bool sent, ) = payable(campaign.owner).call{value: amount}(""); if(sent) { campaign.amountCollected = campaign.amountCollected + amount; }
function donateToCampaign(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); campaign.amountCollected = campaign.amountCollected + amount; }
7,090,359
[ 1, 12, 6430, 3271, 16, 262, 273, 8843, 429, 12, 14608, 18, 8443, 2934, 1991, 95, 1132, 30, 3844, 97, 2932, 8863, 309, 12, 7569, 13, 288, 377, 8965, 18, 8949, 10808, 329, 273, 8965, 18, 8949, 10808, 329, 397, 3844, 31, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2727, 340, 774, 13432, 12, 11890, 5034, 389, 350, 13, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 3844, 273, 1234, 18, 1132, 31, 203, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 67, 350, 15533, 203, 203, 3639, 8965, 18, 19752, 3062, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 8965, 18, 19752, 1012, 18, 6206, 12, 8949, 1769, 203, 203, 203, 3639, 8965, 18, 8949, 10808, 329, 273, 8965, 18, 8949, 10808, 329, 397, 3844, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; abstract contract OwnerOperatorControl is AccessControlUpgradeable { bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); function __OwnerOperatorControl_init() internal { __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Role: not Admin'); _; } modifier onlyOperator() { require(isOperator(_msgSender()), 'Role: not Operator'); _; } function isOperator(address _address) public view returns (bool) { return hasRole(OPERATOR_ROLE, _address); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import './OwnerOperatorControl.sol'; abstract contract OwnerOperatorControlWithSignature is OwnerOperatorControl { /** * @dev Verify that mint was aknowledge by an operator */ function requireOperatorSignature( bytes32 message, uint8 v, bytes32 r, bytes32 s ) public view { require(isOperator(recoverSigner(message, v, r, s)), 'Wrong Signature'); } // for whatever reason I can't get ECDSA.recover to work so let's go old school function recoverSigner( bytes32 message, uint8 v, bytes32 r, bytes32 s ) public pure returns (address) { if (v < 27) { v += 27; } return ecrecover( keccak256( abi.encodePacked( '\x19Ethereum Signed Message:\n32', message ) ), v, r, s ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import './Access/OwnerOperatorControlWithSignature.sol'; import './Tokens/ERC1155/ERC1155Configurable.sol'; import './Tokens/ERC1155/ERC1155WithRoyalties.sol'; import './Tokens/ERC1155/ERC1155WithMetadata.sol'; import './GroupedURI/GroupedURI.sol'; contract BeyondNFT1155V2 is OwnerOperatorControlWithSignature, ERC1155Configurable, ERC1155WithRoyalties, ERC1155WithMetadata, GroupedURI { // function initialize(string memory uri, address _minter) public initializer { // require(_minter != address(0)); // __OwnerOperatorControl_init(); // already inits context and ERC165 // __ERC1155WithRoyalties_init(); // __ERC1155WithMetadata_init(uri); // _setupRole(OPERATOR_ROLE, _minter); // } receive() external payable { revert('No value accepted'); } function mint( uint256 id, uint256 supply, string memory uri_, uint8 v, bytes32 r, bytes32 s, uint256 royalties, address royaltiesRecipient ) external { require(!minted(id), 'ERC1155: Already minted'); address sender = _msgSender(); requireOperatorSignature( prepareMessage(sender, id, supply, uri_), v, r, s ); _mint(sender, id, supply, bytes('')); _setMetadata(id, uri_, sender); if (royalties > 0) { _setRoyalties(id, royaltiesRecipient, royalties); } } function burn( address owner, uint256 id, uint256 amount ) external { require( owner == _msgSender() || isApprovedForAll(owner, _msgSender()), 'ERC1155: caller is not owner nor approved' ); _burn(owner, id, amount); } function burnBatch( address owner, uint256[] memory ids, uint256[] memory amounts ) external { require( owner == _msgSender() || isApprovedForAll(owner, _msgSender()), 'ERC1155: caller is not owner nor approved' ); _burnBatch(owner, ids, amounts); } /** * @dev allows to transfer one id to several recipient with corresponding amounts */ function safeBatchTransferIdFrom( address from, address[] memory tos, uint256 id, uint256[] memory amounts, bytes memory data ) public virtual { require(tos.length == amounts.length, 'ERC1155: length mismatch'); for (uint256 i = 0; i < tos.length; i++) { safeTransferFrom(from, tos[i], id, amounts[i], data); } } /** * Function to let Owner set configurationURI */ function setInteractiveConfURI( uint256 tokenId, address owner, string calldata interactiveConfURI ) public { require( owner == _msgSender() || isApprovedForAll(owner, _msgSender()), 'ERC1155: caller is not owner nor approved' ); _setInteractiveConfURI(tokenId, owner, interactiveConfURI); } function prepareMessage( address sender, uint256 id, uint256 supply, string memory uri_ ) public pure returns (bytes32) { return keccak256(abi.encode(sender, id, supply, uri_)); } function setBatchTokenMetadata( uint256[] memory ids, string[] memory uris, address[] memory creators ) external onlyOwner { for (uint256 i; i < ids.length; i++) { _setMetadata(ids[i], uris[i], creators[i]); } } function registerERC2981Interface() external onlyOwner { _registerInterface(0xc155531d); } function uri(uint256 id) public view virtual override returns (string memory) { // get base uri from id's Group string memory groupUri = _getIdGroupURI(id); // if set it will be something like ipfs://ipfs/IPFS_HASH/{id} return bytes(groupUri).length > 0 ? groupUri : super.uri(id); } // added to be able to batch update already created NFTs // to have them interactive on Wallet and dApps! /** * @dev Function to increment the group * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setNextGroup( string memory currentGroupNewURI, string memory nextGroupBaseURI ) external onlyOwner { _setNnextGroup(currentGroupNewURI, nextGroupBaseURI); } /** * @dev Function to change group id for specific ids * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setIdGroupIdBatch(uint256[] memory ids, uint256[] memory groupIds) external onlyOwner { _setIdGroupIdBatch(ids, groupIds); } /** * @dev Function to change groups uris * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setGroupURIBatch(uint256[] memory groupIds, string[] memory uris) external onlyOwner { _setGroupURIBatch(groupIds, uris); } } //SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * This contract allows to group tokenIds * Each group has its own baseURI * * This will allow to decentralize the tokens in batches, uploading them on IPFS or arweave * in a directory, and then set the directory uri as baseURI for this group of tokens */ contract GroupedURI { event GroupURIBatchUpdate(uint256[] groupIds); event TokenGroupBatchUpdate(uint256[] tokenIds, uint256[] groupIds); uint256 public currentGroupId; mapping(uint256 => string) public tokenGroupsURIs; mapping(uint256 => uint256) public tokenIdToGroupId; function __GroupedURI_init(string memory firstGroupURI) internal { require(bytes(firstGroupURI).length > 0, 'Invalid URI'); // init tokenGroupsURIs currentGroupId = 1; tokenGroupsURIs[1] = firstGroupURI; } /** * @dev Function to link id with currentGroupId */ function _addIdToCurrentGroup(uint256 id) internal { tokenIdToGroupId[id] = currentGroupId; } /** * @dev Function to query the baseURI for a given id */ function _getIdGroupURI(uint256 id) internal view returns (string memory) { return tokenGroupsURIs[tokenIdToGroupId[id]]; } /** * @dev Function to increment group id and set current and next base URI */ function _setNnextGroup( string memory currentGroupNewURI, string memory nextGroupBaseURI ) internal { require(bytes(nextGroupBaseURI).length > 0, 'Invalid URI'); uint256 currentGroupId_ = currentGroupId; if (bytes(currentGroupNewURI).length > 0) { tokenGroupsURIs[currentGroupId_] = currentGroupNewURI; } // initiate new group currentGroupId_++; tokenGroupsURIs[currentGroupId_] = nextGroupBaseURI; // set new group id currentGroupId = currentGroupId_; } /** * @dev Function to change multiple tokenIds tokenGroupsURIs */ function _setIdGroupIdBatch(uint256[] memory ids, uint256[] memory groupIds) internal { require(ids.length == groupIds.length, 'Length mismatch'); for (uint256 i; i < ids.length; i++) { tokenIdToGroupId[ids[i]] = groupIds[i]; } emit TokenGroupBatchUpdate(ids, groupIds); } /** * @dev Function to change multiple tokenGroupsURIs uris */ function _setGroupURIBatch(uint256[] memory groupIds, string[] memory uris) internal { require(groupIds.length == uris.length, 'Length mismatch'); for (uint256 i; i < groupIds.length; i++) { tokenGroupsURIs[groupIds[i]] = uris[i]; } emit GroupURIBatchUpdate(groupIds); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; abstract contract ERC1155Configurable { /** * @dev Emitted when `owner` sets a `configurationURI` for `tokenId` * there */ event ConfigurationURI( uint256 indexed tokenId, address indexed owner, string configurationURI ); // map of tokenId => interactiveConfURI. mapping(uint256 => mapping(address => string)) private _interactiveConfURIs; function _setInteractiveConfURI( uint256 tokenId, address owner, string calldata interactiveConfURI_ ) internal virtual { _interactiveConfURIs[tokenId][owner] = interactiveConfURI_; emit ConfigurationURI(tokenId, owner, interactiveConfURI_); } /** * Configuration uri for tokenId */ function interactiveConfURI(uint256 tokenId, address owner) public view virtual returns (string memory) { return _interactiveConfURIs[tokenId][owner]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol'; abstract contract ERC1155WithMetadata is ERC1155Upgradeable { // tokenURIs for each token mapping(uint256 => string) private _tokenURIs; mapping(uint256 => address) private _creators; function __ERC1155WithMetadata_init(string memory uri_) internal initializer { __ERC1155_init_unchained(uri_); } /** * @dev Return tokenURI for id. */ function uri(uint256 id) public view virtual override returns (string memory) { return _tokenURIs[id]; } /** * @dev Method to know if a token has already been minted or not */ function minted(uint256 id) public view returns (bool) { return _creators[id] != address(0); } /** * @dev returns `id`'s creator * throws if not minted */ function creator(uint256 id) public view returns (address creatorFromId) { address _creator = _creators[id]; require(_creator != address(0), 'ERC1155: Not Minted'); return _creator; } /** * @dev sets metadata for id */ function _setMetadata( uint256 id, string memory tokenURI, address _creator ) internal { if (bytes(tokenURI).length > 0) { _tokenURIs[id] = tokenURI; emit URI(tokenURI, id); } _creators[id] = _creator; } /** * @dev used when burning a token */ function _removeMetadata(uint256 id) internal { delete _tokenURIs[id]; delete _creators[id]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '../ERCWithRoyalties/ERCWithRoyalties.sol'; abstract contract ERC1155WithRoyalties is ERCWithRoyalties { using SafeMathUpgradeable for uint256; mapping(address => uint256) public claimableRoyalties; function __ERC1155WithRoyalties_init() internal initializer { __ERCWithRoyalties_init(); } /** * @dev returns how much royalties are required for `id` * * @return uint256 */ function getRoyalties(uint256 id) public view override returns (uint256) { return _royalties[id].value; } /** * @dev this is called by other contracts to send royalties for a given id * * @return "bytes4(keccak256('onRoyaltiesReceived(uint256)'))" */ function onRoyaltiesReceived(uint256 id) external payable override returns (bytes4) { // this means that a marketplace send royalties for id // store the value to id recipient address recipient = _royalties[id].recipient; require(recipient != address(0), 'No royalties for id'); // transfer directly to user payable(recipient).transfer(msg.value); emit RoyaltiesReceived(id, recipient, msg.value); return this.onRoyaltiesReceived.selector; } /** * @dev allow to claim royalties for `recipient` */ function claimRoyalties(address recipient) external { uint256 value = claimableRoyalties[recipient]; require(value > 0, 'Royalties: Nothing to claim'); // set 0 before calling transfer to protect against re-entrency claimableRoyalties[recipient] = 0; (bool sent, ) = payable(recipient).call{value: value}(''); require(sent, 'Failed to send Ether'); } /** * @dev ERC2981 */ function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata ) external view returns ( address receiver, uint256 royaltyAmount, bytes memory royaltyPaymentData ) { Royalty memory royalty = _royalties[tokenId]; if (royalty.recipient == address(0)) { return (address(0), 0, ''); } return (royalty.recipient, (value * royalty.value) / 10000, ''); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import '@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol'; import './IERCWithRoyalties.sol'; abstract contract ERCWithRoyalties is ERC165Upgradeable, IERCWithRoyalties { event RoyaltiesDefined( uint256 indexed id, address indexed recipient, uint256 value ); event RoyaltiesReceived( uint256 indexed id, address indexed recipient, uint256 value ); uint256 private _maxRoyalty; /* * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * bytes4(keccak256('onRoyaltiesReceived(uint256)')) == 0x058639c2 * * => 0xbb3bafd6 ^ 0x058639c2 == 0xbebd9614 */ bytes4 private constant _INTERFACE_ID_ROYALTIES = 0xbebd9614; struct Royalty { address recipient; uint256 value; } mapping(uint256 => Royalty) internal _royalties; function __ERCWithRoyalties_init() internal initializer { _registerInterface(_INTERFACE_ID_ROYALTIES); _maxRoyalty = 10000; } /** * @dev returns _maxRoyalty */ function maxRoyalty() public view returns (uint256) { return _maxRoyalty; } /** * @dev Set max allowed royalty value */ function _setMaxRoyalty(uint256 maxAllowedRoyalty) internal { require( maxAllowedRoyalty <= 10000, 'Royalties: max royalty can not be more than 100%' ); _maxRoyalty = maxAllowedRoyalty; } /** * @dev Set Royalties * * Requirements: * * - value should be lte 100% * - recipient can not be address(0) */ function _setRoyalties( uint256 id, address recipient, uint256 value ) internal { require( recipient != address(0), 'Royalties: Royalties recipient can not be null address' ); require( value <= _maxRoyalty, 'Royalties: Royalties can not be more than the defined max royalty' ); _royalties[id] = Royalty(recipient, value); emit RoyaltiesDefined(id, recipient, value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import '@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol'; /** * This works with the idea that marketplaces shouldn't be the one managing how royalties are sent to recipients * * Marketplaces should inquire if there are any royalties set for a token id * If yes, it should only send royalties to this contract (using onRoyaltiesReceived) * This contract is the one that knows how Royalties should be handled. * * Complexity of distributing royalties shouldn't be handled by the marketplace */ interface IERCWithRoyalties is IERC165Upgradeable { /** * @dev this is called by other contracts to send royalties for a given id * * @param id token id */ function getRoyalties(uint256 id) external view returns (uint256); /** * @dev this is called by other contracts to send royalties for a given id * * @param id token id * @return `bytes4(keccak256("onRoyaltiesReceived(uint256)"))` */ function onRoyaltiesReceived(uint256 id) external payable returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155MetadataURIUpgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
* @dev Function to change groups uris Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./
function setGroupURIBatch(uint256[] memory groupIds, string[] memory uris) external onlyOwner { _setGroupURIBatch(groupIds, uris); }
6,187,291
[ 1, 2083, 358, 2549, 3252, 21476, 29076, 30, 300, 326, 4894, 1297, 1240, 326, 1375, 5280, 67, 15468, 67, 16256, 8338, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 1114, 3098, 4497, 12, 11890, 5034, 8526, 3778, 1041, 2673, 16, 533, 8526, 3778, 21476, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 389, 542, 1114, 3098, 4497, 12, 1655, 2673, 16, 21476, 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 ]
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct Airline{ bytes name; bool isRegistered; bool canVote; } address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => Airline) private airlines; //Airlines are contract accounts, so we represent them as addresses. //Another approach can be to make a struct Airline. But let's keep it simple. uint256 private airlinesCount; //The number of registered airlines. mapping(address => bool) private authorizedCallers; //Used to keep track of which app contracts can access this contract uint M =2; //Voting threshold, starts when there are at least 4 registered airlines address[] private multiCallsOp = new address[](0); //List of voters on changing the operational mode /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; airlines[firstAirline].isRegistered = true; //Project Specification: First airline is registered when contract is deployed. airlines[firstAirline].canVote = false; //First airline must provide funding before it can vote for others to join airlinesCount = 1; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the calling contract to be in the "authorizedCallers" list * This is used on all functions(except those who are called by the contract owner) * to ensure that only the authorized app contracts gain access to the data on this contract */ modifier requireAuthorizedCaller() { require(authorizedCallers[msg.sender], "Caller is not authorized"); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Sets which app contracts can access this data contract * * This method is used to authorize a FlightSuretyApp contract to interact with FlightSuretyData. * You can use it to change which FlightSuretyApp is active. But it is not required */ function authorizeCaller ( address appContract ) external requireContractOwner requireIsOperational { authorizedCallers[appContract] = true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view //requireAuthorizedCaller returns(bool) { return operational; } /** * @dev Checks if an airline can vote * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function canVote ( address airline ) external view //pure requireIsOperational //requireAuthorizedCaller returns(bool) { return (airlines[airline].canVote); } /** * @dev Does the voting work for multisignature functions * Keeps track of voting responses, * and returns true if the voting threshold is rechead so the caller function can perform the task */ function vote(address voter) private returns(bool success) { require(voter == contractOwner || airlines[voter].canVote, "This address cannot vote."); success = false; bool isDuplicate = false; for(uint c = 0; c < multiCallsOp.length; c++) { if(multiCallsOp[c] == voter) { isDuplicate = true; break; } } require(!isDuplicate, "Caller already voted on changing operational mode"); multiCallsOp.push(voter); uint votes = multiCallsOp.length; if(votes >= M) //Voting threshold reached -> Change operational mode { multiCallsOp = new address[](0); //Reset list of voters success = true; } return(success); } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external //requireContractOwner { require(mode != operational, "Operational status already set to given mode"); if(airlinesCount < 4) //Voting threshold not reached yet { require(msg.sender == contractOwner, "Message sender is not allowed to change the operational mode of the contract"); operational = mode; } else if(vote(msg.sender)) operational = mode; } /** * @dev Checks if an airline is already registered * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function isRegistered ( address airline ) external view //pure requireIsOperational //requireAuthorizedCaller returns(bool) { return (airlines[airline].isRegistered); } /** * @dev Returns the number of registered airlines * */ function RegisteredAirlinesCount ( ) external view //pure //requireIsOperational //OK to reveal the count even if contract is not operational //requireAuthorizedCaller returns(uint) { return (airlinesCount); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function registerAirline ( address airline ) external //view //pure requireIsOperational //requireAuthorizedCaller { //require(airlines[airline].isRegistered == false, "This airline is already registered"); //App contract already checks it. airlines[airline].isRegistered = true; airlines[airline].canVote = false; airlinesCount++; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function enableVoting ( ) external payable//view //pure requireIsOperational //requireAuthorizedCaller { require(airlines[msg.sender].canVote == false, "This airline already can vote"); require(airlines[msg.sender].isRegistered, "This airline is not registered"); require(msg.value >= 10 ether, "Not enough funds to enable voting for this airline"); airlines[msg.sender].canVote = true; require(airlines[msg.sender].canVote, "Failed to enable voting!"); } /** * @dev Buy insurance for a flight * */ struct insuredFlights{ //bytes32[] flightNames; //a list of insured flights for each customer //uint[] amounts; // holds insurance amounts for each insured flight in wei mapping(bytes32 => uint) insuranceDetails; //stores how much did the customer insure for each flight bytes32[] insuranceKeys; //used to search the above mapping--e.g. to view all insured flights } mapping(address => insuredFlights) allInsuredFlights; mapping(address => uint) payouts; //Amounts owed to insurees but have not yet been credited to their accounts //These will be credited to the insurees when they initiate a withdrawal. //event payout(uint amount, address insuree); //This contract is not directly connected to the frontend, no need for events here. function buy ( address customer, bytes32 flight, uint amount ) external //payable //The fees are kept in the app contract requireIsOperational //requireAuthorizedCaller { // 1. Check the customer did not insure this flight previously: require(allInsuredFlights[customer].insuranceDetails[flight] == 0, 'This flight is already insured by this customer'); // 2. Accept insurance: allInsuredFlights[customer].insuranceDetails[flight] = amount; allInsuredFlights[customer].insuranceKeys.push(flight); } /** * @dev Allow a user to view the list of flights they insured * */ function viewInsuredFlights ( address customer ) external returns(bytes32[] memory) { return( allInsuredFlights[customer].insuranceKeys); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flight, address insuree ) external requireIsOperational //Apply Re-entrancy Gaurd Here(not required by project) //requireAuthorizedCaller returns(uint credit) //This is a state-changing function, so it cannot return a value //We will inform caller of the credit amount by emitting an event { //1. Checks credit = allInsuredFlights[insuree].insuranceDetails[flight]; require(credit > 0, 'You either did not insure this flight from before, or you have already claimed the credit for this flight.'); //2. Effects //2.a Update the insurance information in your mapping allInsuredFlights[insuree].insuranceDetails[flight] = 0; //2.b Calculate the amount the customer must be refunded: 1.5 time the insurance amount credit = credit.mul(3); credit = credit.div(2); require(allInsuredFlights[insuree].insuranceDetails[flight] == 0, 'Could not payout your credit'); //3. Interaction payouts[insuree] = payouts[insuree].add(credit); require(payouts[insuree] > 0, 'Unable to add your credit to the payout system'); //web3.js is not connected to this contract, you need to emit from the app contract //just return the tuples and the app contract should do the emit back to the front end //emit payout(credit, insuree); //Next: when the emitted event is caught in the frontend, allow user to withdraw amount -> withdraw button should appear } function getCredit ( address insuree ) external view returns(uint credit) { credit = payouts[insuree]; return credit; } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address insuree ) public requireIsOperational //requireAuthorizedCaller { uint credit = payouts[insuree]; //1. Checks require(credit > 0, 'User does not have credit to withraw'); //2. Effects payouts[insuree] = 0; //reset credit to prevent multiple withrawal of the same credit require(payouts[insuree] == 0, 'Could not withdraw credit'); //3. Interaction insuree.transfer(credit); //insuree.call.value(credit)(""); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address insuree, bytes32 flight ) external payable requireIsOperational //requireAuthorizedCaller { // 1. Check the customer did not insure this flight previously: require(allInsuredFlights[insuree].insuranceDetails[flight] == 0, 'This flight is already insured by this customer'); // 2. Accept insurance: allInsuredFlights[insuree].insuranceDetails[flight] = msg.value; //allInsuredFlights[insuree].insuranceKeys.push(flight); //to be able to show the customer later all the flights he insured //feature not required and needs to be fixed later. } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable requireIsOperational //requireAuthorizedCaller { //fund(); } }
Voting threshold, starts when there are at least 4 registered airlines
uint M =2;
14,078,343
[ 1, 58, 17128, 5573, 16, 2542, 1347, 1915, 854, 622, 4520, 1059, 4104, 23350, 3548, 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, 2254, 490, 273, 22, 31, 4202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xC6b159c07993c13037f52aC89344Dcb96Ae10720/sources/PriceConsumerV3.sol
Get USDC price from chain link Aggregator Get Asset Price from chain link Aggregator Convert to grams Calculate the Asset to be transferred
function toAsset(uint256 value) public view returns(uint256 asset) { uint256 USDCValue = value. mul(uint256(PriceConsumerV3.getLatestPriceUSDC())); uint256 backed = uint256( PriceConsumerV3.getLatestPriceXAU()); backed = backed.mul(2835).div(100); asset = USDCValue.div(backed).mul(10**18).div(10**6); }
8,600,070
[ 1, 967, 11836, 5528, 6205, 628, 2687, 1692, 10594, 639, 968, 10494, 20137, 628, 2687, 1692, 10594, 639, 4037, 358, 24663, 87, 9029, 326, 10494, 358, 506, 906, 4193, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 358, 6672, 12, 11890, 5034, 460, 13, 7010, 3639, 1071, 7010, 3639, 1476, 7010, 3639, 1135, 12, 11890, 5034, 3310, 13, 288, 203, 3639, 2254, 5034, 11836, 5528, 620, 273, 460, 18, 203, 5411, 14064, 12, 11890, 5034, 12, 5147, 5869, 58, 23, 18, 588, 18650, 5147, 3378, 5528, 1435, 10019, 203, 3639, 2254, 5034, 20732, 273, 2254, 5034, 12, 203, 5411, 20137, 5869, 58, 23, 18, 588, 18650, 5147, 60, 14237, 10663, 203, 3639, 20732, 273, 20732, 18, 16411, 12, 6030, 4763, 2934, 2892, 12, 6625, 1769, 1377, 203, 3639, 3310, 273, 11836, 5528, 620, 18, 2892, 12, 823, 329, 2934, 16411, 12, 2163, 636, 2643, 2934, 2892, 12, 2163, 636, 26, 1769, 203, 565, 289, 203, 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 ]
./full_match/421611/0x3dDDBC13056E3d0C0E5Fc18Ad89D2e39E6FA33ac/sources/contracts/testMerkle.sol
@notice owner withdraw the rest token only owner
function claimRestTokens(address to ) public returns (bool) { require(msg.sender == owner); require(IERC20(token).balanceOf(address(this)) >= 0); require(IERC20(token).transfer(to, IERC20(token).balanceOf(address(this)))); return true; }
13,221,497
[ 1, 8443, 598, 9446, 326, 3127, 1147, 1338, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 5188, 5157, 12, 2867, 358, 262, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 374, 1769, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 13866, 12, 869, 16, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 10019, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import { IERC20 } from "./Interfaces.sol"; 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} } 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; } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } /** * @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)); } 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 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'); } } }
* @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)); } 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 callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } }
12,648,430
[ 1, 9890, 654, 39, 3462, 225, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 5267, 364, 1758, 31, 203, 203, 225, 445, 4183, 5912, 12, 203, 565, 467, 654, 39, 3462, 1147, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 460, 203, 225, 262, 2713, 288, 203, 565, 745, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 18, 9663, 16, 358, 16, 460, 10019, 203, 225, 289, 203, 203, 225, 445, 4183, 5912, 1265, 12, 203, 565, 467, 654, 39, 3462, 1147, 16, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 460, 203, 225, 262, 2713, 288, 203, 565, 745, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 1265, 18, 9663, 16, 628, 16, 358, 16, 460, 10019, 203, 225, 289, 203, 203, 225, 445, 4183, 12053, 537, 12, 203, 565, 467, 654, 39, 3462, 1147, 16, 203, 565, 1758, 17571, 264, 16, 203, 565, 2254, 5034, 460, 203, 225, 262, 2713, 288, 203, 565, 2583, 12, 203, 1377, 261, 1132, 422, 374, 13, 747, 261, 2316, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 13, 422, 374, 3631, 203, 1377, 296, 9890, 654, 39, 3462, 30, 6617, 537, 628, 1661, 17, 7124, 358, 1661, 17, 7124, 1699, 1359, 11, 203, 565, 11272, 203, 565, 745, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 9663, 16, 17571, 264, 16, 460, 2 ]
// Permit pattern copied from BAL https://etherscan.io/address/0xba100000625a3754423978a60c9317c58a424e3d#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Permit is ERC20 { string public constant version = "1"; bytes32 public immutable DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public immutable PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public permitNonces; constructor(string memory name, string memory symbol) public ERC20(name, symbol) { uint256 chainId = getChainId(); 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 getChainId() internal pure returns (uint256) { uint256 chainID; assembly { chainID := chainid() } return chainID; } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "ERR_EXPIRED_SIG"); bytes32 digest = keccak256( abi.encodePacked( uint16(0x1901), DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, permitNonces[owner]++, deadline)) ) ); require(owner == _recover(digest, v, r, s), "ERR_INVALID_SIG"); _approve(owner, spender, value); } function _recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) private pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. 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; } } pragma solidity 0.6.12; import "./ERC20Permit.sol"; contract Idle is ERC20Permit { constructor() public ERC20Permit("Idle", "IDLE") { _mint(msg.sender, 13000000 * 10**18); // 13M } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { // 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"); bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "IDLE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "IDLE::delegateBySig: invalid nonce"); require(now <= expiry, "IDLE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * ERC20 modified transferFrom that also update the avgPrice paid for the recipient and * updates user gov idx * * @param sender : sender account * @param recipient : recipient account * @param amount : value to transfer * @return : flag whether transfer was successful or not */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, allowance(sender, msg.sender).sub(amount, "ERC20: transfer amount exceeds allowance")); _moveDelegates(_delegates[sender], _delegates[recipient], amount); return true; } /** * ERC20 modified transfer that also update the delegates * * @param recipient : recipient account * @param amount : value to transfer * @return : flag whether transfer was successful or not */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); _moveDelegates(_delegates[msg.sender], _delegates[recipient], amount); return true; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IDLE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying IDLEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "IDLE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } } pragma solidity 0.6.12; import "./VesterFactory.sol"; import "./Vester.sol"; import "./Idle.sol"; contract LockedIDLE { address public constant IDLE = address(0x875773784Af8135eA0ef43b5a374AaD105c5D39e); address public constant vestingFactory = address(0xbF875f2C6e4Cc1688dfe4ECf79583193B6089972); Idle public idle; VesterFactory public factory; constructor() public { idle = Idle(IDLE); factory = VesterFactory(vestingFactory); } function balanceOf(address _user) public view returns (uint256) { address vestingContract = factory.vestingContracts(_user); if (vestingContract == address(0)) { return 0; } if (_user == address(0x4191dbEe094bDFD087f14791E7D7084f5e92447e)) { return idle.balanceOf(0x6405127E97C3c9D0FB49a48a3332F82581a1EE03); } uint256 balance = idle.balanceOf(vestingContract); // team members have 1/10th of the voting power if (_user == address(0x3675D2A334f17bCD4689533b7Af263D48D96eC72) || _user == address(0x4F314638B730Bc46Df5e600E524267d0641C98B4) || _user == address(0xd889Acb680D5eDbFeE593d2b7355a666248bAB9b) || _user == address(0xaDa343Cb6820F4f5001749892f6CAA9920129F2A) ) { return balance / 10; } return balance; } } pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Vester { using SafeMath for uint; address public idle; address public recipient; uint public vestingAmount; uint public vestingBegin; uint public vestingCliff; uint public vestingEnd; uint public lastUpdate; constructor( address idle_, address recipient_, uint vestingAmount_, uint vestingBegin_, uint vestingCliff_, uint vestingEnd_ ) public { require(vestingBegin_ >= block.timestamp, 'TreasuryVester::constructor: vesting begin too early'); require(vestingCliff_ >= vestingBegin_, 'TreasuryVester::constructor: cliff is too early'); require(vestingEnd_ > vestingCliff_, 'TreasuryVester::constructor: end is too early'); idle = idle_; recipient = recipient_; vestingAmount = vestingAmount_; vestingBegin = vestingBegin_; vestingCliff = vestingCliff_; vestingEnd = vestingEnd_; lastUpdate = vestingBegin; } function setRecipient(address recipient_) public { require(msg.sender == recipient, 'TreasuryVester::setRecipient: unauthorized'); recipient = recipient_; } function claim() public { require(block.timestamp >= vestingCliff, 'TreasuryVester::claim: not time yet'); uint amount; if (block.timestamp >= vestingEnd) { amount = IIdle(idle).balanceOf(address(this)); } else { amount = vestingAmount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin); lastUpdate = block.timestamp; } IIdle(idle).transfer(recipient, amount); } // Add ability to delegate vote in governance function setDelegate(address delegatee) public { require(msg.sender == recipient, 'TreasuryVester::setDelegate: unauthorized'); IIdle(idle).delegate(delegatee); } } interface IIdle { function balanceOf(address account) external view returns (uint); function transfer(address dst, uint rawAmount) external returns (bool); function delegate(address delegatee) external; } pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./Vester.sol"; contract VesterFactory is Ownable { using SafeMath for uint256; address public IDLE; mapping (address => address) public vestingContracts; constructor(address idle) public { require(idle != address(0), "IS_0"); IDLE = idle; } function deployVestingContracts( uint256 vestingStart, address[] memory founders, address[] memory investors, uint256[] memory founderAmounts, uint256[] memory investorAmounts, uint256[] memory foundersVestingParams, uint256[] memory investorsVestingParams ) public onlyOwner { require(founders.length == founderAmounts.length, "FOUNDERS_LEN"); require(investors.length == investorAmounts.length, "INVESTORS_LEN"); for (uint256 i = 0; i < founders.length; i++) { _deployVesting(founders[i], founderAmounts[i], vestingStart, foundersVestingParams[0], foundersVestingParams[1]); } for (uint256 j = 0; j < investors.length; j++) { _deployVesting(investors[j], investorAmounts[j], vestingStart, investorsVestingParams[0], investorsVestingParams[1]); } } function _deployVesting( address recipient, uint256 amount, uint256 beginVesting, uint256 cliff, uint256 endVesting ) internal returns (address vester) { require(recipient != address(0), 'IS_0'); require(amount != 0, 'IS_0'); uint256 timestamp = block.timestamp; require(cliff >= timestamp, 'TIMESTAMP'); require(endVesting >= timestamp, 'TIMESTAMP'); vester = address(new Vester(IDLE, recipient, amount, beginVesting, cliff, endVesting)); vestingContracts[recipient] = vester; // Idle tokens should already be in this contract IERC20(IDLE).transfer(vester, amount); } function emergencyWithdrawal(address token, address to, uint256 amount) external onlyOwner { ERC20(token).transfer(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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); }
Idle tokens should already be in this contract
function _deployVesting( address recipient, uint256 amount, uint256 beginVesting, uint256 cliff, uint256 endVesting ) internal returns (address vester) { require(recipient != address(0), 'IS_0'); require(amount != 0, 'IS_0'); uint256 timestamp = block.timestamp; require(cliff >= timestamp, 'TIMESTAMP'); require(endVesting >= timestamp, 'TIMESTAMP'); vester = address(new Vester(IDLE, recipient, amount, beginVesting, cliff, endVesting)); vestingContracts[recipient] = vester; IERC20(IDLE).transfer(vester, amount); }
491,687
[ 1, 13834, 2430, 1410, 1818, 506, 316, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 12411, 58, 10100, 12, 203, 1377, 1758, 8027, 16, 2254, 5034, 3844, 16, 203, 1377, 2254, 5034, 2376, 58, 10100, 16, 2254, 5034, 927, 3048, 16, 2254, 5034, 679, 58, 10100, 203, 565, 262, 2713, 1135, 261, 2867, 331, 7654, 13, 225, 288, 203, 1377, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 296, 5127, 67, 20, 8284, 203, 1377, 2583, 12, 8949, 480, 374, 16, 296, 5127, 67, 20, 8284, 203, 203, 1377, 2254, 5034, 2858, 273, 1203, 18, 5508, 31, 203, 1377, 2583, 12, 830, 3048, 1545, 2858, 16, 296, 17201, 8284, 203, 1377, 2583, 12, 409, 58, 10100, 1545, 2858, 16, 296, 17201, 8284, 203, 203, 1377, 331, 7654, 273, 1758, 12, 2704, 776, 7654, 12, 734, 900, 16, 8027, 16, 3844, 16, 2376, 58, 10100, 16, 927, 3048, 16, 679, 58, 10100, 10019, 203, 1377, 331, 10100, 20723, 63, 20367, 65, 273, 331, 7654, 31, 203, 1377, 467, 654, 39, 3462, 12, 734, 900, 2934, 13866, 12, 3324, 387, 16, 3844, 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 ]
/** Copyright (c) 2018 Productivist Productivist.com / ERC20 token mechanism Version 1.0 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. based on the contracts of OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts **/ pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations (only add and sub here) with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ 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 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(); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract PRODToken is ERC20, Pausable { using SafeMath for uint256; string public name = "Productivist"; // token name string public symbol = "PROD"; // token symbol uint256 public decimals = 8; // token digit // Token distribution, must sumup to 1000 uint256 public constant SHARE_PURCHASERS = 617; uint256 public constant SHARE_FOUNDATION = 173; uint256 public constant SHARE_TEAM = 160; uint256 public constant SHARE_BOUNTY = 50; // Wallets addresses address public foundationAddress = 0x0; address public teamAddress = 0x0; address public bountyAddress = 0x0; uint256 totalSupply_ = 0; uint256 public cap = 385000000 * 10 ** decimals; // Max cap 385.000.000 token mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; bool public mintingFinished = false; event Burn(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } /** * @dev Change token name, Owner only. * @param _name The name of the token. */ function setName(string _name) onlyOwner public { name = _name; } function setWallets(address _foundation, address _team, address _bounty) public onlyOwner canMint { require(_foundation != address(0) && _team != address(0) && _bounty != address(0)); foundationAddress = _foundation; teamAddress = _team; bountyAddress = _bounty; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @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 whenNotPaused returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev 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 whenNotPaused 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 whenNotPaused returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public whenNotPaused 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 whenNotPaused 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; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); require(_to != address(0)); 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) { require(foundationAddress != address(0) && teamAddress != address(0) && bountyAddress != address(0)); require(SHARE_PURCHASERS + SHARE_FOUNDATION + SHARE_TEAM + SHARE_BOUNTY == 1000); require(totalSupply_ != 0); // before calling this method totalSupply includes only purchased tokens uint256 onePerThousand = totalSupply_ / SHARE_PURCHASERS; //ignore (totalSupply mod 617) ~= 616e-8, uint256 foundationTokens = onePerThousand * SHARE_FOUNDATION; uint256 teamTokens = onePerThousand * SHARE_TEAM; uint256 bountyTokens = onePerThousand * SHARE_BOUNTY; mint(foundationAddress, foundationTokens); mint(teamAddress, teamTokens); mint(bountyAddress, bountyTokens); mintingFinished = true; emit MintFinished(); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public whenNotPaused { require(_value <= balances[msg.sender]); // 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 address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } /** * @dev This is an especial owner-only function to make massive tokens minting. * @param _data is an array of addresses * @param _amount is an array of uint256 */ function batchMint(address[] _data,uint256[] _amount) public onlyOwner canMint { for (uint i = 0; i < _data.length; i++) { mint(_data[i],_amount[i]); } } }
* @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 whenNotPaused returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
12,072,756
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1717, 1575, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 20467, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 389, 1717, 1575, 329, 620, 13, 1071, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 565, 2254, 11144, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 15533, 203, 565, 309, 261, 67, 1717, 1575, 329, 620, 405, 11144, 13, 288, 203, 1377, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 31, 203, 1377, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 11144, 18, 1717, 24899, 1717, 1575, 329, 620, 1769, 203, 565, 289, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-06 */ // 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/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/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/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/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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/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/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: contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; 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: contracts/extensions/ERC721ABurnable.sol // Creator: Chiru Labs pragma solidity ^0.8.7; /** * @title ERC721A Burnable Token * @dev ERC721A Token that can be irreversibly burned (destroyed). */ abstract contract ERC721ABurnable is Context, ERC721A { /** * @dev Burns `tokenId`. See {ERC721A-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId); } } // File: contracts/extensions/MessageSigning.sol pragma solidity ^0.8.4; abstract contract MessageSigning { // Signer Address address internal signerAddress; constructor(address signerAddress_){ signerAddress = signerAddress_; } /************ * @dev message singing handling ************/ function isValidSignature(bytes memory message, bytes memory signature) public view returns (bool) { bytes32 _messageHash = keccak256(abi.encodePacked(message)); bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); return _recoverSigner(ethSignedMessageHash, signature) == signerAddress; } /** * @dev Set the _signerAddress just in case */ function _setSignerAddress(address newSignerAddress) internal virtual { require(newSignerAddress != signerAddress, "New Signer Address cannot be the same as current one"); signerAddress = newSignerAddress; } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) private pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _splitSignature(bytes memory sig) private pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } } // 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: @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; } } // // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @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"); } } } // // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: contracts/B.Hive721a.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.7; //t ___ ___ //o _____ /\ \ ___ /\__\ //n /::\ \ \:\ \ ___ /\ \ /:/ _/_ //y /:/\:\ \ \:\ \ /\__\ \:\ \ /:/ /\__\ //3 /:/ /::\__\ ___ /::\ \ /:/__/ \:\ \ /:/ /:/ _/_ //6 /:/_/:/\:|__| /\ /:/\:\__\ /::\ \ ___ \:\__\ /:/_/:/ /\__\ //5 \:\/:/ /:/ / \:\/:/ \/__/ \/\:\ \__ /\ \ |:| | \:\/:/ /:/ / //. \::/_/:/ / \::/__/ ~~\:\/\__\ \:\ \|:| | \::/_/:/ / //x \:\/:/ / \:\ \ \::/ / \:\__|:|__| \:\/:/ / // \::/ / \:\__\ /:/ / \::::/__/ \::/ / // \/__/ \/__/ \/__/ ~~~~ \/__/ /** * @title ERC721a Contract for B.Hive Collection */ contract TheBHive is ERC721A, Ownable, ERC721ABurnable, ReentrancyGuard, MessageSigning, PaymentSplitter { using Strings for uint256; // Provenance Hash of the Bees string public constant BEES_PROVENANCE = "AB29DAFA2947EBF9E83C4DE85019EA386636F7EBF8D37C32E93EE97F18544AF3"; // Max supply uint32 public maxSupply; // Amount of reserved token uint32 public remainingReserves; // Max amount of tokens that can be minted at the same time uint32 public immutable maxBatchSize; // Price token in ether uint256 public price; uint256 public constant startTokenId = 1; mapping(address => uint32) private _presale2MintTracking; // Max token by wallet mapping(string => uint32) private _walletsLimit; // Contract status. If paused, only reserve minting is enabled bool public paused = true; // Sale Phase. Presale if true and public sale if false bool public presale = true; bool public isPresale2 = false; //Flag locking contract from URI changes bool public isLocked = false; // flag showing if the collection is revealed or not bool public revealed = false; // holds the metadata URI string private _baseTokenURI; //payment splitter address[] private addressList = [ 0x06d7A7a8541EA1Ab7a24f179EDeBc0a1DFcAcE75, // expenses wallet 0x586F844C396AEc480AE479EE8FE6Afe103e135E4 // Community Wallet ]; uint256[] private shareList = [80, 20]; /** * @dev Initializes tbe contract with: * unrevealedURI_: the initial URI before the reveal, in a complete format eg: "ipfs://QmdsxxxxxxxxxxxxxxxxxxepJF/hidden.json" * signerAddress_: Whitelist Signer Address */ constructor ( string memory name_, string memory symbol_, address signerAddress_, uint32 maxSupply_, uint32 remainingReserves_, uint32 maxBatchSize_, uint256 price_ ) ERC721A(name_, symbol_) MessageSigning(signerAddress_) PaymentSplitter(addressList, shareList) { require(maxSupply_ >= remainingReserves_, "Maximum Supply should be greater than the reserves"); maxSupply = maxSupply_; remainingReserves = remainingReserves_; maxBatchSize = maxBatchSize_; price = price_; _walletsLimit["OG"] = 3; _walletsLimit["BL"] = 2; _walletsLimit["PS2"] = 3; _walletsLimit["Pub"] = 20; setBaseURI("ipfs://QmV2enMdpu8cR6XtN11bHJaDM7TYoXvQ1Ex44DYM2s7R3X"); // unrevealedURI_ } function _startTokenId() internal pure override returns (uint256) { return startTokenId; } /** * @dev change the signerAddress just in case */ function setSignerAddress(address newsignerAddress) external onlyOwner{ _setSignerAddress(newsignerAddress); } /** * @dev Switch the status of the contract */ function switchPauseStatus() external onlyOwner{ paused = !paused; } /** * @dev End the presale & sets the public Sales price */ function endPresale(uint256 publicSalesPrice) external onlyOwner{ require(presale, "Presale already ended"); price = publicSalesPrice; presale = false; isPresale2 = false; } /** * @dev enables presale phase 2 */ function startPresale2() external onlyOwner{ require(presale, "Presale already ended"); require(!isPresale2, "Presale phase 3 already active"); isPresale2 = true; } /** * @dev Change the `price` of the token for `newPrice` */ function setNewPrice(uint newPrice) external onlyOwner{ require(price != newPrice, "New Price should be different than current price"); price = newPrice; } /** * @dev Updating the max allowed in each phase */ function updateWalletsLimit (uint32 newWalletsLimit, string memory list) external onlyOwner{ require(_walletsLimit[list] != newWalletsLimit, "New limit per wallet cannot be equal to the current one"); _walletsLimit[list] = newWalletsLimit; } /** * @dev changes the base uri to the revealedURI and sets the revealed to true * @param revealedURI_: the final URI after reveal in a format eg: "ipfs://QmdsxxxxxxxxxxxxxxxxxxepJF/" */ function revealCollection(string memory revealedURI_) external onlyOwner { require(!revealed, "Collection already revealed"); revealed = true; setBaseURI(revealedURI_); } /** * @dev Decreases the total supply */ function decreaseSupply(uint32 newSupply, uint32 newRemainingReserves) external onlyOwner { require(newSupply < maxSupply,"Maximum supply can only be decreased"); require(newRemainingReserves <= remainingReserves, "Reseves cannot be increased"); require(newSupply >= newRemainingReserves + totalSupply(), "Maximum supply cannot be lower than the current supply + reserves"); maxSupply = newSupply; remainingReserves = newRemainingReserves; } /** * @dev ERC721 standard * @return baseURI value */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Set the base URI * * The style MUST BE as follow : "ipfs://QmdsaXXXXXXXXXXXXXXXXXXXX7epJF/" */ function setBaseURI(string memory newBaseTokenURI) public onlyOwner { require (!isLocked, "Metadata is locked!"); _baseTokenURI = newBaseTokenURI; } // minting /** * @dev Admin Mint of reserves */ function AirDrop (address to, uint32 amountToMint) external onlyOwner{ require (to != address(0), "address 0 requested"); require (amountToMint <= remainingReserves, "The requested amount is greater than the remaining reserves"); require (amountToMint > 0, "Amount should be greater than 0"); require (amountToMint <= maxBatchSize, "Quantity to mint too high"); _safeMint(to, amountToMint); remainingReserves -= amountToMint; } /** * @dev Minting for whitelisted addresses */ function whitelistMinting(uint amountToMint, bytes memory WhitelistSignature, string memory presaleList) external payable { require (presale, "Presale over!"); require (isValidSignature(abi.encodePacked(_msgSender(), presaleList), WhitelistSignature), "Wallet not whitelisted"); if(!isPresale2){ require (_getAux(msg.sender) + amountToMint <= _walletsLimit[presaleList], "max NFTs per address exceeded"); _setAux(msg.sender, uint64(_getAux(msg.sender) + amountToMint)); } else { require(_numberMinted(msg.sender) - _getAux(msg.sender) + amountToMint <= _walletsLimit[presaleList], "max NFTs per address exceeded"); _presale2MintTracking[msg.sender] += uint32(amountToMint); } _mintNFT(amountToMint); } /** * @dev Minting for the public sale */ function publicMint(uint amountToMint) external payable{ require (!presale, "Presale on"); require(_numberMinted(msg.sender) - _getAux(msg.sender) - _presale2MintTracking[msg.sender] + amountToMint <= _walletsLimit["Pub"] , "max NFTs per address exceeded"); _mintNFT(amountToMint); } /** * @dev Mint the amount of NFT requested */ function _mintNFT(uint _amountToMint) internal nonReentrant { require (!paused, "Contract paused"); require (_amountToMint > 0, "Amount should be greater than 0"); require (_amountToMint + totalSupply() <= maxSupply - remainingReserves, "Request superior max Supply"); require (msg.value == price*_amountToMint, "Incorrect Payment Amount"); require (_amountToMint <= maxBatchSize, "Quantity to mint too high"); _safeMint(msg.sender, _amountToMint); } /** * @dev Return the URI of the NFT * @notice return the hidden URI then the Revealed JSON when the Revealed param is true */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token"); if(!revealed) { return _baseURI(); } string memory URI = _baseURI(); return bytes(URI).length > 0 ? string(abi.encodePacked(URI, tokenId.toString(), ".json")) : ""; } /** * @dev Return the number of minted tokens for a wallet address * @param presalePhase 1 for presale phases 1 & 2, 3 for presale Phase 3, any other nbr for public sale */ function getNbrOfMintedToken(address wallet, uint32 presalePhase) external view returns (uint256) { if(presalePhase == 1) { return _getAux(wallet); } if(presalePhase == 3) { return _presale2MintTracking[wallet]; } return _numberMinted(wallet) - _getAux(wallet) - _presale2MintTracking[wallet]; } function getWalletsLimit(string memory list) external view returns (uint32) { return _walletsLimit[list]; } /** * @dev Return an array of token Id owned by `_owner` */ function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty arraya return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 currentTokenId = _startTokenId(); uint256 index = 0; address lastOwner; while (index < tokenCount && currentTokenId < _currentIndex) { if (!_ownerships[currentTokenId].burned && _ownerships[currentTokenId].addr != address(0)) { lastOwner = _ownerships[currentTokenId].addr; } if (lastOwner == _owner && !_ownerships[currentTokenId].burned) { result[index] = currentTokenId; unchecked { index++; } } unchecked { currentTokenId++; } } return result; } } /** * @dev and for the eternity.... **/ function lockMetadata() external onlyOwner { require(!isLocked, "Metadata Already Locked"); require(revealed, "Collection should be revealed before being locked"); isLocked = true; } }
File: contracts/extensions/ERC721ABurnable.sol Creator: Chiru Labs* @title ERC721A Burnable Token @dev ERC721A Token that can be irreversibly burned (destroyed)./
abstract contract ERC721ABurnable is Context, ERC721A { function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.7; function burn(uint256 tokenId) public virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId); } }
15,454,296
[ 1, 812, 30, 20092, 19, 9489, 19, 654, 39, 27, 5340, 2090, 321, 429, 18, 18281, 29525, 30, 1680, 481, 89, 511, 5113, 225, 4232, 39, 27, 5340, 37, 605, 321, 429, 3155, 225, 4232, 39, 27, 5340, 37, 3155, 716, 848, 506, 9482, 266, 2496, 24755, 18305, 329, 261, 11662, 329, 2934, 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, 17801, 6835, 4232, 39, 27, 5340, 2090, 321, 429, 353, 1772, 16, 4232, 39, 27, 5340, 37, 288, 203, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 27, 31, 203, 203, 203, 565, 445, 18305, 12, 11890, 5034, 1147, 548, 13, 1071, 5024, 288, 203, 3639, 3155, 5460, 12565, 3778, 2807, 5460, 12565, 273, 23178, 951, 12, 2316, 548, 1769, 203, 203, 3639, 1426, 353, 31639, 1162, 5541, 273, 261, 67, 3576, 12021, 1435, 422, 2807, 5460, 12565, 18, 4793, 747, 203, 5411, 353, 31639, 1290, 1595, 12, 10001, 5460, 12565, 18, 4793, 16, 389, 3576, 12021, 10756, 747, 203, 5411, 336, 31639, 12, 2316, 548, 13, 422, 389, 3576, 12021, 10663, 203, 203, 3639, 309, 16051, 291, 31639, 1162, 5541, 13, 15226, 12279, 11095, 1248, 5541, 50, 280, 31639, 5621, 203, 203, 3639, 389, 70, 321, 12, 2316, 548, 1769, 203, 565, 289, 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 ]
// 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // 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; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/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 /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 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))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 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))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 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))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import './libraries/PathPrice.sol'; import './interfaces/IHotPotV3Fund.sol'; import './interfaces/IHotPot.sol'; import './interfaces/IHotPotV3FundController.sol'; import './base/Multicall.sol'; contract HotPotV3FundController is IHotPotV3FundController, Multicall { using Path for bytes; address public override immutable uniV3Factory; address public override immutable uniV3Router; address public override immutable hotpot; address public override governance; address public override immutable WETH9; uint32 maxPIS = (100 << 16) + 9974;// MaxPriceImpact: 1%, MaxSwapSlippage: 0.5% = (1 - (sqrtSlippage/1e4)^2) * 100% mapping (address => bool) public override verifiedToken; mapping (address => bytes) public override harvestPath; modifier onlyManager(address fund){ require(msg.sender == IHotPotV3Fund(fund).manager(), "OMC"); _; } modifier onlyGovernance{ require(msg.sender == governance, "OGC"); _; } modifier checkDeadline(uint deadline) { require(block.timestamp <= deadline, 'CDL'); _; } constructor( address _hotpot, address _governance, address _uniV3Router, address _uniV3Factory, address _weth9 ) { hotpot = _hotpot; governance = _governance; uniV3Router = _uniV3Router; uniV3Factory = _uniV3Factory; WETH9 = _weth9; } /// @inheritdoc IControllerState function maxPriceImpact() external override view returns(uint32 priceImpact){ return maxPIS >> 16; } /// @inheritdoc IControllerState function maxSqrtSlippage() external override view returns(uint32 sqrtSlippage){ return maxPIS & 0xffff; } /// @inheritdoc IGovernanceActions function setHarvestPath(address token, bytes calldata path) external override onlyGovernance { bytes memory _path = path; while (true) { (address tokenIn, address tokenOut, uint24 fee) = _path.decodeFirstPool(); // pool is exist address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee); require(pool != address(0), "PIE"); // at least 2 observations (,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0(); require(observationCardinality >= 2, "OC"); if (_path.hasMultiplePools()) { _path = _path.skipToken(); } else { //最后一个交易对:输入WETH9, 输出hotpot require(tokenIn == WETH9 && tokenOut == hotpot, "IOT"); break; } } harvestPath[token] = path; emit SetHarvestPath(token, path); } /// @inheritdoc IGovernanceActions function setMaxPriceImpact(uint32 priceImpact) external override onlyGovernance { require(priceImpact <= 1e4 ,"SPI"); maxPIS = (priceImpact << 16) | (maxPIS & 0xffff); emit SetMaxPriceImpact(priceImpact); } /// @inheritdoc IGovernanceActions function setMaxSqrtSlippage(uint32 sqrtSlippage) external override onlyGovernance { require(sqrtSlippage <= 1e4 ,"SSS"); maxPIS = maxPIS & 0xffff0000 | sqrtSlippage; emit SetMaxSqrtSlippage(sqrtSlippage); } /// @inheritdoc IHotPotV3FundController function harvest(address token, uint amount) external override returns(uint burned) { bytes memory path = harvestPath[token]; PathPrice.verifySlippage(path, uniV3Factory, maxPIS & 0xffff); uint value = amount <= IERC20(token).balanceOf(address(this)) ? amount : IERC20(token).balanceOf(address(this)); TransferHelper.safeApprove(token, uniV3Router, value); ISwapRouter.ExactInputParams memory args = ISwapRouter.ExactInputParams({ path: path, recipient: address(this), deadline: block.timestamp, amountIn: value, amountOutMinimum: 0 }); burned = ISwapRouter(uniV3Router).exactInput(args); IHotPot(hotpot).burn(burned); emit Harvest(token, amount, burned); } /// @inheritdoc IGovernanceActions function setGovernance(address account) external override onlyGovernance { require(account != address(0)); governance = account; emit SetGovernance(account); } /// @inheritdoc IGovernanceActions function setVerifiedToken(address token, bool isVerified) external override onlyGovernance { verifiedToken[token] = isVerified; emit ChangeVerifiedToken(token, isVerified); } /// @inheritdoc IManagerActions function setDescriptor(address fund, bytes calldata _descriptor) external override onlyManager(fund) { return IHotPotV3Fund(fund).setDescriptor(_descriptor); } /// @inheritdoc IManagerActions function setDepositDeadline(address fund, uint deadline) external override onlyManager(fund) { return IHotPotV3Fund(fund).setDepositDeadline(deadline); } /// @inheritdoc IManagerActions function setPath( address fund, address distToken, bytes memory path ) external override onlyManager(fund){ require(verifiedToken[distToken]); address fundToken = IHotPotV3Fund(fund).token(); bytes memory _path = path; bytes memory _reverse; (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); _reverse = abi.encodePacked(tokenOut, fee, tokenIn); bool isBuy; // 第一个tokenIn是基金token,那么就是buy路径 if(tokenIn == fundToken){ isBuy = true; } // 如果是sellPath, 第一个需要是目标代币 else{ require(tokenIn == distToken); } while (true) { require(verifiedToken[tokenIn], "VIT"); require(verifiedToken[tokenOut], "VOT"); // pool is exist address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee); require(pool != address(0), "PIE"); // at least 2 observations (,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0(); require(observationCardinality >= 2, "OC"); if (path.hasMultiplePools()) { path = path.skipToken(); (tokenIn, tokenOut, fee) = path.decodeFirstPool(); _reverse = abi.encodePacked(tokenOut, fee, _reverse); } else { /// @dev 如果是buy, 最后一个token要是目标代币; /// @dev 如果是sell, 最后一个token要是基金token. if(isBuy) require(tokenOut == distToken, "OID"); else require(tokenOut == fundToken, "OIF"); break; } } if(!isBuy) (_path, _reverse) = (_reverse, _path); IHotPotV3Fund(fund).setPath(distToken, _path, _reverse); } /// @inheritdoc IManagerActions function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){ return IHotPotV3Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount, maxPIS); } /// @inheritdoc IManagerActions function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){ return IHotPotV3Fund(fund).add(poolIndex, positionIndex, amount, collect, maxPIS); } /// @inheritdoc IManagerActions function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint amount){ return IHotPotV3Fund(fund).sub(poolIndex, positionIndex, proportionX128, maxPIS); } /// @inheritdoc IManagerActions function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){ return IHotPotV3Fund(fund).move(poolIndex, subIndex, addIndex, proportionX128, maxPIS); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '../interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title HPT (Hotpot Funds) 代币接口定义. interface IHotPot is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(uint value) external returns (bool) ; function burnFrom(address from, uint value) external returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './IHotPotV3FundERC20.sol'; import './fund/IHotPotV3FundEvents.sol'; import './fund/IHotPotV3FundState.sol'; import './fund/IHotPotV3FundUserActions.sol'; import './fund/IHotPotV3FundManagerActions.sol'; /// @title Hotpot V3 基金接口 /// @notice 接口定义分散在多个接口文件 interface IHotPotV3Fund is IHotPotV3FundERC20, IHotPotV3FundEvents, IHotPotV3FundState, IHotPotV3FundUserActions, IHotPotV3FundManagerActions { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './controller/IManagerActions.sol'; import './controller/IGovernanceActions.sol'; import './controller/IControllerState.sol'; import './controller/IControllerEvents.sol'; /// @title Hotpot V3 控制合约接口定义. /// @notice 基金经理和治理均需通过控制合约进行操作. interface IHotPotV3FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents { /// @notice 基金分成全部用于销毁HPT /// @dev 任何人都可以调用本函数 /// @param token 用于销毁时购买HPT的代币类型 /// @param amount 代币数量 /// @return burned 销毁数量 function harvest(address token, uint amount) external returns(uint burned); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Hotpot V3 基金份额代币接口定义 interface IHotPotV3FundERC20 is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data /// @dev The `msg.value` should not be trusted for any method callable from multicall. function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title HotPotV3Controller 事件接口定义 interface IControllerEvents { /// @notice 当设置受信任token时触发 event ChangeVerifiedToken(address indexed token, bool isVerified); /// @notice 当调用Harvest时触发 event Harvest(address indexed token, uint amount, uint burned); /// @notice 当调用setHarvestPath时触发 event SetHarvestPath(address indexed token, bytes path); /// @notice 当调用setGovernance时触发 event SetGovernance(address indexed account); /// @notice 当调用setMaxSqrtSlippage时触发 event SetMaxSqrtSlippage(uint sqrtSlippage); /// @notice 当调用setMaxPriceImpact时触发 event SetMaxPriceImpact(uint priceImpact); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title HotPotV3Controller 状态变量及只读函数 interface IControllerState { /// @notice Returns the address of the Uniswap V3 router function uniV3Router() external view returns (address); /// @notice Returns the address of the Uniswap V3 facotry function uniV3Factory() external view returns (address); /// @notice 本项目治理代币HPT的地址 function hotpot() external view returns (address); /// @notice 治理账户地址 function governance() external view returns (address); /// @notice Returns the address of WETH9 function WETH9() external view returns (address); /// @notice 代币是否受信任 /// @dev The call will revert if the the token argument is address 0. /// @param token 要查询的代币地址 function verifiedToken(address token) external view returns (bool); /// @notice harvest时交易路径 /// @param token 要兑换的代币 function harvestPath(address token) external view returns (bytes memory); /// @notice 获取swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100% /// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5% function maxSqrtSlippage() external view returns (uint32); /// @notice 获取swap时最大价格影响,取值范围为 0-1e4 function maxPriceImpact() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title 治理操作接口定义 interface IGovernanceActions { /// @notice Change governance /// @dev This function can only be called by governance /// @param account 新的governance地址 function setGovernance(address account) external; /// @notice Set the token to be verified for all fund, vice versa /// @dev This function can only be called by governance /// @param token 目标代币 /// @param isVerified 是否受信任 function setVerifiedToken(address token, bool isVerified) external; /// @notice Set the swap path for harvest /// @dev This function can only be called by governance /// @param token 目标代币 /// @param path 路径 function setHarvestPath(address token, bytes calldata path) external; /// @notice 设置swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100% /// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5% /// @dev This function can only be called by governance /// @param sqrtSlippage 0-1e4 function setMaxSqrtSlippage(uint32 sqrtSlippage) external; /// @notice Set the max price impact for swap /// @dev This function can only be called by governance /// @param priceImpact 0-1e4 function setMaxPriceImpact(uint32 priceImpact) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '../fund/IHotPotV3FundManagerActions.sol'; /// @title 控制器合约基金经理操作接口定义 interface IManagerActions { /// @notice 设置基金描述信息 /// @dev This function can only be called by manager /// @param _descriptor 描述信息 function setDescriptor(address fund, bytes calldata _descriptor) external; /// @notice 设置基金存入截止时间 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param deadline 最晚存入截止时间 function setDepositDeadline(address fund, uint deadline) external; /// @notice 设置代币交易路径 /// @dev This function can only be called by manager /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param fund 基金地址 /// @param distToken 目标代币地址 /// @param path 符合uniswap v3格式的交易路径 function setPath( address fund, address distToken, bytes memory path ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 /// @param deadline 最晚交易时间 /// @return liquidity 添加的lp数量 function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint deadline ) external returns(uint128 liquidity); /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 /// @param deadline 最晚交易时间 /// @return liquidity 添加的lp数量 function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect, uint deadline ) external returns(uint128 liquidity); /// @notice 撤资指定头寸 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 /// @param deadline 最晚交易时间 /// @return amount 撤资获得的基金本币数量 function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128, uint deadline ) external returns(uint amount); /// @notice 调整头寸投资 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 /// @param deadline 最晚交易时间 /// @return liquidity 调整后添加的lp数量 function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, uint deadline ) external returns(uint128 liquidity); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 事件接口定义 interface IHotPotV3FundEvents { /// @notice 当存入基金token时,会触发该事件 event Deposit(address indexed owner, uint amount, uint share); /// @notice 当取走基金token时,会触发该事件 event Withdraw(address indexed owner, uint amount, uint share); /// @notice 当调用setDescriptor时触发 event SetDescriptor(bytes descriptor); /// @notice 当调用setDepositDeadline时触发 event SetDeadline(uint deadline); /// @notice 当调用setPath时触发 event SetPath(address distToken, bytes path); /// @notice 当调用init时,会触发该事件 event Init(uint poolIndex, uint positionIndex, uint amount); /// @notice 当调用add时,会触发该事件 event Add(uint poolIndex, uint positionIndex, uint amount, bool collect); /// @notice 当调用sub时,会触发该事件 event Sub(uint poolIndex, uint positionIndex, uint proportionX128); /// @notice 当调用move时,会触发该事件 event Move(uint poolIndex, uint subIndex, uint addIndex, uint proportionX128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @notice 基金经理操作接口定义 interface IHotPotV3FundManagerActions { /// @notice 设置基金描述信息 /// @dev This function can only be called by controller /// @param _descriptor 描述信息 function setDescriptor(bytes calldata _descriptor) external; /// @notice 设置基金存入截止时间 /// @dev This function can only be called by controller /// @param deadline 最晚存入截止时间 function setDepositDeadline(uint deadline) external; /// @notice 设置代币交易路径 /// @dev This function can only be called by controller /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param distToken 目标代币地址 /// @param buy 购买路径(本币->distToken) /// @param sell 销售路径(distToken->本币) function setPath( address distToken, bytes calldata buy, bytes calldata sell ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by controller /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 添加的lp数量 function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint32 maxPIS ) external returns(uint128 liquidity); /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 添加的lp数量 function add( uint poolIndex, uint positionIndex, uint amount, bool collect, uint32 maxPIS ) external returns(uint128 liquidity); /// @notice 撤资指定头寸 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 /// @param maxPIS 最大价格影响和价格滑点 /// @return amount 撤资获得的基金本币数量 function sub( uint poolIndex, uint positionIndex, uint proportionX128, uint32 maxPIS ) external returns(uint amount); /// @notice 调整头寸投资 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 调整后添加的lp数量 function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了 uint32 maxPIS ) external returns(uint128 liquidity); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 状态变量及只读函数 interface IHotPotV3FundState { /// @notice 控制器合约地址 function controller() external view returns (address); /// @notice 基金经理地址 function manager() external view returns (address); /// @notice 基金本币地址 function token() external view returns (address); /// @notice 32 bytes 基金经理 + 任意长度的简要描述 function descriptor() external view returns (bytes memory); /// @notice 基金锁定期 function lockPeriod() external view returns (uint); /// @notice 基金经理收费基线 function baseLine() external view returns (uint); /// @notice 基金经理收费比例 function managerFee() external view returns (uint); /// @notice 基金存入截止时间 function depositDeadline() external view returns (uint); /// @notice 获取最新存入时间 /// @param account 目标地址 /// @return 最新存入时间 function lastDepositTime(address account) external view returns (uint); /// @notice 总投入数量 function totalInvestment() external view returns (uint); /// @notice owner的投入数量 /// @param owner 用户地址 /// @return 投入本币的数量 function investmentOf(address owner) external view returns (uint); /// @notice 指定头寸的资产数量 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return 以本币计价的头寸资产数量 function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint); /// @notice 指定pool的资产数量 /// @param poolIndex 池子索引号 /// @return 以本币计价的池子资产数量 function assetsOfPool(uint poolIndex) external view returns(uint); /// @notice 总资产数量 /// @return 以本币计价的总资产数量 function totalAssets() external view returns (uint); /// @notice 基金本币->目标代币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币购买路径 function buyPath(address _token) external view returns (bytes memory); /// @notice 目标代币->基金本币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币销售路径 function sellPath(address _token) external view returns (bytes memory); /// @notice 获取池子地址 /// @param index 池子索引号 /// @return 池子地址 function pools(uint index) external view returns(address); /// @notice 头寸信息 /// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届 function positions(uint poolIndex, uint positionIndex) external view returns( bool isEmpty, int24 tickLower, int24 tickUpper ); /// @notice pool数组长度 function poolsLength() external view returns(uint); /// @notice 指定池子的头寸数组长度 /// @param poolIndex 池子索引号 /// @return 头寸数组长度 function positionsLength(uint poolIndex) external view returns(uint); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 用户操作接口定义 /// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账; interface IHotPotV3FundUserActions { /// @notice 用户存入基金本币 /// @param amount 存入数量 /// @return share 用户获得的基金份额 function deposit(uint amount) external returns(uint share); /// @notice 用户取出指定份额的本币 /// @param share 取出的基金份额数量 /// @param amountMin 最小提取值 /// @param deadline 最晚交易时间 /// @return amount 返回本币数量 function withdraw(uint share, uint amountMin, uint deadline) external returns(uint amount); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint64 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint64 { uint256 internal constant Q64 = 0x10000000000000000; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol"; import "./FixedPoint64.sol"; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol"; import "@uniswap/v3-periphery/contracts/libraries/Path.sol"; library PathPrice { using Path for bytes; /// @notice 获取目标代币当前价格的平方根 /// @param path 兑换路径 /// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96( bytes memory path, address uniV3Factory ) internal view returns (uint sqrtPriceX96){ require(path.length > 0, "IPL"); sqrtPriceX96 = FixedPoint96.Q96; uint _nextSqrtPriceX96; uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); (_nextSqrtPriceX96,,,,,,) = pool.slot0(); sqrtPriceX96 = tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _nextSqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96, _nextSqrtPriceX96, FixedPoint96.Q96); // decide whether to continue or terminate if (path.hasMultiplePools()) path = path.skipToken(); else break; } } /// @notice 获取目标代币预言机价格的平方根 /// @param path 兑换路径 /// @return sqrtPriceX96Last 预言机价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96Last( bytes memory path, address uniV3Factory ) internal view returns (uint sqrtPriceX96Last){ require(path.length > 0, "IPL"); sqrtPriceX96Last = FixedPoint96.Q96; uint _nextSqrtPriceX96; uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); // sqrtPriceX96Last (int56[] memory tickCumulatives,) = pool.observe(secondAges); _nextSqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1])); sqrtPriceX96Last = tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96Last, FixedPoint96.Q96, _nextSqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96Last, _nextSqrtPriceX96, FixedPoint96.Q96); // decide whether to continue or terminate if (path.hasMultiplePools()) path = path.skipToken(); else break; } } /// @notice 验证交易滑点是否满足条件 /// @param path 兑换路径 /// @param uniV3Factory uniswap v3 factory /// @param maxSqrtSlippage 最大滑点,最大值: 1e4 /// @return 当前价 function verifySlippage( bytes memory path, address uniV3Factory, uint32 maxSqrtSlippage ) internal view returns(uint) { uint last = getSqrtPriceX96Last(path, uniV3Factory); uint current = getSqrtPriceX96(path, uniV3Factory); if(last > current) require(current > FullMath.mulDiv(maxSqrtSlippage, last, 1e4), "VS"); return current; } }
@title Hotpot V3 控制合约接口定义. @notice 基金经理和治理均需通过控制合约进行操作.
interface IHotPotV3FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents { function harvest(address token, uint amount) external returns(uint burned); pragma solidity >=0.5.0; }
416,974
[ 1, 25270, 13130, 776, 23, 225, 167, 241, 105, 166, 235, 119, 166, 243, 235, 168, 123, 104, 167, 241, 103, 166, 242, 101, 166, 111, 253, 165, 122, 236, 18, 225, 225, 166, 258, 123, 170, 234, 244, 168, 124, 242, 168, 243, 233, 166, 245, 239, 167, 115, 124, 168, 243, 233, 166, 256, 234, 170, 255, 227, 170, 227, 253, 169, 128, 234, 167, 241, 105, 166, 235, 119, 166, 243, 235, 168, 123, 104, 169, 128, 254, 169, 99, 239, 167, 246, 240, 165, 126, 255, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 467, 25270, 18411, 58, 23, 42, 1074, 2933, 353, 467, 1318, 6100, 16, 13102, 1643, 82, 1359, 6100, 16, 467, 2933, 1119, 16, 467, 2933, 3783, 288, 203, 565, 445, 17895, 26923, 12, 2867, 1147, 16, 2254, 3844, 13, 3903, 1135, 12, 11890, 18305, 329, 1769, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Audit report available at https://www.tkd-coop.com/files/audit.pdf //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //Control who can access various functions. contract AccessControl { address payable public creatorAddress; uint16 public totalDirectors = 0; mapping(address => bool) public directors; modifier onlyCREATOR() { require( msg.sender == creatorAddress, "You are not the creator of the contract." ); _; } // Constructor constructor() { creatorAddress = payable(msg.sender); } } // Interface to TAC Contract abstract contract ITAC { function transfer(address recipient, uint256 amount) public virtual returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) public virtual returns (bool); function balanceOf(address account) public view virtual returns (uint256); } contract TACLockup is AccessControl { /////////////////////////////////////////////////DATA STRUCTURES AND GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////// // Lockup duration in seconds for each time period uint64 public lockupDuration = 604800; // Hardcoded limits that cannot be changed by admin. // Time is in seconds. uint64 public minLockupDuration = 1; uint64 public maxLockupDuration = 2592000; // 100/removalFactor = % of TAC that can be removed each time. uint64 public removalFactor = 10; // minimum amount of a removal if they have that much balance uint256 public minRemovalAmount = 5000000000000000000; uint64 public minRemovalFactor = 1; //100% removal, no limit uint64 public maxRemovalFactor = 100; //1% removal mapping(address => uint256) public lockedTACForUser; mapping(address => uint64) public lastRemovalTime; address TACContract = 0xdbCCd6D9640E3aaCcb288be5C6ee6455d940cede; //Will be changed by admin once TACContract is deployed. address TACTreasuryContract = 0xdbCCd6D9640E3aaCcb288be5C6ee6455d940cede; //Will be changed by admin once TACContract is deployed. //This function is separate from setParameters to lower the chance of accidental override. function setTACAddress(address _TACContract) public onlyCREATOR { TACContract = _TACContract; } function setTACTreasuryAddress(address _TACTreasuryContract) public onlyCREATOR { TACTreasuryContract = _TACTreasuryContract; } //Admin function to adjust the lockup duration. Adjustments must stay within pre-defined limits. function setParameters( uint64 _lockupDuration, uint64 _removalFactor, uint256 _minRemovalAmount ) public onlyCREATOR { if ( (_lockupDuration <= maxLockupDuration) && (_lockupDuration >= minLockupDuration) ) { lockupDuration = _lockupDuration; } if ( (_removalFactor <= maxRemovalFactor) && (_removalFactor >= minRemovalFactor) ) { removalFactor = _removalFactor; } minRemovalAmount = _minRemovalAmount; } //Returns current valued function getValues() public view returns (uint64 _lockupDuration, uint64 _removalFactor) { _lockupDuration = lockupDuration; _removalFactor = removalFactor; } //Function called by the TAC contract to adjust the locked up balance of a user. function adjustBalance(address user, uint256 amount) public { require( msg.sender == TACTreasuryContract, "Only the TAC Treasury Contract can call this function" ); lockedTACForUser[user] += amount; //If the user has no balance, we need to set this as the current last removal time. if (lastRemovalTime[user] == 0) { lastRemovalTime[user] = uint64(block.timestamp); } } //Function to lock your own TAC. //Users must have previously approved this contract. function lockMyTAC(uint256 amount) public { ITAC TAC = ITAC(TACContract); TAC.transferFrom(msg.sender, address(this), amount); lockedTACForUser[msg.sender] += amount; //If the user has no balance, we need to set this as the current last removal time. if (lastRemovalTime[msg.sender] == 0) { lastRemovalTime[msg.sender] = uint64(block.timestamp); } } // Returns returns the amount of TAC a user has locked as well as the last removal time. function getUserInfo(address user) public view returns (uint256 lockedAmount, uint64 time) { lockedAmount = lockedTACForUser[user]; time = lastRemovalTime[user]; } // Returns the amount of locked TAC a user has function getTACLocked(address user) public view returns (uint256 lockedAmount) { lockedAmount = lockedTACForUser[user]; } 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; } // Function any user can call to receive their TAC allocation. function claimTAC() public { require( lockedTACForUser[msg.sender] > 0, "You need to have received some TAC first" ); require( block.timestamp > lastRemovalTime[msg.sender] + lockupDuration, "You need to wait a bit longer" ); ITAC TAC = ITAC(TACContract); //Calculate amount to transfer and adjust removal time uint256 transferAmount = div( lockedTACForUser[msg.sender], removalFactor ); lastRemovalTime[msg.sender] = uint64(block.timestamp); //If they have enough balance but the transfer amount is small, transfer the min amount. if ( (transferAmount <= minRemovalAmount) && (lockedTACForUser[msg.sender] > minRemovalAmount) ) { transferAmount = minRemovalAmount; } //Transfer entire balance if min transfer amount is greater than their balance. if (minRemovalAmount > lockedTACForUser[msg.sender]) { transferAmount = lockedTACForUser[msg.sender]; } //Decrement user's balance and transfer lockedTACForUser[msg.sender] = lockedTACForUser[msg.sender] - transferAmount; TAC.transfer(msg.sender, transferAmount); } }
Control who can access various functions.
contract AccessControl { address payable public creatorAddress; uint16 public totalDirectors = 0; mapping(address => bool) public directors; pragma solidity ^0.8.0; modifier onlyCREATOR() { require( msg.sender == creatorAddress, "You are not the creator of the contract." ); _; } constructor() { creatorAddress = payable(msg.sender); } }
13,115,299
[ 1, 3367, 10354, 848, 2006, 11191, 4186, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 24349, 288, 203, 565, 1758, 8843, 429, 1071, 11784, 1887, 31, 203, 565, 2254, 2313, 1071, 2078, 5368, 1383, 273, 374, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 2657, 1383, 31, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 9606, 1338, 5458, 3575, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 11784, 1887, 16, 203, 5411, 315, 6225, 854, 486, 326, 11784, 434, 326, 6835, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 3885, 1435, 288, 203, 3639, 11784, 1887, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.7.0; // SPDX-License-Identifier: MIT import { ERC20 } from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } //---- contract UPool is ERC20 { using SafeMath for uint256; address public factory; address public router; modifier onlyRouter() { require(msg.sender == router, 'UnilendV1: UnAutorised Operaton'); _; } constructor( address _router, address _token, string memory _name, string memory _symbol ) ERC20(_name, _symbol) { factory = msg.sender; router = _router; token = _token; ltv = 70; lbv = 50; lb = 10; // liquidationBonus = 5; borrowStatus = true; lendStatus = true; collateralStatus = true; _updateInterest(200000); // 20% } address public token; uint256 public tborrowAmount; uint256 public tsupplyAmount; // uint256 public tsupplyAvailable; uint public blockinterestRate; // uint public liquidationBonus; uint public lastInterestBlock; uint public totalinterest; uint public totalPaidinterest; uint ltv; // loan to value uint lbv; // liquidity borrow value uint lb; // liquidation bonus bool borrowStatus; bool lendStatus; bool collateralStatus; // mapping(address => supplyMeta) lendingData; mapping(address => mapping(uint => borrowMeta)) borrowData; mapping(address => uint) public borrowID; struct borrowMeta { uint amount; uint paid; uint paidInterest; uint interestShare; uint interestAmount; uint currentInterest; uint block; uint collateralAmount; bool status; address collateral; } uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UnilendV1: LOCKED'); unlocked = 0; _; unlocked = 1; } function getTotalBorrowedAmount() external view returns (uint) { return tborrowAmount; } function getLTV() external view returns (uint) { return ltv; } function getLBV() external view returns (uint) { return lbv; } function getLB() external view returns (uint) { return lb; } function getBorrowStatus() external view returns (bool) { return borrowStatus; } function getLendStatus() external view returns (bool) { return lendStatus; } function getCollateralStatus() external view returns (bool) { return collateralStatus; } function setLTV(uint _value) external onlyRouter { ltv = _value; } function setLBV(uint _value) external onlyRouter { lbv = _value; } function setLB(uint _value) external onlyRouter { lb = _value; } function setBorrowStatus(bool _status) external onlyRouter { borrowStatus = _status; } function setLendStatus(bool _status) external onlyRouter { lendStatus = _status; } function setCollateralStatus(bool _status) external onlyRouter { collateralStatus = _status; } function _updateInterest(uint newInterest) internal { blockinterestRate = (newInterest*10**8).div(4*60*24*365); } function updateInterest(uint newInterest) public onlyRouter { _updateInterest(newInterest); } // ------------- function _updateTotinterest() internal { uint remainingBlocks = block.number - lastInterestBlock; // totalinterest = totalinterest.add( ( tborrowAmount.mul( remainingBlocks.mul(blockinterestRate) )).div(10**12) ); uint newAmount = ( tborrowAmount.mul( remainingBlocks.mul(blockinterestRate) )).div(10**12); tborrowAmount = tborrowAmount.add( newAmount ); tsupplyAmount = tsupplyAmount.add( newAmount ); lastInterestBlock = block.number; } function calculateShare(uint _totalShares, uint _totalAmount, uint _amount) public pure returns (uint){ if(_totalShares == 0){ return Math.sqrt(_amount.mul( _amount )).sub(1000); } else { return (_amount).mul( _totalShares ).div( _totalAmount ); } } function getShareValue(uint _totalAmount, uint _totalSupply, uint _amount) public pure returns (uint){ return ( _amount.mul(_totalAmount) ).div( _totalSupply ); } function getShareByValue(uint _totalAmount, uint _totalSupply, uint _valueAmount) public pure returns (uint){ return ( _valueAmount.mul(_totalSupply) ).div( _totalAmount ); } function lend(address _address, address _recipient, uint amount) public onlyRouter { _updateTotinterest(); uint _totalSupply = totalSupply(); // uint _totalPoolAmount = tsupplyAmount.add(totalinterest); uint ntokens = calculateShare(_totalSupply, tsupplyAmount, amount); // transfer ERC20 token for amount IERC20(token).transferFrom(_recipient, address(this), amount); // mint uTokens _mint(_address, ntokens); tsupplyAmount = tsupplyAmount.add(amount); } uint public totalBorrowShare; mapping(address => uint) public borrowShare; function borrow(address _address, address _recipient, uint amount) public onlyRouter { _updateTotinterest(); require(amount <= IERC20(token).balanceOf(address(this)), "Liquidity not available"); require(amount > 0, "Borrow Amount Should be Greater than 0"); uint nShares = calculateShare(tborrowAmount, totalBorrowShare, amount); borrowShare[_address] = borrowShare[_address].add(nShares); totalBorrowShare = totalBorrowShare.add(nShares); // transfer ERC20 token for amount IERC20(token).transfer(_recipient, amount); tborrowAmount = tborrowAmount.add(amount); // tsupplyAvailable = tsupplyAvailable.sub(amount); } function repay(address _address, address _recipient, uint amount) public onlyRouter returns(uint, bool, bool) { _updateTotinterest(); uint borrowAmount = getShareValue(tborrowAmount, totalBorrowShare, borrowShare[_address]); if(amount > borrowAmount){ amount = borrowAmount; } if(amount > 0){ uint paidShare = getShareByValue(tborrowAmount, totalBorrowShare, amount); totalBorrowShare = totalBorrowShare.sub(paidShare); borrowShare[_address] = borrowShare[_address].sub(paidShare); tborrowAmount = tborrowAmount.sub(amount); // transfer ERC20 token for amount IERC20(token).transferFrom(_recipient, address(this), amount); if(amount == borrowAmount){ // bm.status = false; // borrowID[_address] ++; borrowShare[_address] = 0; return (amount, true, true); } else { return (amount, true, false); } } else { return (0, true, false); } } function borrowBalanceOf(address _address) public view returns (uint) { // borrowMeta storage bm = borrowData[_address][borrowID[_address]]; uint _balance = borrowShare[_address]; if(_balance > 0){ uint _tsupplyAmount = tsupplyAmount; uint _tborrowAmount = tborrowAmount; if(lastInterestBlock < block.number){ uint remainingBlocks = block.number - lastInterestBlock; uint newAmount = ( tborrowAmount.mul( remainingBlocks.mul(blockinterestRate) )).div(10**12); _tborrowAmount = tborrowAmount.add( newAmount ); _tsupplyAmount = _tsupplyAmount.add( newAmount ); } uint _totalPoolAmount = _tborrowAmount; return getShareValue(_totalPoolAmount, totalBorrowShare, _balance); } else { return 0; } } function redeem(address _address, address _recipient, uint tok_amount) public onlyRouter returns(uint) { _updateTotinterest(); require(balanceOf(_address) >= tok_amount, "Balance Exeeds Requested"); uint poolAmount = getShareValue(tsupplyAmount, totalSupply(), tok_amount); require(IERC20(token).balanceOf(address(this)) >= poolAmount, "Not enough Liquidity"); // tsupplyAvailable = tsupplyAvailable.sub(poolAmount); tsupplyAmount = tsupplyAmount.sub(poolAmount); // BURN uTokens _burn(_address, tok_amount); // transfer ERC20 token for amount IERC20(token).transfer(_recipient, poolAmount); return poolAmount; } function lendingBalanceOf(address _address) public view returns (uint) { uint _balance = balanceOf(_address); if(_balance > 0){ uint _tsupplyAmount = tsupplyAmount; if(lastInterestBlock < block.number){ uint remainingBlocks = block.number - lastInterestBlock; _tsupplyAmount = _tsupplyAmount.add( ( tborrowAmount.mul( remainingBlocks.mul(blockinterestRate) )).div(10**12) ); } uint _totalPoolAmount = _tsupplyAmount; return getShareValue(_totalPoolAmount, totalSupply(), _balance); } else { return 0; } } } contract AUniLendFactory is Context { using SafeMath for uint256; uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UnilendV1: LOCKED'); unlocked = 0; _; unlocked = 1; } event PoolCreated(address indexed token, address pool, uint); address public router; address public admin; mapping(address => address) public Pools; mapping(address => address) public Assets; uint public poolLength; constructor() { admin = msg.sender; } function createPool(address _token) public returns (address) { require(Pools[_token] == address(0), 'UnilendV1: POOL ALREADY CREATED'); require(router != address(0), 'UnilendV1: ROUTER NOT CREATED YET'); ERC20 asset = ERC20(_token); string memory aTokenName = string(abi.encodePacked("UnilendV1 - ", asset.name())); string memory aTokenSymbol = string(abi.encodePacked("u", asset.symbol())); UPool _poolMeta = new UPool(router, _token, aTokenName, aTokenSymbol); address _poolAddress = address(_poolMeta); Pools[_token] = _poolAddress; Assets[_poolAddress] = _token; poolLength++; emit PoolCreated(_token, _poolAddress, poolLength); return _poolAddress; } function setAdmin(address _admin) external { require(_admin == _admin, 'UnilendV1: FORBIDDEN'); admin = _admin; } function getAdmin() external view returns (address) { return admin; } function getPoolLength() external view returns (uint) { return poolLength; } function getPool(address _token) external view returns (address) { return Pools[_token]; } function getPools(address[] memory _tokens) external view returns (address[] memory) { address[] memory _addresss = new address[](_tokens.length); for (uint i=0; i<_tokens.length; i++) { _addresss[i] = Pools[_tokens[i]]; } return _addresss; } function setRouter(address _router) external { require(router == address(0), 'UnilendV1: ROUTER ALREADY SET'); router = _router; } }
tsupplyAvailable = tsupplyAvailable.sub(poolAmount); BURN uTokens transfer ERC20 token for amount
function redeem(address _address, address _recipient, uint tok_amount) public onlyRouter returns(uint) { _updateTotinterest(); require(balanceOf(_address) >= tok_amount, "Balance Exeeds Requested"); uint poolAmount = getShareValue(tsupplyAmount, totalSupply(), tok_amount); require(IERC20(token).balanceOf(address(this)) >= poolAmount, "Not enough Liquidity"); tsupplyAmount = tsupplyAmount.sub(poolAmount); _burn(_address, tok_amount); IERC20(token).transfer(_recipient, poolAmount); return poolAmount; }
5,510,877
[ 1, 88, 2859, 1283, 5268, 273, 268, 2859, 1283, 5268, 18, 1717, 12, 6011, 6275, 1769, 605, 8521, 582, 5157, 7412, 4232, 39, 3462, 1147, 364, 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 ]
[ 1, 1, 1, 1, 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, 283, 24903, 12, 2867, 389, 2867, 16, 1758, 389, 20367, 16, 2254, 946, 67, 8949, 13, 1071, 1338, 8259, 1135, 12, 11890, 13, 288, 203, 3639, 389, 2725, 18801, 2761, 395, 5621, 203, 540, 203, 3639, 2583, 12, 12296, 951, 24899, 2867, 13, 1545, 946, 67, 8949, 16, 315, 13937, 1312, 73, 9765, 25829, 8863, 203, 540, 203, 3639, 2254, 2845, 6275, 273, 7932, 834, 620, 12, 88, 2859, 1283, 6275, 16, 2078, 3088, 1283, 9334, 946, 67, 8949, 1769, 203, 540, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 2845, 6275, 16, 315, 1248, 7304, 511, 18988, 24237, 8863, 203, 540, 203, 540, 203, 3639, 268, 2859, 1283, 6275, 273, 268, 2859, 1283, 6275, 18, 1717, 12, 6011, 6275, 1769, 203, 540, 203, 540, 203, 3639, 389, 70, 321, 24899, 2867, 16, 946, 67, 8949, 1769, 203, 540, 203, 3639, 467, 654, 39, 3462, 12, 2316, 2934, 13866, 24899, 20367, 16, 2845, 6275, 1769, 203, 540, 203, 3639, 327, 2845, 6275, 31, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xFBEBaa86E76e8cc1d4EBBFaD0892BbC9F8C16b10/sources/TokenERC20.sol
* Set allowance for other address Allows `_spender` to spend no more than `_value` tokens on your behalf @param _spender The address authorized to spend @param _value the max amount they can spend/
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
2,607,483
[ 1, 694, 1699, 1359, 364, 1308, 1758, 25619, 1375, 67, 87, 1302, 264, 68, 358, 17571, 1158, 1898, 2353, 1375, 67, 1132, 68, 2430, 603, 3433, 12433, 6186, 225, 389, 87, 1302, 264, 1021, 1758, 10799, 358, 17571, 225, 389, 1132, 326, 943, 3844, 2898, 848, 17571, 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, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 203, 565, 1135, 261, 6430, 2216, 13, 288, 203, 565, 1699, 1359, 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, -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/250/0x1CD4f1E9336555af8398A2619E7ff2712E8F4046/sources/contracts/Qissa.sol
(revenue * quota) / 10000
user.pendingRevenue = user.pendingRevenue.add(usersRevenueShare(addRevenueSlot.revenue, user.quota));
13,223,233
[ 1, 12, 266, 24612, 225, 13257, 13, 342, 12619, 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, 5411, 729, 18, 9561, 426, 24612, 273, 729, 18, 9561, 426, 24612, 18, 1289, 12, 5577, 426, 24612, 9535, 12, 1289, 426, 24612, 8764, 18, 266, 24612, 16, 729, 18, 23205, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xd2f81cd7a20d60c0d558496c7169a20968389b40 //Contract name: EtherbotsCore //Balance: 0 Ether //Verification Date: 3/4/2018 //Transacion Count: 52578 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // Pause functionality taken from OpenZeppelin. License below. /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. 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: */ /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event SetPaused(bool paused); // starts unpaused 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); _; } function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; SetPaused(paused); return true; } function unpause() public onlyOwner whenPaused returns (bool) { paused = false; SetPaused(paused); return true; } } contract EtherbotsPrivileges is Pausable { event ContractUpgrade(address newContract); } // This contract implements both the original ERC-721 standard and // the proposed 'deed' standard of 841 // I don't know which standard will eventually be adopted - support both for now /// @title Interface for contracts conforming to ERC-721: Deed Standard /// @author William Entriken (https://phor.net), et. al. /// @dev Specification at https://github.com/ethereum/eips/841 /// can read the comments there contract ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("countOfDeeds()")) ^ bytes4(keccak256("countOfDeedsByOwner(address)")) ^ bytes4(keccak256("deedOfOwnerByIndex(address,uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("takeOwnership(uint256)")); function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// function ownerOf(uint256 _deedId) public view returns (address _owner); function countOfDeeds() external view returns (uint256 _count); function countOfDeedsByOwner(address _owner) external view returns (uint256 _count); function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// event Transfer(address indexed from, address indexed to, uint256 indexed deedId); event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); function approve(address _to, uint256 _deedId) external payable; function takeOwnership(uint256 _deedId) external payable; } /// @title Metadata extension to ERC-721 interface /// @author William Entriken (https://phor.net) /// @dev Specification at https://github.com/ethereum/eips/issues/XXXX contract ERC721Metadata is ERC721 { bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("deedUri(uint256)")); function name() public pure returns (string n); function symbol() public pure returns (string s); /// @notice A distinct URI (RFC 3986) for a given token. /// @dev If: /// * The URI is a URL /// * The URL is accessible /// * The URL points to a valid JSON file format (ECMA-404 2nd ed.) /// * The JSON base element is an object /// then these names of the base element SHALL have special meaning: /// * "name": A string identifying the item to which `_deedId` grants /// ownership /// * "description": A string detailing the item to which `_deedId` grants /// ownership /// * "image": A URI pointing to a file of image/* mime type representing /// the item to which `_deedId` grants ownership /// Wallets and exchanges MAY display this to the end user. /// Consider making any images at a width between 320 and 1080 pixels and /// aspect ratio between 1.91:1 and 4:5 inclusive. function deedUri(uint256 _deedId) external view returns (string _uri); } /// @title Enumeration extension to ERC-721 interface /// @author William Entriken (https://phor.net) /// @dev Specification at https://github.com/ethereum/eips/issues/XXXX contract ERC721Enumerable is ERC721Metadata { /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Enumerable = bytes4(keccak256("deedByIndex()")) ^ bytes4(keccak256("countOfOwners()")) ^ bytes4(keccak256("ownerByIndex(uint256)")); function deedByIndex(uint256 _index) external view returns (uint256 _deedId); function countOfOwners() external view returns (uint256 _count); function ownerByIndex(uint256 _index) external view returns (address _owner); } contract ERC721Original { bytes4 constant INTERFACE_SIGNATURE_ERC721Original = bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("takeOwnership(uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")); // Core functions function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 _totalSupply); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint _tokenId) public view returns (address _owner); function approve(address _to, uint _tokenId) external payable; function transferFrom(address _from, address _to, uint _tokenId) public; function transfer(address _to, uint _tokenId) public payable; // Optional functions function name() public pure returns (string _name); function symbol() public pure returns (string _symbol); function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint _tokenId); function tokenMetadata(uint _tokenId) public view returns (string _infoUrl); // Events // event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); // event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); } contract ERC721AllImplementations is ERC721Original, ERC721Enumerable { } contract EtherbotsBase is EtherbotsPrivileges { function EtherbotsBase() public { // scrapyard = address(this); } /*** EVENTS ***/ /// Forge fires when a new part is created - 4 times when a crate is opened, /// and once when a battle takes place. Also has fires when /// parts are combined in the furnace. event Forge(address owner, uint256 partID, Part part); /// Transfer event as defined in ERC721. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// The main struct representation of a robot part. Each robot in Etherbots is represented by four copies /// of this structure, one for each of the four parts comprising it: /// 1. Right Arm (Melee), /// 2. Left Arm (Defence), /// 3. Head (Turret), /// 4. Body. // store token id on this? struct Part { uint32 tokenId; uint8 partType; uint8 partSubType; uint8 rarity; uint8 element; uint32 battlesLastDay; uint32 experience; uint32 forgeTime; uint32 battlesLastReset; } // Part type - can be shared with other part factories. uint8 constant DEFENCE = 1; uint8 constant MELEE = 2; uint8 constant BODY = 3; uint8 constant TURRET = 4; // Rarity - can be shared with other part factories. uint8 constant STANDARD = 1; uint8 constant SHADOW = 2; uint8 constant GOLD = 3; // Store a user struct // in order to keep track of experience and perk choices. // This perk tree is a binary tree, efficiently encodable as an array. // 0 reflects no perk selected. 1 is first choice. 2 is second. 3 is both. // Each choice costs experience (deducted from user struct). /*** ~~~~~ROBOT PERKS~~~~~ ***/ // PERK 1: ATTACK vs DEFENCE PERK CHOICE. // Choose // PERK TWO ATTACK/ SHOOT, or DEFEND/DODGE // PERK 2: MECH vs ELEMENTAL PERK CHOICE --- // Choose steel and electric (Mech path), or water and fire (Elemetal path) // (... will the mechs win the war for Ethertopia? or will the androids // be deluged in flood and fire? ...) // PERK 3: Commit to a specific elemental pathway: // 1. the path of steel: the iron sword; the burning frying pan! // 2. the path of electricity: the deadly taser, the fearsome forcefield // 3. the path of water: high pressure water blasters have never been so cool // 4. the path of fire!: we will hunt you down, Aang... struct User { // address userAddress; uint32 numShards; //limit shards to upper bound eg 10000 uint32 experience; uint8[32] perks; } //Maintain an array of all users. // User[] public users; // Store a map of the address to a uint representing index of User within users // we check if a user exists at multiple points, every time they acquire // via a crate or the market. Users can also manually register their address. mapping ( address => User ) public addressToUser; // Array containing the structs of all parts in existence. The ID // of each part is an index into this array. Part[] parts; // Mapping from part IDs to to owning address. Should always exist. mapping (uint256 => address) public partIndexToOwner; // A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. REMOVE? mapping (address => uint256) addressToTokensOwned; // Mapping from Part ID to an address approved to call transferFrom(). // maximum of one approved address for transfer at any time. mapping (uint256 => address) public partIndexToApproved; address auction; // address scrapyard; // Array to store approved battle contracts. // Can only ever be added to, not removed from. // Once a ruleset is published, you will ALWAYS be able to use that contract address[] approvedBattles; function getUserByAddress(address _user) public view returns (uint32, uint8[32]) { return (addressToUser[_user].experience, addressToUser[_user].perks); } // Transfer a part to an address function _transfer(address _from, address _to, uint256 _tokenId) internal { // No cap on number of parts // Very unlikely to ever be 2^256 parts owned by one account // Shouldn't waste gas checking for overflow // no point making it less than a uint --> mappings don't pack addressToTokensOwned[_to]++; // transfer ownership partIndexToOwner[_tokenId] = _to; // New parts are transferred _from 0x0, but we can't account that address. if (_from != address(0)) { addressToTokensOwned[_from]--; // clear any previously approved ownership exchange delete partIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } function getPartById(uint _id) external view returns ( uint32 tokenId, uint8 partType, uint8 partSubType, uint8 rarity, uint8 element, uint32 battlesLastDay, uint32 experience, uint32 forgeTime, uint32 battlesLastReset ) { Part memory p = parts[_id]; return (p.tokenId, p.partType, p.partSubType, p.rarity, p.element, p.battlesLastDay, p.experience, p.forgeTime, p.battlesLastReset); } function substring(string str, uint startIndex, uint endIndex) internal pure returns (string) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex-startIndex); for (uint i = startIndex; i < endIndex; i++) { result[i-startIndex] = strBytes[i]; } return string(result); } // helper functions adapted from Jossie Calderon on stackexchange function stringToUint32(string s) internal pure returns (uint32) { bytes memory b = bytes(s); uint result = 0; for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed if (b[i] >= 48 && b[i] <= 57) { result = result * 10 + (uint(b[i]) - 48); // bytes and int are not compatible with the operator -. } } return uint32(result); } function stringToUint8(string s) internal pure returns (uint8) { return uint8(stringToUint32(s)); } function uintToString(uint v) internal pure returns (string) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory s = new bytes(i); // i + 1 is inefficient for (uint j = 0; j < i; j++) { s[j] = reversed[i - j - 1]; // to avoid the off-by-one error } string memory str = string(s); return str; } } contract EtherbotsNFT is EtherbotsBase, ERC721Enumerable, ERC721Original { function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return (_interfaceID == ERC721Original.INTERFACE_SIGNATURE_ERC721Original) || (_interfaceID == ERC721.INTERFACE_SIGNATURE_ERC721) || (_interfaceID == ERC721Metadata.INTERFACE_SIGNATURE_ERC721Metadata) || (_interfaceID == ERC721Enumerable.INTERFACE_SIGNATURE_ERC721Enumerable); } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string _name) { return "Etherbots"; } function symbol() public pure returns (string _smbol) { return "ETHBOT"; } // total supply of parts --> as no parts are ever deleted, this is simply // the total supply of parts ever created function totalSupply() public view returns (uint) { return parts.length; } /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() external view returns (uint256) { return parts.length; } //--/ internal function which checks whether the token with id (_tokenId) /// is owned by the (_claimant) address function owns(address _owner, uint256 _tokenId) public view returns (bool) { return (partIndexToOwner[_tokenId] == _owner); } /// internal function which checks whether the token with id (_tokenId) /// is owned by the (_claimant) address function ownsAll(address _owner, uint256[] _tokenIds) public view returns (bool) { require(_tokenIds.length > 0); for (uint i = 0; i < _tokenIds.length; i++) { if (partIndexToOwner[_tokenIds[i]] != _owner) { return false; } } return true; } function _approve(uint256 _tokenId, address _approved) internal { partIndexToApproved[_tokenId] = _approved; } function _approvedFor(address _newOwner, uint256 _tokenId) internal view returns (bool) { return (partIndexToApproved[_tokenId] == _newOwner); } function ownerByIndex(uint256 _index) external view returns (address _owner){ return partIndexToOwner[_index]; } // returns the NUMBER of tokens owned by (_owner) function balanceOf(address _owner) public view returns (uint256 count) { return addressToTokensOwned[_owner]; } function countOfDeedsByOwner(address _owner) external view returns (uint256) { return balanceOf(_owner); } // transfers a part to another account function transfer(address _to, uint256 _tokenId) public whenNotPaused payable { // payable for ERC721 --> don't actually send eth @_@ require(msg.value == 0); // Safety checks to prevent accidental transfers to common accounts require(_to != address(0)); require(_to != address(this)); // can't transfer parts to the auction contract directly require(_to != address(auction)); // can't transfer parts to any of the battle contracts directly for (uint j = 0; j < approvedBattles.length; j++) { require(_to != approvedBattles[j]); } // Cannot send tokens you don't own require(owns(msg.sender, _tokenId)); // perform state changes necessary for transfer _transfer(msg.sender, _to, _tokenId); } // transfers a part to another account function transferAll(address _to, uint256[] _tokenIds) public whenNotPaused payable { require(msg.value == 0); // Safety checks to prevent accidental transfers to common accounts require(_to != address(0)); require(_to != address(this)); // can't transfer parts to the auction contract directly require(_to != address(auction)); // can't transfer parts to any of the battle contracts directly for (uint j = 0; j < approvedBattles.length; j++) { require(_to != approvedBattles[j]); } // Cannot send tokens you don't own require(ownsAll(msg.sender, _tokenIds)); for (uint k = 0; k < _tokenIds.length; k++) { // perform state changes necessary for transfer _transfer(msg.sender, _to, _tokenIds[k]); } } // approves the (_to) address to use the transferFrom function on the token with id (_tokenId) // if you want to clear all approvals, simply pass the zero address function approve(address _to, uint256 _deedId) external whenNotPaused payable { // payable for ERC721 --> don't actually send eth @_@ require(msg.value == 0); // use internal function? // Cannot approve the transfer of tokens you don't own require(owns(msg.sender, _deedId)); // Store the approval (can only approve one at a time) partIndexToApproved[_deedId] = _to; Approval(msg.sender, _to, _deedId); } // approves many token ids function approveMany(address _to, uint256[] _tokenIds) external whenNotPaused payable { for (uint i = 0; i < _tokenIds.length; i++) { uint _tokenId = _tokenIds[i]; // Cannot approve the transfer of tokens you don't own require(owns(msg.sender, _tokenId)); // Store the approval (can only approve one at a time) partIndexToApproved[_tokenId] = _to; //create event for each approval? _tokenId guaranteed to hold correct value? Approval(msg.sender, _to, _tokenId); } } // transfer the part with id (_tokenId) from (_from) to (_to) // (_to) must already be approved for this (_tokenId) function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused { // Safety checks to prevent accidents require(_to != address(0)); require(_to != address(this)); // sender must be approved require(partIndexToApproved[_tokenId] == msg.sender); // from must currently own the token require(owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } // returns the current owner of the token with id = _tokenId function ownerOf(uint256 _deedId) public view returns (address _owner) { _owner = partIndexToOwner[_deedId]; // must result false if index key not found require(_owner != address(0)); } // returns a dynamic array of the ids of all tokens which are owned by (_owner) // Looping through every possible part and checking it against the owner is // actually much more efficient than storing a mapping or something, because // it won't be executed as a transaction function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 totalParts = totalSupply(); return tokensOfOwnerWithinRange(_owner, 0, totalParts); } function tokensOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tmpResult = new uint256[](tokenCount); if (tokenCount == 0) { return tmpResult; } uint256 resultIndex = 0; for (uint partId = _start; partId < _start + _numToSearch; partId++) { if (partIndexToOwner[partId] == _owner) { tmpResult[resultIndex] = partId; resultIndex++; if (resultIndex == tokenCount) { //found all tokens accounted for, no need to continue break; } } } // copy number of tokens found in given range uint resultLength = resultIndex; uint256[] memory result = new uint256[](resultLength); for (uint i=0; i<resultLength; i++) { result[i] = tmpResult[i]; } return result; } //same issues as above // Returns an array of all part structs owned by the user. Free to call. function getPartsOfOwner(address _owner) external view returns(bytes24[]) { uint256 totalParts = totalSupply(); return getPartsOfOwnerWithinRange(_owner, 0, totalParts); } // This is public so it can be called by getPartsOfOwner. It should NOT be called by another contract // as it is very gas hungry. function getPartsOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(bytes24[]) { uint256 tokenCount = balanceOf(_owner); uint resultIndex = 0; bytes24[] memory result = new bytes24[](tokenCount); for (uint partId = _start; partId < _start + _numToSearch; partId++) { if (partIndexToOwner[partId] == _owner) { result[resultIndex] = _partToBytes(parts[partId]); resultIndex++; } } return result; // will have 0 elements if tokenCount == 0 } function _partToBytes(Part p) internal pure returns (bytes24 b) { b = bytes24(p.tokenId); b = b << 8; b = b | bytes24(p.partType); b = b << 8; b = b | bytes24(p.partSubType); b = b << 8; b = b | bytes24(p.rarity); b = b << 8; b = b | bytes24(p.element); b = b << 32; b = b | bytes24(p.battlesLastDay); b = b << 32; b = b | bytes24(p.experience); b = b << 32; b = b | bytes24(p.forgeTime); b = b << 32; b = b | bytes24(p.battlesLastReset); } uint32 constant FIRST_LEVEL = 1000; uint32 constant INCREMENT = 1000; // every level, you need 1000 more exp to go up a level function getLevel(uint32 _exp) public pure returns(uint32) { uint32 c = 0; for (uint32 i = FIRST_LEVEL; i <= FIRST_LEVEL + _exp; i += c * INCREMENT) { c++; } return c; } string metadataBase = "https://api.etherbots.io/api/"; function setMetadataBase(string _base) external onlyOwner { metadataBase = _base; } // part type, subtype, // have one internal function which lets us implement the divergent interfaces function _metadata(uint256 _id) internal view returns(string) { Part memory p = parts[_id]; return strConcat(strConcat( metadataBase, uintToString(uint(p.partType)), "/", uintToString(uint(p.partSubType)), "/" ), uintToString(uint(p.rarity)), "", "", ""); } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure 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); } /// @notice A distinct URI (RFC 3986) for a given token. /// @dev If: /// * The URI is a URL /// * The URL is accessible /// * The URL points to a valid JSON file format (ECMA-404 2nd ed.) /// * The JSON base element is an object /// then these names of the base element SHALL have special meaning: /// * "name": A string identifying the item to which `_deedId` grants /// ownership /// * "description": A string detailing the item to which `_deedId` grants /// ownership /// * "image": A URI pointing to a file of image/* mime type representing /// the item to which `_deedId` grants ownership /// Wallets and exchanges MAY display this to the end user. /// Consider making any images at a width between 320 and 1080 pixels and /// aspect ratio between 1.91:1 and 4:5 inclusive. function deedUri(uint256 _deedId) external view returns (string _uri){ return _metadata(_deedId); } /// returns a metadata URI function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl) { return _metadata(_tokenId); } function takeOwnership(uint256 _deedId) external payable { // payable for ERC721 --> don't actually send eth @_@ require(msg.value == 0); address _from = partIndexToOwner[_deedId]; require(_approvedFor(msg.sender, _deedId)); _transfer(_from, msg.sender, _deedId); } // parts are stored sequentially function deedByIndex(uint256 _index) external view returns (uint256 _deedId){ return _index; } function countOfOwners() external view returns (uint256 _count){ // TODO: implement this return 0; } // thirsty function function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint _tokenId){ return _tokenOfOwnerByIndex(_owner, _index); } // code duplicated function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){ // The index should be valid. require(_index < balanceOf(_owner)); // can loop through all without uint256 seen = 0; uint256 totalTokens = totalSupply(); for (uint i = 0; i < totalTokens; i++) { if (partIndexToOwner[i] == _owner) { if (seen == _index) { return i; } seen++; } } } function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId){ return _tokenOfOwnerByIndex(_owner, _index); } } // the contract which all battles must implement // allows for different types of battles to take place contract PerkTree is EtherbotsNFT { // The perktree is represented in a uint8[32] representing a binary tree // see the number of perks active // buy a new perk // 0: Prestige level -> starts at 0; // next row of tree // 1: offensive moves 2: defensive moves // next row of tree // 3: melee attack 4: turret shooting 5: defend arm 6: body dodge // next row of tree // 7: mech melee 8: android melee 9: mech turret 10: android turret // 11: mech defence 12: android defence 13: mech body 14: android body //next row of tree // 15: melee electric 16: melee steel 17: melee fire 18: melee water // 19: turret electric 20: turret steel 21: turret fire 22: turret water // 23: defend electric 24: defend steel 25: defend fire 26: defend water // 27: body electric 28: body steel 29: body fire 30: body water function _leftChild(uint8 _i) internal pure returns (uint8) { return 2*_i + 1; } function _rightChild(uint8 _i) internal pure returns (uint8) { return 2*_i + 2; } function _parent(uint8 _i) internal pure returns (uint8) { return (_i-1)/2; } uint8 constant PRESTIGE_INDEX = 0; uint8 constant PERK_COUNT = 30; event PrintPerk(string,uint8,uint8[32]); function _isValidPerkToAdd(uint8[32] _perks, uint8 _index) internal pure returns (bool) { // a previously unlocked perk is not a valid perk to add. if ((_index==PRESTIGE_INDEX) || (_perks[_index] > 0)) { return false; } // perk not valid if any ancestor not unlocked for (uint8 i = _parent(_index); i > PRESTIGE_INDEX; i = _parent(i)) { if (_perks[i] == 0) { return false; } } return true; } // sum of perks (excluding prestige) function _sumActivePerks(uint8[32] _perks) internal pure returns (uint256) { uint32 sum = 0; //sum from after prestige_index, to count+1 (for prestige index). for (uint8 i = PRESTIGE_INDEX+1; i < PERK_COUNT+1; i++) { sum += _perks[i]; } return sum; } // you can unlock a new perk every two levels (including prestige when possible) function choosePerk(uint8 _i) external { require((_i >= PRESTIGE_INDEX) && (_i < PERK_COUNT+1)); User storage currentUser = addressToUser[msg.sender]; uint256 _numActivePerks = _sumActivePerks(currentUser.perks); bool canPrestige = (_numActivePerks == PERK_COUNT); //add prestige value to sum of perks _numActivePerks += currentUser.perks[PRESTIGE_INDEX] * PERK_COUNT; require(_numActivePerks < getLevel(currentUser.experience) / 2); if (_i == PRESTIGE_INDEX) { require(canPrestige); _prestige(); } else { require(_isValidPerkToAdd(currentUser.perks, _i)); _addPerk(_i); } PerkChosen(msg.sender, _i); } function _addPerk(uint8 perk) internal { addressToUser[msg.sender].perks[perk]++; } function _prestige() internal { User storage currentUser = addressToUser[msg.sender]; for (uint8 i = 1; i < currentUser.perks.length; i++) { currentUser.perks[i] = 0; } currentUser.perks[PRESTIGE_INDEX]++; } event PerkChosen(address indexed upgradedUser, uint8 indexed perk); } // Central collection of storage on which all other contracts depend. // Contains structs for parts, users and functions which control their // transferrence. // Auction contract, facilitating statically priced sales, as well as // inflationary and deflationary pricing for items. // Relies heavily on the ERC721 interface and so most of the methods // are tightly bound to that implementation contract NFTAuctionBase is Pausable { ERC721AllImplementations public nftContract; uint256 public ownerCut; uint public minDuration; uint public maxDuration; // Represents an auction on an NFT (in this case, Robot part) struct Auction { // address of part owner address seller; // wei price of listing uint256 startPrice; // wei price of floor uint256 endPrice; // duration of sale in seconds. uint64 duration; // Time when sale started // Reset to 0 after sale concluded uint64 start; } function NFTAuctionBase() public { minDuration = 60 minutes; maxDuration = 30 days; // arbitrary } // map of all tokens and their auctions mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startPrice, uint256 endPrice, uint64 duration, uint64 start); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); // returns true if the token with id _partId is owned by the _claimant address function _owns(address _claimant, uint256 _partId) internal view returns (bool) { return nftContract.ownerOf(_partId) == _claimant; } // returns false if auction start time is 0, likely from uninitialised struct function _isActiveAuction(Auction _auction) internal pure returns (bool) { return _auction.start > 0; } // assigns ownership of the token with id = _partId to this contract // must have already been approved function _escrow(address, uint _partId) internal { // throws on transfer fail nftContract.takeOwnership(_partId); } // transfer the token with id = _partId to buying address function _transfer(address _purchasor, uint256 _partId) internal { // successful purchaseder must takeOwnership of _partId // nftContract.approve(_purchasor, _partId); // actual transfer nftContract.transfer(_purchasor, _partId); } // creates function _newAuction(uint256 _partId, Auction _auction) internal { require(_auction.duration >= minDuration); require(_auction.duration <= maxDuration); tokenIdToAuction[_partId] = _auction; AuctionCreated(uint256(_partId), uint256(_auction.startPrice), uint256(_auction.endPrice), uint64(_auction.duration), uint64(_auction.start) ); } function setMinDuration(uint _duration) external onlyOwner { minDuration = _duration; } function setMaxDuration(uint _duration) external onlyOwner { maxDuration = _duration; } /// Removes auction from public view, returns token to the seller function _cancelAuction(uint256 _partId, address _seller) internal { _removeAuction(_partId); _transfer(_seller, _partId); AuctionCancelled(_partId); } event PrintEvent(string, address, uint); // Calculates price and transfers purchase to owner. Part is NOT transferred to buyer. function _purchase(uint256 _partId, uint256 _purchaseAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_partId]; // check that this token is being auctioned require(_isActiveAuction(auction)); // enforce purchase >= the current price uint256 price = _currentPrice(auction); require(_purchaseAmount >= price); // Store seller before we delete auction. address seller = auction.seller; // Valid purchase. Remove auction to prevent reentrancy. _removeAuction(_partId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate and take fee from purchase uint256 auctioneerCut = _computeFee(price); uint256 sellerProceeds = price - auctioneerCut; PrintEvent("Seller, proceeds", seller, sellerProceeds); // Pay the seller seller.transfer(sellerProceeds); } // Calculate excess funds and return to buyer. uint256 purchaseExcess = _purchaseAmount - price; PrintEvent("Sender, excess", msg.sender, purchaseExcess); // Return any excess funds. Reentrancy again prevented by deleting auction. msg.sender.transfer(purchaseExcess); AuctionSuccessful(_partId, price, msg.sender); return price; } // returns the current price of the token being auctioned in _auction function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secsElapsed = now - _auction.start; return _computeCurrentPrice( _auction.startPrice, _auction.endPrice, _auction.duration, secsElapsed ); } // Checks if NFTPart is currently being auctioned. // function _isBeingAuctioned(Auction storage _auction) internal view returns (bool) { // return (_auction.start > 0); // } // removes the auction of the part with id _partId function _removeAuction(uint256 _partId) internal { delete tokenIdToAuction[_partId]; } // computes the current price of an deflating-price auction function _computeCurrentPrice( uint256 _startPrice, uint256 _endPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256 _price) { _price = _startPrice; if (_secondsPassed >= _duration) { // Has been up long enough to hit endPrice. // Return this price floor. _price = _endPrice; // this is a statically price sale. Just return the price. } else if (_duration > 0) { // This auction contract supports auctioning from any valid price to any other valid price. // This means the price can dynamically increase upward, or downard. int256 priceDifference = int256(_endPrice) - int256(_startPrice); int256 currentPriceDifference = priceDifference * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startPrice) + currentPriceDifference; _price = uint256(currentPrice); } return _price; } // Compute percentage fee of transaction function _computeFee (uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } } // Clock auction for NFTParts. // Only timed when pricing is dynamic (i.e. startPrice != endPrice). // Else, this becomes an infinite duration statically priced sale, // resolving when succesfully purchase for or cancelled. contract DutchAuction is NFTAuctionBase, EtherbotsPrivileges { // The ERC-165 interface signature for ERC-721. bytes4 constant InterfaceSignature_ERC721 = bytes4(0xda671b9b); function DutchAuction(address _nftAddress, uint256 _fee) public { require(_fee <= 10000); ownerCut = _fee; ERC721AllImplementations candidateContract = ERC721AllImplementations(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nftContract = candidateContract; } // Remove all ether from the contract. This will be marketplace fees. // Transfers to the NFT contract. // Can be called by owner or NFT contract. function withdrawBalance() external { address nftAddress = address(nftContract); require(msg.sender == owner || msg.sender == nftAddress); nftAddress.transfer(this.balance); } event PrintEvent(string, address, uint); // Creates an auction and lists it. function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startPrice == uint256(uint128(_startPrice))); require(_endPrice == uint256(uint128(_endPrice))); require(_duration == uint256(uint64(_duration))); require(_startPrice >= _endPrice); require(msg.sender == address(nftContract)); _escrow(_seller, _partId); Auction memory auction = Auction( _seller, uint128(_startPrice), uint128(_endPrice), uint64(_duration), uint64(now) //seconds uint ); PrintEvent("Auction Start", 0x0, auction.start); _newAuction(_partId, auction); } // SCRAPYARD PRICING LOGIC uint8 constant LAST_CONSIDERED = 5; uint8 public scrapCounter = 0; uint[5] public lastScrapPrices; // Purchases an open auction // Will transfer ownership if successful. function purchase(uint256 _partId) external payable whenNotPaused { address seller = tokenIdToAuction[_partId].seller; // _purchase will throw if the purchase or funds transfer fails uint256 price = _purchase(_partId, msg.value); _transfer(msg.sender, _partId); // If the seller is the scrapyard, track price information. if (seller == address(nftContract)) { lastScrapPrices[scrapCounter] = price; if (scrapCounter == LAST_CONSIDERED - 1) { scrapCounter = 0; } else { scrapCounter++; } } } function averageScrapPrice() public view returns (uint) { uint sum = 0; for (uint8 i = 0; i < LAST_CONSIDERED; i++) { sum += lastScrapPrices[i]; } return sum / LAST_CONSIDERED; } // Allows a user to cancel an auction before it's resolved. // Returns the part to the seller. function cancelAuction(uint256 _partId) external { Auction storage auction = tokenIdToAuction[_partId]; require(_isActiveAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_partId, seller); } // returns the current price of the auction of a token with id _partId function getCurrentPrice(uint256 _partId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_partId]; require(_isActiveAuction(auction)); return _currentPrice(auction); } // Returns the details of an auction from its _partId. function getAuction(uint256 _partId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_partId]; require(_isActiveAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.start); } // Allows owner to cancel an auction. // ONLY able to be used when contract is paused, // in the case of emergencies. // Parts returned to seller as it's equivalent to them // calling cancel. function cancelAuctionWhenPaused(uint256 _partId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_partId]; require(_isActiveAuction(auction)); _cancelAuction(_partId, auction.seller); } } contract EtherbotsAuction is PerkTree { // Sets the reference to the sale auction. function setAuctionAddress(address _address) external onlyOwner { require(_address != address(0)); DutchAuction candidateContract = DutchAuction(_address); // Set the new contract address auction = candidateContract; } // list a part for auction. function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, uint256 _duration ) external whenNotPaused { // user must have current control of the part // will lose control if they delegate to the auction // therefore no duplicate auctions! require(owns(msg.sender, _partId)); _approve(_partId, auction); // will throw if inputs are invalid // will clear transfer approval DutchAuction(auction).createAuction(_partId,_startPrice,_endPrice,_duration,msg.sender); } // transfer balance back to core contract function withdrawAuctionBalance() external onlyOwner { DutchAuction(auction).withdrawBalance(); } // SCRAP FUNCTION // This takes scrapped parts and automatically relists them on the market. // Provides a good floor for entrance into the game, while keeping supply // constant as these parts were already in circulation. // uint public constant SCRAPYARD_STARTING_PRICE = 0.1 ether; uint scrapMinStartPrice = 0.05 ether; // settable minimum starting price for sanity uint scrapMinEndPrice = 0.005 ether; // settable minimum ending price for sanity uint scrapAuctionDuration = 2 days; function setScrapMinStartPrice(uint _newMinStartPrice) external onlyOwner { scrapMinStartPrice = _newMinStartPrice; } function setScrapMinEndPrice(uint _newMinEndPrice) external onlyOwner { scrapMinEndPrice = _newMinEndPrice; } function setScrapAuctionDuration(uint _newScrapAuctionDuration) external onlyOwner { scrapAuctionDuration = _newScrapAuctionDuration; } function _createScrapPartAuction(uint _scrapPartId) internal { // if (scrapyard == address(this)) { _approve(_scrapPartId, auction); DutchAuction(auction).createAuction( _scrapPartId, _getNextAuctionPrice(), // gen next auction price scrapMinEndPrice, scrapAuctionDuration, address(this) ); // } } function _getNextAuctionPrice() internal view returns (uint) { uint avg = DutchAuction(auction).averageScrapPrice(); // add 30% to the average // prevent runaway pricing uint next = avg + ((30 * avg) / 100); if (next < scrapMinStartPrice) { next = scrapMinStartPrice; } return next; } } contract PerksRewards is EtherbotsAuction { /// An internal method that creates a new part and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Forge event /// and a Transfer event. function _createPart(uint8[4] _partArray, address _owner) internal returns (uint) { uint32 newPartId = uint32(parts.length); assert(newPartId == parts.length); Part memory _part = Part({ tokenId: newPartId, partType: _partArray[0], partSubType: _partArray[1], rarity: _partArray[2], element: _partArray[3], battlesLastDay: 0, experience: 0, forgeTime: uint32(now), battlesLastReset: uint32(now) }); assert(newPartId == parts.push(_part) - 1); // emit the FORGING!!! Forge(_owner, newPartId, _part); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPartId); return newPartId; } uint public PART_REWARD_CHANCE = 995; // Deprecated subtypes contain the subtype IDs of legacy items // which are no longer available to be redeemed in game. // i.e. subtype ID 14 represents lambo body, presale exclusive. // a value of 0 represents that subtype (id within range) // as being deprecated for that part type (body, turret, etc) uint8[] public defenceElementBySubtypeIndex; uint8[] public meleeElementBySubtypeIndex; uint8[] public bodyElementBySubtypeIndex; uint8[] public turretElementBySubtypeIndex; // uint8[] public defenceElementBySubtypeIndex = [1,2,4,3,4,1,3,3,2,1,4]; // uint8[] public meleeElementBySubtypeIndex = [3,1,3,2,3,4,2,2,1,1,1,1,4,4]; // uint8[] public bodyElementBySubtypeIndex = [2,1,2,3,4,3,1,1,4,2,3,4,1,0,1]; // no more lambos :'( // uint8[] public turretElementBySubtypeIndex = [4,3,2,1,2,1,1,3,4,3,4]; function setRewardChance(uint _newChance) external onlyOwner { require(_newChance > 980); // not too hot require(_newChance <= 1000); // not too cold PART_REWARD_CHANCE = _newChance; // just right // come at me goldilocks } // The following functions DON'T create parts, they add new parts // as possible rewards from the reward pool. function addDefenceParts(uint8[] _newElement) external onlyOwner { for (uint8 i = 0; i < _newElement.length; i++) { defenceElementBySubtypeIndex.push(_newElement[i]); } // require(defenceElementBySubtypeIndex.length < uint(uint8(-1))); } function addMeleeParts(uint8[] _newElement) external onlyOwner { for (uint8 i = 0; i < _newElement.length; i++) { meleeElementBySubtypeIndex.push(_newElement[i]); } // require(meleeElementBySubtypeIndex.length < uint(uint8(-1))); } function addBodyParts(uint8[] _newElement) external onlyOwner { for (uint8 i = 0; i < _newElement.length; i++) { bodyElementBySubtypeIndex.push(_newElement[i]); } // require(bodyElementBySubtypeIndex.length < uint(uint8(-1))); } function addTurretParts(uint8[] _newElement) external onlyOwner { for (uint8 i = 0; i < _newElement.length; i++) { turretElementBySubtypeIndex.push(_newElement[i]); } // require(turretElementBySubtypeIndex.length < uint(uint8(-1))); } // Deprecate subtypes. Once a subtype has been deprecated it can never be // undeprecated. Starting with lambo! function deprecateDefenceSubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner { defenceElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0; } function deprecateMeleeSubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner { meleeElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0; } function deprecateBodySubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner { bodyElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0; } function deprecateTurretSubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner { turretElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0; } // function _randomIndex(uint _rand, uint8 _startIx, uint8 _endIx, uint8 _modulo) internal pure returns (uint8) { // require(_startIx < _endIx); // bytes32 randBytes = bytes32(_rand); // uint result = 0; // for (uint8 i=_startIx; i<_endIx; i++) { // result = result | uint8(randBytes[i]); // result << 8; // } // uint8 resultInt = uint8(uint(result) % _modulo); // return resultInt; // } // This function takes a random uint, an owner and randomly generates a valid part. // It then transfers that part to the owner. function _generateRandomPart(uint _rand, address _owner) internal { // random uint 20 in length - MAYBE 20. // first randomly gen a part type _rand = uint(keccak256(_rand)); uint8[4] memory randomPart; randomPart[0] = uint8(_rand % 4) + 1; _rand = uint(keccak256(_rand)); // randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret if (randomPart[0] == DEFENCE) { randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex); randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == MELEE) { randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex); randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == BODY) { randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex); randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == TURRET) { randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex); randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]); } _rand = uint(keccak256(_rand)); randomPart[2] = _getRarity(_rand); // randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity _createPart(randomPart, _owner); } function _getRandomPartSubtype(uint _rand, uint8[] elementBySubtypeIndex) internal pure returns (uint8) { require(elementBySubtypeIndex.length < uint(uint8(-1))); uint8 subtypeLength = uint8(elementBySubtypeIndex.length); require(subtypeLength > 0); uint8 subtypeIndex = uint8(_rand % subtypeLength); // uint8 subtypeIndex = _randomIndex(_rand,4,8,subtypeLength); uint8 count = 0; while (elementBySubtypeIndex[subtypeIndex] == 0) { subtypeIndex++; count++; if (subtypeIndex == subtypeLength) { subtypeIndex = 0; } if (count > subtypeLength) { break; } } require(elementBySubtypeIndex[subtypeIndex] != 0); return subtypeIndex + 1; } function _getRarity(uint rand) pure internal returns (uint8) { uint16 rarity = uint16(rand % 1000); if (rarity >= 990) { // 1% chance of gold return GOLD; } else if (rarity >= 970) { // 2% chance of shadow return SHADOW; } else { return STANDARD; } } function _getElement(uint8[] elementBySubtypeIndex, uint8 subtype) internal pure returns (uint8) { uint8 subtypeIndex = subtype - 1; return elementBySubtypeIndex[subtypeIndex]; } mapping(address => uint[]) pendingPartCrates ; function getPendingPartCrateLength() external view returns (uint) { return pendingPartCrates[msg.sender].length; } /// Put shards together into a new part-crate function redeemShardsIntoPending() external { User storage user = addressToUser[msg.sender]; while (user.numShards >= SHARDS_TO_PART) { user.numShards -= SHARDS_TO_PART; pendingPartCrates[msg.sender].push(block.number); // 256 blocks to redeem } } function openPendingPartCrates() external { uint[] memory crates = pendingPartCrates[msg.sender]; for (uint i = 0; i < crates.length; i++) { uint pendingBlockNumber = crates[i]; // can't open on the same timestamp require(block.number > pendingBlockNumber); var hash = block.blockhash(pendingBlockNumber); if (uint(hash) != 0) { // different results for all different crates, even on the same block/same user // randomness is already taken care of uint rand = uint(keccak256(hash, msg.sender, i)); // % (10 ** 20); _generateRandomPart(rand, msg.sender); } else { // Do nothing, no second chances to secure integrity of randomness. } } delete pendingPartCrates[msg.sender]; } uint32 constant SHARDS_MAX = 10000; function _addShardsToUser(User storage _user, uint32 _shards) internal { uint32 updatedShards = _user.numShards + _shards; if (updatedShards > SHARDS_MAX) { updatedShards = SHARDS_MAX; } _user.numShards = updatedShards; ShardsAdded(msg.sender, _shards); } // FORGING / SCRAPPING event ShardsAdded(address caller, uint32 shards); event Scrap(address user, uint partId); uint32 constant SHARDS_TO_PART = 500; uint8 public scrapPercent = 60; uint8 public burnRate = 60; function setScrapPercent(uint8 _newPercent) external onlyOwner { require((_newPercent >= 50) && (_newPercent <= 90)); scrapPercent = _newPercent; } // function setScrapyard(address _scrapyard) external onlyOwner { // scrapyard = _scrapyard; // } function setBurnRate(uint8 _rate) external onlyOwner { burnRate = _rate; } uint public scrapCount = 0; // scraps a part for shards function scrap(uint partId) external { require(owns(msg.sender, partId)); User storage u = addressToUser[msg.sender]; _addShardsToUser(u, (SHARDS_TO_PART * scrapPercent) / 100); Scrap(msg.sender, partId); // this doesn't need to be secure // no way to manipulate it apart from guaranteeing your parts are resold // or burnt if (uint(keccak256(scrapCount)) % 100 >= burnRate) { _transfer(msg.sender, address(this), partId); _createScrapPartAuction(partId); } else { _transfer(msg.sender, address(0), partId); } scrapCount++; } } contract Mint is PerksRewards { // Owner only function to give an address new parts. // Strictly capped at 5000. // This will ONLY be used for promotional purposes (i.e. providing items for Wax/OPSkins partnership) // which we don't benefit financially from, or giving users who win the prize of designing a part // for the game, a single copy of that part. uint16 constant MINT_LIMIT = 5000; uint16 public partsMinted = 0; function mintParts(uint16 _count, address _owner) public onlyOwner { require(_count > 0 && _count <= 50); // check overflow require(partsMinted + _count > partsMinted); require(partsMinted + _count < MINT_LIMIT); addressToUser[_owner].numShards += SHARDS_TO_PART * _count; partsMinted += _count; } function mintParticularPart(uint8[4] _partArray, address _owner) public onlyOwner { require(partsMinted < MINT_LIMIT); /* cannot create deprecated parts for (uint i = 0; i < deprecated.length; i++) { if (_partArray[2] == deprecated[i]) { revert(); } } */ _createPart(_partArray, _owner); partsMinted++; } } contract NewCratePreSale { // migration functions migrate the data from the previous contract in stages // all addresses are included for transparency and easy verification // however addresses with no robots (i.e. failed transaction and never bought properly) have been commented out. // to view the full list of state assignments, go to etherscan.io/address/{address} and you can view the verified mapping (address => uint[]) public userToRobots; function _migrate(uint _index) external onlyOwner { bytes4 selector = bytes4(keccak256("setData()")); address a = migrators[_index]; require(a.delegatecall(selector)); } // source code - feel free to verify the migration address[6] migrators = [ 0x700FeBD9360ac0A0a72F371615427Bec4E4454E5, //0x97AE01893E42d6d33fd9851A28E5627222Af7BBB, 0x72Cc898de0A4EAC49c46ccb990379099461342f6, 0xc3cC48da3B8168154e0f14Bf0446C7a93613F0A7, 0x4cC96f2Ddf6844323ae0d8461d418a4D473b9AC3, 0xa52bFcb5FF599e29EE2B9130F1575BaBaa27de0A, 0xe503b42AabdA22974e2A8B75Fa87E010e1B13584 ]; function NewCratePreSale() public payable { owner = msg.sender; // one time transfer of state from the previous contract // var previous = CratePreSale(0x3c7767011C443EfeF2187cf1F2a4c02062da3998); //MAINNET // oldAppreciationRateWei = previous.appreciationRateWei(); oldAppreciationRateWei = 100000000000000; appreciationRateWei = oldAppreciationRateWei; // oldPrice = previous.currentPrice(); oldPrice = 232600000000000000; currentPrice = oldPrice; // oldCratesSold = previous.cratesSold(); oldCratesSold = 1075; cratesSold = oldCratesSold; // Migration Rationale // due to solidity issues with enumerability (contract calls cannot return dynamic arrays etc) // no need for trust -> can still use web3 to call the previous contract and check the state // will only change in the future if people send more eth // and will be obvious due to change in crate count. Any purchases on the old contract // after this contract is deployed will be fully refunded, and those robots bought will be voided. // feel free to validate any address on the old etherscan: // https://etherscan.io/address/0x3c7767011C443EfeF2187cf1F2a4c02062da3998 // can visit the exact contracts at the addresses listed above } // ------ STATE ------ uint256 constant public MAX_CRATES_TO_SELL = 3900; // Max no. of robot crates to ever be sold uint256 constant public PRESALE_END_TIMESTAMP = 1518699600; // End date for the presale - no purchases can be made after this date - Midnight 16 Feb 2018 UTC uint256 public appreciationRateWei; uint32 public cratesSold; uint256 public currentPrice; // preserve these for later verification uint32 public oldCratesSold; uint256 public oldPrice; uint256 public oldAppreciationRateWei; // mapping (address => uint32) public userCrateCount; // replaced with more efficient method // store the unopened crates of this user // actually stores the blocknumber of each crate mapping (address => uint[]) public addressToPurchasedBlocks; // store the number of expired crates for each user // i.e. crates where the user failed to open the crate within 256 blocks (~1 hour) // these crates will be able to be opened post-launch mapping (address => uint) public expiredCrates; // store the part information of purchased crates function openAll() public { uint len = addressToPurchasedBlocks[msg.sender].length; require(len > 0); uint8 count = 0; // len > i to stop predicatable wraparound for (uint i = len - 1; i >= 0 && len > i; i--) { uint crateBlock = addressToPurchasedBlocks[msg.sender][i]; require(block.number > crateBlock); // can't open on the same timestamp var hash = block.blockhash(crateBlock); if (uint(hash) != 0) { // different results for all different crates, even on the same block/same user // randomness is already taken care of uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20); userToRobots[msg.sender].push(rand); count++; } else { // all others will be expired expiredCrates[msg.sender] += (i + 1); break; } } CratesOpened(msg.sender, count); delete addressToPurchasedBlocks[msg.sender]; } // ------ EVENTS ------ event CratesPurchased(address indexed _from, uint8 _quantity); event CratesOpened(address indexed _from, uint8 _quantity); // ------ FUNCTIONS ------ function getPrice() view public returns (uint256) { return currentPrice; } function getRobotCountForUser(address _user) external view returns(uint256) { return userToRobots[_user].length; } function getRobotForUserByIndex(address _user, uint _index) external view returns(uint) { return userToRobots[_user][_index]; } function getRobotsForUser(address _user) view public returns (uint[]) { return userToRobots[_user]; } function getPendingCratesForUser(address _user) external view returns(uint[]) { return addressToPurchasedBlocks[_user]; } function getPendingCrateForUserByIndex(address _user, uint _index) external view returns(uint) { return addressToPurchasedBlocks[_user][_index]; } function getExpiredCratesForUser(address _user) external view returns(uint) { return expiredCrates[_user]; } function incrementPrice() private { // Decrease the rate of increase of the crate price // as the crates become more expensive // to avoid runaway pricing // (halving rate of increase at 0.1 ETH, 0.2 ETH, 0.3 ETH). if ( currentPrice == 100000000000000000 ) { appreciationRateWei = 200000000000000; } else if ( currentPrice == 200000000000000000) { appreciationRateWei = 100000000000000; } else if (currentPrice == 300000000000000000) { appreciationRateWei = 50000000000000; } currentPrice += appreciationRateWei; } function purchaseCrates(uint8 _cratesToBuy) public payable whenNotPaused { require(now < PRESALE_END_TIMESTAMP); // Check presale is still ongoing. require(_cratesToBuy <= 10); // Can only buy max 10 crates at a time. Don't be greedy! require(_cratesToBuy >= 1); // Sanity check. Also, you have to buy a crate. require(cratesSold + _cratesToBuy <= MAX_CRATES_TO_SELL); // Check max crates sold is less than hard limit uint256 priceToPay = _calculatePayment(_cratesToBuy); require(msg.value >= priceToPay); // Check buyer sent sufficient funds to purchase if (msg.value > priceToPay) { //overpaid, return excess msg.sender.transfer(msg.value-priceToPay); } //all good, payment received. increment number sold, price, and generate crate receipts! cratesSold += _cratesToBuy; for (uint8 i = 0; i < _cratesToBuy; i++) { incrementPrice(); addressToPurchasedBlocks[msg.sender].push(block.number); } CratesPurchased(msg.sender, _cratesToBuy); } function _calculatePayment (uint8 _cratesToBuy) private view returns (uint256) { uint256 tempPrice = currentPrice; for (uint8 i = 1; i < _cratesToBuy; i++) { tempPrice += (currentPrice + (appreciationRateWei * i)); } // for every crate over 1 bought, add current Price and a multiple of the appreciation rate // very small edge case of buying 10 when you the appreciation rate is about to halve // is compensated by the great reduction in gas by buying N at a time. return tempPrice; } //owner only withdrawal function for the presale function withdraw() onlyOwner public { owner.transfer(this.balance); } function addFunds() onlyOwner external payable { } event SetPaused(bool paused); // starts unpaused bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() external onlyOwner whenNotPaused returns (bool) { paused = true; SetPaused(paused); return true; } function unpause() external onlyOwner whenPaused returns (bool) { paused = false; SetPaused(paused); return true; } address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract EtherbotsMigrations is Mint { event CratesOpened(address indexed _from, uint8 _quantity); event OpenedOldCrates(address indexed _from); event MigratedCrates(address indexed _from, uint16 _quantity, bool isMigrationComplete); address presale = 0xc23F76aEa00B775AADC8504CcB22468F4fD2261A; mapping(address => bool) public hasMigrated; mapping(address => bool) public hasOpenedOldCrates; mapping(address => uint[]) pendingCrates; mapping(address => uint16) public cratesMigrated; // Element: copy for MIGRATIONS ONLY. string constant private DEFENCE_ELEMENT_BY_ID = "12434133214"; string constant private MELEE_ELEMENT_BY_ID = "31323422111144"; string constant private BODY_ELEMENT_BY_ID = "212343114234111"; string constant private TURRET_ELEMENT_BY_ID = "43212113434"; // Once only function. // Transfers all pending and expired crates in the old contract // into pending crates in the current one. // Users can then open them on the new contract. // Should only rarely have to be called. // event oldpending(uint old); function openOldCrates() external { require(hasOpenedOldCrates[msg.sender] == false); // uint oldPendingCrates = NewCratePreSale(presale).getPendingCrateForUserByIndex(msg.sender,0); // getting unrecognised opcode here --! // oldpending(oldPendingCrates); // require(oldPendingCrates == 0); _migrateExpiredCrates(); hasOpenedOldCrates[msg.sender] = true; OpenedOldCrates(msg.sender); } function migrate() external whenNotPaused { // Can't migrate twice . require(hasMigrated[msg.sender] == false); // require(NewCratePreSale(presale).getPendingCrateForUserByIndex(msg.sender,0) == 0); // No pending crates in the new contract allowed. Make sure you open them first. require(pendingCrates[msg.sender].length == 0); // If the user has old expired crates, don't let them migrate until they've // converted them to pending crates in the new contract. if (NewCratePreSale(presale).getExpiredCratesForUser(msg.sender) > 0) { require(hasOpenedOldCrates[msg.sender]); } // have to make a ton of calls unfortunately uint16 length = uint16(NewCratePreSale(presale).getRobotCountForUser(msg.sender)); // gas limit will be exceeded with *whale* etherbot players! // let's migrate their robots in batches of ten. // they can afford it bool isMigrationComplete = false; var max = length - cratesMigrated[msg.sender]; if (max > 9) { max = 9; } else { // final call - all robots will be migrated isMigrationComplete = true; hasMigrated[msg.sender] = true; } for (uint i = cratesMigrated[msg.sender]; i < cratesMigrated[msg.sender] + max; i++) { var robot = NewCratePreSale(presale).getRobotForUserByIndex(msg.sender, i); var robotString = uintToString(robot); // MigratedBot(robotString); _migrateRobot(robotString); } cratesMigrated[msg.sender] += max; MigratedCrates(msg.sender, cratesMigrated[msg.sender], isMigrationComplete); } function _migrateRobot(string robot) private { var (melee, defence, body, turret) = _convertBlueprint(robot); // blueprints event // blueprints(body, turret, melee, defence); _createPart(melee, msg.sender); _createPart(defence, msg.sender); _createPart(turret, msg.sender); _createPart(body, msg.sender); } function _getRarity(string original, uint8 low, uint8 high) pure private returns (uint8) { uint32 rarity = stringToUint32(substring(original,low,high)); if (rarity >= 950) { return GOLD; } else if (rarity >= 850) { return SHADOW; } else { return STANDARD; } } function _getElement(string elementString, uint partId) pure private returns(uint8) { return stringToUint8(substring(elementString, partId-1,partId)); } // Actually part type function _getPartId(string original, uint8 start, uint8 end, uint8 partCount) pure private returns(uint8) { return (stringToUint8(substring(original,start,end)) % partCount) + 1; } function userPendingCrateNumber(address _user) external view returns (uint) { return pendingCrates[_user].length; } // convert old string representation of robot into 4 new ERC721 parts function _convertBlueprint(string original) pure private returns(uint8[4] body,uint8[4] melee, uint8[4] turret, uint8[4] defence ) { /* ------ CONVERSION TIME ------ */ body[0] = BODY; body[1] = _getPartId(original, 3, 5, 15); body[2] = _getRarity(original, 0, 3); body[3] = _getElement(BODY_ELEMENT_BY_ID, body[1]); turret[0] = TURRET; turret[1] = _getPartId(original, 8, 10, 11); turret[2] = _getRarity(original, 5, 8); turret[3] = _getElement(TURRET_ELEMENT_BY_ID, turret[1]); melee[0] = MELEE; melee[1] = _getPartId(original, 13, 15, 14); melee[2] = _getRarity(original, 10, 13); melee[3] = _getElement(MELEE_ELEMENT_BY_ID, melee[1]); defence[0] = DEFENCE; var len = bytes(original).length; // string of number does not have preceding 0's if (len == 20) { defence[1] = _getPartId(original, 18, 20, 11); } else if (len == 19) { defence[1] = _getPartId(original, 18, 19, 11); } else { //unlikely to have length less than 19 defence[1] = uint8(1); } defence[2] = _getRarity(original, 15, 18); defence[3] = _getElement(DEFENCE_ELEMENT_BY_ID, defence[1]); // implicit return } // give one more chance function _migrateExpiredCrates() private { // get the number of expired crates uint expired = NewCratePreSale(presale).getExpiredCratesForUser(msg.sender); for (uint i = 0; i < expired; i++) { pendingCrates[msg.sender].push(block.number); } } // Users can open pending crates on the new contract. function openCrates() public whenNotPaused { uint[] memory pc = pendingCrates[msg.sender]; require(pc.length > 0); uint8 count = 0; for (uint i = 0; i < pc.length; i++) { uint crateBlock = pc[i]; require(block.number > crateBlock); // can't open on the same timestamp var hash = block.blockhash(crateBlock); if (uint(hash) != 0) { // different results for all different crates, even on the same block/same user // randomness is already taken care of uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20); _migrateRobot(uintToString(rand)); count++; } } CratesOpened(msg.sender, count); delete pendingCrates[msg.sender]; } } contract Battle { // This struct does not exist outside the context of a battle // the name of the battle type function name() external view returns (string); // the number of robots currently battling function playerCount() external view returns (uint count); // creates a new battle, with a submitted user string for initial input/ function createBattle(address _creator, uint[] _partIds, bytes32 _commit, uint _revealLength) external payable returns (uint); // cancels the battle at battleID function cancelBattle(uint battleID) external; function winnerOf(uint battleId, uint index) external view returns (address); function loserOf(uint battleId, uint index) external view returns (address); event BattleCreated(uint indexed battleID, address indexed starter); event BattleStage(uint indexed battleID, uint8 moveNumber, uint8[2] attackerMovesDefenderMoves, uint16[2] attackerDamageDefenderDamage); event BattleEnded(uint indexed battleID, address indexed winner); event BattleConcluded(uint indexed battleID); event BattlePropertyChanged(string name, uint previous, uint value); } contract EtherbotsBattle is EtherbotsMigrations { // can never remove any of these contracts, can only add // once we publish a contract, you'll always be able to play by that ruleset // good for two player games which are non-susceptible to collusion // people can be trusted to choose the most beneficial outcome, which in this case // is the fairest form of gameplay. // fields which are vulnerable to collusion still have to be centrally controlled :( function addApprovedBattle(Battle _battle) external onlyOwner { approvedBattles.push(_battle); } function _isApprovedBattle() internal view returns (bool) { for (uint8 i = 0; i < approvedBattles.length; i++) { if (msg.sender == address(approvedBattles[i])) { return true; } } return false; } modifier onlyApprovedBattles(){ require(_isApprovedBattle()); _; } function createBattle(uint _battleId, uint[] partIds, bytes32 commit, uint revealLength) external payable { // sanity check to make sure _battleId is a valid battle require(_battleId < approvedBattles.length); //if parts are given, make sure they are owned if (partIds.length > 0) { require(ownsAll(msg.sender, partIds)); } //battle can decide number of parts required for battle Battle battle = Battle(approvedBattles[_battleId]); // Transfer all to selected battle contract. for (uint i=0; i<partIds.length; i++) { _approve(partIds[i], address(battle)); } uint newDuelId = battle.createBattle.value(msg.value)(msg.sender, partIds, commit, revealLength); NewDuel(_battleId, newDuelId); } event NewDuel(uint battleId, uint duelId); mapping(address => Reward[]) public pendingRewards; // actually probably just want a length getter here as default public mapping getters // are pretty expensive function getPendingBattleRewardsCount(address _user) external view returns (uint) { return pendingRewards[_user].length; } struct Reward { uint blocknumber; int32 exp; } function addExperience(address _user, uint[] _partIds, int32[] _exps) external onlyApprovedBattles { address user = _user; require(_partIds.length == _exps.length); int32 sum = 0; for (uint i = 0; i < _exps.length; i++) { sum += _addPartExperience(_partIds[i], _exps[i]); } _addUserExperience(user, sum); _storeReward(user, sum); } // store sum. function _storeReward(address _user, int32 _battleExp) internal { pendingRewards[_user].push(Reward({ blocknumber: 0, exp: _battleExp })); } /* function _getExpProportion(int _exp) returns(int) { // assume max/min of 1k, -1k return 1000 + _exp + 1; // makes it between (1, 2001) } */ uint8 bestMultiple = 3; uint8 mediumMultiple = 2; uint8 worstMultiple = 1; uint8 minShards = 1; uint8 bestProbability = 97; uint8 mediumProbability = 85; function _getExpMultiple(int _exp) internal view returns (uint8, uint8) { if (_exp > 500) { return (bestMultiple,mediumMultiple); } else if (_exp > 0) { return (mediumMultiple,mediumMultiple); } else { return (worstMultiple,mediumMultiple); } } function setBest(uint8 _newBestMultiple) external onlyOwner { bestMultiple = _newBestMultiple; } function setMedium(uint8 _newMediumMultiple) external onlyOwner { mediumMultiple = _newMediumMultiple; } function setWorst(uint8 _newWorstMultiple) external onlyOwner { worstMultiple = _newWorstMultiple; } function setMinShards(uint8 _newMin) external onlyOwner { minShards = _newMin; } function setBestProbability(uint8 _newBestProb) external onlyOwner { bestProbability = _newBestProb; } function setMediumProbability(uint8 _newMinProb) external onlyOwner { mediumProbability = _newMinProb; } function _calculateShards(int _exp, uint rand) internal view returns (uint16) { var (a, b) = _getExpMultiple(_exp); uint16 shards; uint randPercent = rand % 100; if (randPercent > bestProbability) { shards = uint16(a * ((rand % 20) + 12) / b); } else if (randPercent > mediumProbability) { shards = uint16(a * ((rand % 10) + 6) / b); } else { shards = uint16((a * (rand % 5)) / b); } if (shards < minShards) { shards = minShards; } return shards; } // convert wins into pending battle crates // Not to pending old crates (migration), nor pending part crates (redeemShards) function convertReward() external { Reward[] storage rewards = pendingRewards[msg.sender]; for (uint i = 0; i < rewards.length; i++) { if (rewards[i].blocknumber == 0) { rewards[i].blocknumber = block.number; } } } // in PerksRewards function redeemBattleCrates() external { uint8 count = 0; uint len = pendingRewards[msg.sender].length; require(len > 0); for (uint i = 0; i < len; i++) { Reward memory rewardStruct = pendingRewards[msg.sender][i]; // can't open on the same timestamp require(block.number > rewardStruct.blocknumber); // ensure user has converted all pendingRewards require(rewardStruct.blocknumber != 0); var hash = block.blockhash(rewardStruct.blocknumber); if (uint(hash) != 0) { // different results for all different crates, even on the same block/same user // randomness is already taken care of uint rand = uint(keccak256(hash, msg.sender, i)); _generateBattleReward(rand,rewardStruct.exp); count++; } else { // Do nothing, no second chances to secure integrity of randomness. } } CratesOpened(msg.sender, count); delete pendingRewards[msg.sender]; } function _generateBattleReward(uint rand, int32 exp) internal { if (((rand % 1000) > PART_REWARD_CHANCE) && (exp > 0)) { _generateRandomPart(rand, msg.sender); } else { _addShardsToUser(addressToUser[msg.sender], _calculateShards(exp, rand)); } } // don't need to do any scaling // should already have been done by previous stages function _addUserExperience(address user, int32 exp) internal { // never allow exp to drop below 0 User memory u = addressToUser[user]; if (exp < 0 && uint32(int32(u.experience) + exp) > u.experience) { u.experience = 0; return; } else if (exp > 0) { // check for overflow require(uint32(int32(u.experience) + exp) > u.experience); } addressToUser[user].experience = uint32(int32(u.experience) + exp); //_addUserReward(user, exp); } function setMinScaled(int8 _min) external onlyOwner { minScaled = _min; } int8 minScaled = 25; function _scaleExp(uint32 _battleCount, int32 _exp) internal view returns (int32) { if (_battleCount <= 10) { return _exp; // no drop off } int32 exp = (_exp * 10)/int32(_battleCount); if (exp < minScaled) { return minScaled; } return exp; } function _addPartExperience(uint _id, int32 _baseExp) internal returns (int32) { // never allow exp to drop below 0 Part storage p = parts[_id]; if (now - p.battlesLastReset > 24 hours) { p.battlesLastReset = uint32(now); p.battlesLastDay = 0; } p.battlesLastDay++; int32 exp = _baseExp; if (exp > 0) { exp = _scaleExp(p.battlesLastDay, _baseExp); } if (exp < 0 && uint32(int32(p.experience) + exp) > p.experience) { // check for wrap-around p.experience = 0; return; } else if (exp > 0) { // check for overflow require(uint32(int32(p.experience) + exp) > p.experience); } parts[_id].experience = uint32(int32(parts[_id].experience) + exp); return exp; } function totalLevel(uint[] partIds) public view returns (uint32) { uint32 total = 0; for (uint i = 0; i < partIds.length; i++) { total += getLevel(parts[partIds[i]].experience); } return total; } //requires parts in order function hasOrderedRobotParts(uint[] partIds) external view returns(bool) { uint len = partIds.length; if (len != 4) { return false; } for (uint i = 0; i < len; i++) { if (parts[partIds[i]].partType != i+1) { return false; } } return true; } } contract EtherbotsCore is EtherbotsBattle { // The structure of Etherbots is modelled on CryptoKitties for obvious reasons: // ease of implementation, tried + tested etc. // it elides some features and includes some others. // The full system is implemented in the following manner: // // EtherbotsBase | Storage and base types // EtherbotsAccess | Access Control - who can change which state vars etc. // EtherbotsNFT | ERC721 Implementation // EtherbotsBattle | Battle interface contract: only one implementation currently, but could add more later. // EtherbotsAuction | Auction interface contract function EtherbotsCore() public { // Starts paused. paused = true; owner = msg.sender; } function() external payable { } function withdrawBalance() external onlyOwner { owner.transfer(this.balance); } }
The structure of Etherbots is modelled on CryptoKitties for obvious reasons: ease of implementation, tried + tested etc. it elides some features and includes some others. The full system is implemented in the following manner: EtherbotsBase | Storage and base types EtherbotsAccess | Access Control - who can change which state vars etc. EtherbotsNFT | ERC721 Implementation EtherbotsBattle | Battle interface contract: only one implementation currently, but could add more later. EtherbotsAuction | Auction interface contract
contract EtherbotsCore is EtherbotsBattle { function EtherbotsCore() public { paused = true; owner = msg.sender; } function() external payable { } function withdrawBalance() external onlyOwner { owner.transfer(this.balance); } }
14,085,045
[ 1, 1986, 3695, 434, 512, 1136, 4819, 87, 353, 938, 1259, 603, 15629, 14102, 88, 606, 364, 28067, 14000, 30, 28769, 434, 4471, 16, 12928, 397, 18432, 5527, 18, 518, 415, 4369, 2690, 4467, 471, 6104, 2690, 10654, 18, 1021, 1983, 2619, 353, 8249, 316, 326, 3751, 21296, 30, 512, 1136, 4819, 87, 2171, 565, 571, 5235, 471, 1026, 1953, 512, 1136, 4819, 87, 1862, 225, 571, 5016, 8888, 300, 10354, 848, 2549, 1492, 919, 4153, 5527, 18, 512, 1136, 4819, 87, 50, 4464, 377, 571, 4232, 39, 27, 5340, 25379, 512, 1136, 4819, 87, 38, 4558, 298, 225, 571, 605, 4558, 298, 1560, 6835, 30, 1338, 1245, 4471, 4551, 16, 1496, 3377, 527, 1898, 5137, 18, 512, 1136, 4819, 87, 37, 4062, 571, 432, 4062, 1560, 6835, 2, 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, 1, 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, 4819, 87, 4670, 353, 512, 1136, 4819, 87, 38, 4558, 298, 288, 203, 203, 203, 203, 203, 565, 445, 512, 1136, 4819, 87, 4670, 1435, 1071, 288, 203, 3639, 17781, 273, 638, 31, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 1435, 3903, 8843, 429, 288, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 13937, 1435, 3903, 1338, 5541, 288, 203, 3639, 3410, 18, 13866, 12, 2211, 18, 12296, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x20b504802dbce474b4dc59c9474f9270c85b94d8 //Contract name: DaRiCpAy //Balance: 0 Ether //Verification Date: 1/8/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title 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 */ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * 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 */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } //The Persian Daric was a gold coin which, along //with a similar silver coin, the siglos, represented //the bimetallic monetary standard of the //Achaemenid Persian Empire.in that era Daric //was the best phenomena in purpose to making //possible exchange in whole world.This is a //contract to celebrate our ancestors and to //remind us of the tradition. The tradition one //that made our lives today. We are going to the //future, while this is our past that drives us //forward. Author, Farhad Ghanaatgar //Constructor contract DaRiCpAy is StandardToken { using SafeMath for uint256; // EVENTS event CreatedIRC(address indexed _creator, uint256 _amountOfIRC); // TOKEN DATA string public constant name = "DaRiC"; string public constant symbol = "IRC"; uint256 public constant decimals = 18; string public version = "1.0"; // IRC TOKEN PURCHASE LIMITS uint256 public maxPresaleSupply; // MAX TOTAL DURING PRESALE (0.8% of MAXTOTALSUPPLY) // PURCHASE DATES uint256 public constant preSaleStartTime = 1516406400; //Saturday, 20-Jan-18 00:00:00 UTC in RFC 2822 uint256 public constant preSaleEndTime = 1518220800 ; // Saturday, 10-Feb-18 00:00:00 UTC in RFC 2822 uint256 public saleStartTime = 1518267600 ; // Saturday, 10-Feb-18 13:00:00 UTC in RFC 2822 uint256 public saleEndTime = 1522429200; //Friday, 30-Mar-18 17:00:00 UTC in RFC 2822 // PURCHASE BONUSES uint256 public lowEtherBonusLimit = 5 * 1 ether; // 5+ Ether uint256 public lowEtherBonusValue = 110; // 10% Discount uint256 public midEtherBonusLimit = 24 * 1 ether; // 24+ Ether uint256 public midEtherBonusValue = 115; // 15% Discount uint256 public highEtherBonusLimit = 50 * 1 ether; // 50+ Ether uint256 public highEtherBonusValue = 120; // 20% Discount uint256 public highTimeBonusLimit = 0; // 1-12 Days uint256 public highTimeBonusValue = 115; // 20% Discount uint256 public midTimeBonusLimit = 1036800; // 12-24 Days uint256 public midTimeBonusValue = 110; // 15% Discount uint256 public lowTimeBonusLimit = 3124800; // 24+ Days uint256 public lowTimeBonusValue = 105; // 5% Discount // PRICING INFO uint256 public constant IRC_PER_ETH_PRE_SALE = 10000; // 10000 IRC = 1 ETH uint256 public constant IRC_PER_ETH_SALE = 8000; // 8000 IRC = 1 ETH // ADDRESSES address public constant ownerAddress = 0x88ce817Efd0dD935Eed8e9d553167d08870AA6e7; // The owners address // STATE INFO bool public allowInvestment = true; // Flag to change if transfering is allowed uint256 public totalWEIInvested = 0; // Total WEI invested uint256 public totalIRCAllocated = 0; // Total IRC allocated mapping (address => uint256) public WEIContributed; // Total WEI Per Account // INITIALIZATIONS FUNCTION function DaRiCpAy() { require(msg.sender == ownerAddress); totalSupply = 20*1000000*1000000000000000000; // MAX TOTAL IRC 20 million uint256 totalIRCReserved = totalSupply.mul(20).div(100); // 20% reserved for IRC maxPresaleSupply = totalSupply*8/1000 + totalIRCReserved; // MAX TOTAL DURING PRESALE (0.8% of MAXTOTALSUPPLY) balances[msg.sender] = totalIRCReserved; totalIRCAllocated = totalIRCReserved; } // FALL BACK FUNCTION TO ALLOW ETHER DONATIONS function() payable { require(allowInvestment); // Smallest investment is 0.00001 ether uint256 amountOfWei = msg.value; require(amountOfWei >= 10000000000000); uint256 amountOfIRC = 0; uint256 absLowTimeBonusLimit = 0; uint256 absMidTimeBonusLimit = 0; uint256 absHighTimeBonusLimit = 0; uint256 totalIRCAvailable = 0; // Investment periods if (now > preSaleStartTime && now < preSaleEndTime) { // Pre-sale ICO amountOfIRC = amountOfWei.mul(IRC_PER_ETH_PRE_SALE); absLowTimeBonusLimit = preSaleStartTime + lowTimeBonusLimit; absMidTimeBonusLimit = preSaleStartTime + midTimeBonusLimit; absHighTimeBonusLimit = preSaleStartTime + highTimeBonusLimit; totalIRCAvailable = maxPresaleSupply - totalIRCAllocated; } else if (now > saleStartTime && now < saleEndTime) { // ICO amountOfIRC = amountOfWei.mul(IRC_PER_ETH_SALE); absLowTimeBonusLimit = saleStartTime + lowTimeBonusLimit; absMidTimeBonusLimit = saleStartTime + midTimeBonusLimit; absHighTimeBonusLimit = saleStartTime + highTimeBonusLimit; totalIRCAvailable = totalSupply - totalIRCAllocated; } else { // Invalid investment period revert(); } // Check that IRC calculated greater than zero assert(amountOfIRC > 0); // Apply Bonuses if (amountOfWei >= highEtherBonusLimit) { amountOfIRC = amountOfIRC.mul(highEtherBonusValue).div(100); } else if (amountOfWei >= midEtherBonusLimit) { amountOfIRC = amountOfIRC.mul(midEtherBonusValue).div(100); } else if (amountOfWei >= lowEtherBonusLimit) { amountOfIRC = amountOfIRC.mul(lowEtherBonusValue).div(100); } if (now >= absLowTimeBonusLimit) { amountOfIRC = amountOfIRC.mul(lowTimeBonusValue).div(100); } else if (now >= absMidTimeBonusLimit) { amountOfIRC = amountOfIRC.mul(midTimeBonusValue).div(100); } else if (now >= absHighTimeBonusLimit) { amountOfIRC = amountOfIRC.mul(highTimeBonusValue).div(100); } // Max sure it doesn't exceed remaining supply assert(amountOfIRC <= totalIRCAvailable); // Update total IRC balance totalIRCAllocated = totalIRCAllocated + amountOfIRC; // Update user IRC balance uint256 balanceSafe = balances[msg.sender].add(amountOfIRC); balances[msg.sender] = balanceSafe; // Update total WEI Invested totalWEIInvested = totalWEIInvested.add(amountOfWei); // Update total WEI Invested by account uint256 contributedSafe = WEIContributed[msg.sender].add(amountOfWei); WEIContributed[msg.sender] = contributedSafe; // CHECK VALUES assert(totalIRCAllocated <= totalSupply); assert(totalIRCAllocated > 0); assert(balanceSafe > 0); assert(totalWEIInvested > 0); assert(contributedSafe > 0); // CREATE EVENT FOR SENDER CreatedIRC(msg.sender, amountOfIRC); } // CHANGE PARAMETERS METHODS function transferEther(address addressToSendTo, uint256 value) { require(msg.sender == ownerAddress); addressToSendTo; addressToSendTo.transfer(value) ; } function changeAllowInvestment(bool _allowInvestment) { require(msg.sender == ownerAddress); allowInvestment = _allowInvestment; } function changeSaleTimes(uint256 _saleStartTime, uint256 _saleEndTime) { require(msg.sender == ownerAddress); saleStartTime = _saleStartTime; saleEndTime = _saleEndTime; } function changeEtherBonuses(uint256 _lowEtherBonusLimit, uint256 _lowEtherBonusValue, uint256 _midEtherBonusLimit, uint256 _midEtherBonusValue, uint256 _highEtherBonusLimit, uint256 _highEtherBonusValue) { require(msg.sender == ownerAddress); lowEtherBonusLimit = _lowEtherBonusLimit; lowEtherBonusValue = _lowEtherBonusValue; midEtherBonusLimit = _midEtherBonusLimit; midEtherBonusValue = _midEtherBonusValue; highEtherBonusLimit = _highEtherBonusLimit; highEtherBonusValue = _highEtherBonusValue; } function changeTimeBonuses(uint256 _highTimeBonusLimit, uint256 _highTimeBonusValue, uint256 _midTimeBonusLimit, uint256 _midTimeBonusValue, uint256 _lowTimeBonusLimit, uint256 _lowTimeBonusValue) { require(msg.sender == ownerAddress); highTimeBonusLimit = _highTimeBonusLimit; highTimeBonusValue = _highTimeBonusValue; midTimeBonusLimit = _midTimeBonusLimit; midTimeBonusValue = _midTimeBonusValue; lowTimeBonusLimit = _lowTimeBonusLimit; lowTimeBonusValue = _lowTimeBonusValue; } }
Flag to change if transfering is allowed
bool public allowInvestment = true;
13,106,117
[ 1, 4678, 358, 2549, 309, 7412, 310, 353, 2935, 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, 202, 6430, 1071, 1699, 3605, 395, 475, 273, 638, 31, 6862, 6862, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUtil { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } interface IStakingProxy { function getBalance() external view returns(uint256); function withdraw(uint256 _amount) external; function stake() external; function distribute() external; } interface IRewardStaking { function stakeFor(address, uint256) external; function stake( uint256) external; function withdraw(uint256 amount, bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address _account) external view returns (uint256); } /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /* * @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; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } interface IGac { function paused() external view returns (bool); function transferFromDisabled() external view returns (bool); function unpause() external; function pause() external; function enableTransferFrom() external; function disableTransferFrom() external; function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } /** * @title Global Access Control Managed - Base Class * @notice allows inheriting contracts to leverage global access control permissions conveniently, as well as granting contract-specific pausing functionality */ contract GlobalAccessControlManaged is PausableUpgradeable { IGac public gac; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); /// ======================= /// ===== Initializer ===== /// ======================= /** * @notice Initializer * @dev this is assumed to be used in the initializer of the inhereiting contract * @param _globalAccessControl global access control which is pinged to allow / deny access to permissioned calls by role */ function __GlobalAccessControlManaged_init(address _globalAccessControl) public initializer { __Pausable_init_unchained(); gac = IGac(_globalAccessControl); } /// ===================== /// ===== Modifiers ===== /// ===================== // @dev only holders of the given role on the GAC can call modifier onlyRole(bytes32 role) { require(gac.hasRole(role, msg.sender), "GAC: invalid-caller-role"); _; } // @dev only holders of any of the given set of roles on the GAC can call modifier onlyRoles(bytes32[] memory roles) { bool validRoleFound = false; for (uint256 i = 0; i < roles.length; i++) { bytes32 role = roles[i]; if (gac.hasRole(role, msg.sender)) { validRoleFound = true; break; } } require(validRoleFound, "GAC: invalid-caller-role"); _; } // @dev only holders of the given role on the GAC can call, or a specified address // @dev used to faciliate extra contract-specific permissioned accounts modifier onlyRoleOrAddress(bytes32 role, address account) { require( gac.hasRole(role, msg.sender) || msg.sender == account, "GAC: invalid-caller-role-or-address" ); _; } /// @dev can be pausable by GAC or local flag modifier gacPausable() { require(!gac.paused(), "global-paused"); require(!paused(), "local-paused"); _; } /// ================================ /// ===== Permissioned actions ===== /// ================================ function pause() external { require(gac.hasRole(PAUSER_ROLE, msg.sender)); _pause(); } function unpause() external { require(gac.hasRole(UNPAUSER_ROLE, msg.sender)); _unpause(); } } /* Citadel locking contract Adapted from CvxLockerV2.sol (https://github.com/convex-eth/platform/blob/4a51cf7e411db27fa8fc2244137013f9fbdebb38/contracts/contracts/CvxLockerV2.sol). Changes: - Upgradeability - Removed staking */ contract StakedCitadelLocker is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, GlobalAccessControlManaged { using BoringMath for uint256; using BoringMath224 for uint224; using BoringMath112 for uint112; using BoringMath32 for uint32; using SafeERC20Upgradeable for IERC20Upgradeable; /* ========== STATE VARIABLES ========== */ struct Reward { bool useBoost; uint40 periodFinish; uint208 rewardRate; uint40 lastUpdateTime; uint208 rewardPerTokenStored; } struct Balances { uint112 locked; uint112 boosted; uint32 nextUnlockIndex; } struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } struct EarnedData { address token; uint256 amount; } struct Epoch { uint224 supply; //epoch boosted supply uint32 date; //epoch start date } //token constants IERC20Upgradeable public stakingToken; // xCTDL token //rewards address[] public rewardTokens; mapping(address => Reward) public rewardData; // Duration that rewards are streamed over uint256 public constant rewardsDuration = 86400; // 1 day // Duration of lock/earned penalty period uint256 public constant lockDuration = rewardsDuration * 7 * 21; // 21 weeks // reward token -> distributor -> is approved to add rewards mapping(address => mapping(address => bool)) public rewardDistributors; // user -> reward token -> amount mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) public rewards; //supplies and epochs uint256 public lockedSupply; uint256 public boostedSupply; Epoch[] public epochs; //mappings for balance data mapping(address => Balances) public balances; mapping(address => LockedBalance[]) public userLocks; // ========== Not used ========== //boost address public boostPayment = address(0); uint256 public maximumBoostPayment = 0; uint256 public boostRate = 10000; uint256 public nextMaximumBoostPayment = 0; uint256 public nextBoostRate = 10000; uint256 public constant denominator = 10000; // ============================== //staking uint256 public minimumStake = 10000; uint256 public maximumStake = 10000; address public stakingProxy = address(0); uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing //management uint256 public kickRewardPerEpoch = 100; uint256 public kickRewardEpochDelay = 4; //shutdown bool public isShutdown = false; //erc20-like interface string private _name; string private _symbol; uint8 private _decimals; /* ========== CONSTRUCTOR ========== */ function initialize( address _stakingToken, address _gac, string calldata name, string calldata symbol ) public initializer { require(_stakingToken != address(0)); // dev: _stakingToken address should not be zero stakingToken = IERC20Upgradeable(_stakingToken); _name = name; _symbol = symbol; _decimals = 18; uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)})); __Ownable_init(); __ReentrancyGuard_init(); __GlobalAccessControlManaged_init(_gac); } function decimals() public view returns (uint8) { return _decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function version() public view returns (uint256) { return 2; } /* ========== ADMIN CONFIGURATION ========== */ // Add a new reward token to be distributed to stakers function addReward( address _rewardsToken, address _distributor, bool _useBoost ) public onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime == 0); // require(_rewardsToken != address(stakingToken)); rewardTokens.push(_rewardsToken); rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp); rewardData[_rewardsToken].periodFinish = uint40(block.timestamp); rewardData[_rewardsToken].useBoost = _useBoost; rewardDistributors[_rewardsToken][_distributor] = true; } // Modify approval for an address to call notifyRewardAmount function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime > 0); rewardDistributors[_rewardsToken][_distributor] = _approved; } //Set the staking contract for the underlying cvx function setStakingContract(address _staking) external onlyOwner gacPausable { require(stakingProxy == address(0), "!assign"); stakingProxy = _staking; } //set staking limits. will stake the mean of the two once either ratio is crossed function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner gacPausable { require(_minimum <= denominator, "min range"); require(_maximum <= denominator, "max range"); require(_minimum <= _maximum, "min range"); minimumStake = _minimum; maximumStake = _maximum; updateStakeRatio(0); } //set boost parameters function setBoost( uint256 _max, uint256 _rate, address _receivingAddress ) external onlyOwner gacPausable { require(_max < 1500, "over max payment"); //max 15% require(_rate < 30000, "over max rate"); //max 3x require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid nextMaximumBoostPayment = _max; nextBoostRate = _rate; boostPayment = _receivingAddress; } //set kick incentive function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner gacPausable { require(_rate <= 500, "over max rate"); //max 5% per epoch require(_delay >= 2, "min delay"); //minimum 2 epochs of grace kickRewardPerEpoch = _rate; kickRewardEpochDelay = _delay; } //shutdown the contract. unstake all tokens. release all locks function shutdown() external onlyOwner { isShutdown = true; } /* ========== VIEWS ========== */ function getRewardTokens() external view returns (address[] memory) { uint256 numTokens = rewardTokens.length; address[] memory tokens = new address[](numTokens); for (uint256 i = 0; i < numTokens; i++) { tokens[i] = rewardTokens[i]; } return tokens; } function _rewardPerToken(address _rewardsToken) internal view returns (uint256) { if (boostedSupply == 0) { return rewardData[_rewardsToken].rewardPerTokenStored; } return uint256(rewardData[_rewardsToken].rewardPerTokenStored).add( _lastTimeRewardApplicable( rewardData[_rewardsToken].periodFinish ) .sub(rewardData[_rewardsToken].lastUpdateTime) .mul(rewardData[_rewardsToken].rewardRate) .mul(1e18) .div( rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply ) ); } function _earned( address _user, address _rewardsToken, uint256 _balance ) internal view returns (uint256) { return _balance .mul( _rewardPerToken(_rewardsToken).sub( userRewardPerTokenPaid[_user][_rewardsToken] ) ) .div(1e18) .add(rewards[_user][_rewardsToken]); } function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) { return MathUpgradeable.min(block.timestamp, _finishTime); } function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) { return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish); } function rewardPerToken(address _rewardsToken) external view returns (uint256) { return _rewardPerToken(_rewardsToken); } function getRewardForDuration(address _rewardsToken) external view returns (uint256) { return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration); } // Address and claimable amount of all reward tokens for the given account function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) { userRewards = new EarnedData[](rewardTokens.length); Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < userRewards.length; i++) { address token = rewardTokens[i]; userRewards[i].token = token; userRewards[i].amount = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); } return userRewards; } // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens function rewardWeightOf(address _user) external view returns (uint256 amount) { return balances[_user].boosted; } // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount) { return balances[_user].locked; } //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; //start with current boosted amount amount = balances[_user].boosted; uint256 locksLength = locks.length; //remove old records only (will be better gas-wise than adding up) for (uint256 i = nextUnlockIndex; i < locksLength; i++) { if (locks[i].unlockTime <= block.timestamp) { amount = amount.sub(locks[i].boosted); } else { //stop now as no futher checks are needed break; } } //also remove amount locked in the next epoch uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { amount = amount.sub(locks[locksLength - 1].boosted); } return amount; } //BOOSTED balance of an account which only includes properly locked tokens at the given epoch function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get timestamp of given epoch index uint256 epochTime = epochs[_epoch].date; //get timestamp of first non-inclusive epoch uint256 cutoffEpoch = epochTime.sub(lockDuration); //need to add up since the range could be in the middle somewhere //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //lock epoch must be less or equal to the epoch we're basing from. if (lockEpoch <= epochTime) { if (lockEpoch > cutoffEpoch) { amount = amount.add(locks[i].boosted); } else { //stop now as no futher checks matter break; } } } return amount; } //return currently locked but not active balance function pendingLockOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; uint256 locksLength = locks.length; //return amount if latest lock is in the future uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { return locks[locksLength - 1].boosted; } return 0; } function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get next epoch from the given epoch index uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //return the next epoch balance if (lockEpoch == nextEpoch) { return locks[i].boosted; } else if (lockEpoch < nextEpoch) { //no need to check anymore break; } } return 0; } //supply of all properly locked BOOSTED balances at most recent eligible epoch function totalSupply() external view returns (uint256 supply) { uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); uint256 cutoffEpoch = currentEpoch.sub(lockDuration); uint256 epochindex = epochs.length; //do not include next epoch's supply if (uint256(epochs[epochindex - 1].date) > currentEpoch) { epochindex--; } //traverse inversely to make more current queries more gas efficient for (uint256 i = epochindex - 1; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(e.supply); } return supply; } //supply of all properly locked BOOSTED balances at the given epoch function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) { uint256 epochStart = uint256(epochs[_epoch].date) .div(rewardsDuration) .mul(rewardsDuration); uint256 cutoffEpoch = epochStart.sub(lockDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = _epoch; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(epochs[i].supply); } return supply; } //find an epoch index based on timestamp function findEpochId(uint256 _time) external view returns (uint256 epoch) { uint256 max = epochs.length - 1; uint256 min = 0; //convert to start point _time = _time.div(rewardsDuration).mul(rewardsDuration); for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min + max + 1) / 2; uint256 midEpochBlock = epochs[mid].date; if (midEpochBlock == _time) { //found return mid; } else if (midEpochBlock < _time) { min = mid; } else { max = mid - 1; } } return min; } // Information on a user's locked balances function lockedBalances(address _user) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; uint256 idx; for (uint256 i = nextUnlockIndex; i < locks.length; i++) { if (locks[i].unlockTime > block.timestamp) { if (idx == 0) { lockData = new LockedBalance[](locks.length - i); } lockData[idx] = locks[i]; idx++; locked = locked.add(locks[i].amount); } else { unlockable = unlockable.add(locks[i].amount); } } return (userBalance.locked, unlockable, locked, lockData); } //number of epochs function epochCount() external view returns (uint256) { return epochs.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function checkpointEpoch() external { _checkpointEpoch(); } //insert a new epoch if needed. fill in any gaps function _checkpointEpoch() internal { //create new epoch in the future where new non-active locks will lock to uint256 nextEpoch = block .timestamp .div(rewardsDuration) .mul(rewardsDuration) .add(rewardsDuration); uint256 epochindex = epochs.length; //first epoch add in constructor, no need to check 0 length //check to add if (epochs[epochindex - 1].date < nextEpoch) { //fill any epoch gaps while (epochs[epochs.length - 1].date != nextEpoch) { uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date) .add(rewardsDuration); epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)})); } //update boost parameters on a new epoch if (boostRate != nextBoostRate) { boostRate = nextBoostRate; } if (maximumBoostPayment != nextMaximumBoostPayment) { maximumBoostPayment = nextMaximumBoostPayment; } } } // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards function lock( address _account, uint256 _amount, uint256 _spendRatio ) external nonReentrant gacPausable updateReward(_account) { //pull tokens stakingToken.safeTransferFrom(msg.sender, address(this), _amount); //lock _lock(_account, _amount, _spendRatio, false); } //lock tokens function _lock( address _account, uint256 _amount, uint256 _spendRatio, bool _isRelock ) internal { require(_amount > 0, "Cannot stake 0"); require(_spendRatio <= maximumBoostPayment, "over max spend"); require(!isShutdown, "shutdown"); Balances storage bal = balances[_account]; //must try check pointing epoch first _checkpointEpoch(); //calc lock and boosted amount uint256 spendAmount = _amount.mul(_spendRatio).div(denominator); uint256 boostRatio = boostRate.mul(_spendRatio).div( maximumBoostPayment == 0 ? 1 : maximumBoostPayment ); uint112 lockAmount = _amount.sub(spendAmount).to112(); uint112 boostedAmount = _amount .add(_amount.mul(boostRatio).div(denominator)) .to112(); //add user balances bal.locked = bal.locked.add(lockAmount); bal.boosted = bal.boosted.add(boostedAmount); //add to total supplies lockedSupply = lockedSupply.add(lockAmount); boostedSupply = boostedSupply.add(boostedAmount); //add user lock records or add to current uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); //if a fresh lock, add on an extra duration period if (!_isRelock) { lockEpoch = lockEpoch.add(rewardsDuration); } uint256 unlockTime = lockEpoch.add(lockDuration); uint256 idx = userLocks[_account].length; //if the latest user lock is smaller than this lock, always just add new entry to the end of the list if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) { userLocks[_account].push( LockedBalance({ amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime) }) ); } else { //else add to a current lock //if latest lock is further in the future, lower index //this can only happen if relocking an expired lock after creating a new lock if (userLocks[_account][idx - 1].unlockTime > unlockTime) { idx--; } //if idx points to the epoch when same unlock time, update //(this is always true with a normal lock but maybe not with relock) if (userLocks[_account][idx - 1].unlockTime == unlockTime) { LockedBalance storage userL = userLocks[_account][idx - 1]; userL.amount = userL.amount.add(lockAmount); userL.boosted = userL.boosted.add(boostedAmount); } else { //can only enter here if a relock is made after a lock and there's no lock entry //for the current epoch. //ex a list of locks such as "[...][older][current*][next]" but without a "current" lock //length - 1 is the next epoch //length - 2 is a past epoch //thus need to insert an entry for current epoch at the 2nd to last entry //we will copy and insert the tail entry(next) and then overwrite length-2 entry //reset idx idx = userLocks[_account].length; //get current last item LockedBalance storage userL = userLocks[_account][idx - 1]; //add a copy to end of list userLocks[_account].push( LockedBalance({ amount: userL.amount, boosted: userL.boosted, unlockTime: userL.unlockTime }) ); //insert current epoch lock entry by overwriting the entry at length-2 userL.amount = lockAmount; userL.boosted = boostedAmount; userL.unlockTime = uint32(unlockTime); } } //update epoch supply, epoch checkpointed above so safe to add to latest uint256 eIndex = epochs.length - 1; //if relock, epoch should be current and not next, thus need to decrease index to length-2 if (_isRelock) { eIndex--; } Epoch storage e = epochs[eIndex]; e.supply = e.supply.add(uint224(boostedAmount)); //send boost payment if (spendAmount > 0) { stakingToken.safeTransfer(boostPayment, spendAmount); } emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount); } // Withdraw all currently locked tokens where the unlock time has passed function _processExpiredLocks( address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay ) internal updateReward(_account) { LockedBalance[] storage locks = userLocks[_account]; Balances storage userBalance = balances[_account]; uint112 locked; uint112 boostedAmount; uint256 length = locks.length; uint256 reward = 0; if ( isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay) ) { //if time is beyond last lock, can just bundle everything together locked = userBalance.locked; boostedAmount = userBalance.boosted; //dont delete, just set next index userBalance.nextUnlockIndex = length.to32(); //check for kick reward //this wont have the exact reward rate that you would get if looped through //but this section is supposed to be for quick and easy low gas processing of all locks //we'll assume that if the reward was good enough someone would have processed at an earlier epoch if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[length - 1].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = uint256(locks[length - 1].amount).mul(rRate).div( denominator ); } } else { //use a processed index(nextUnlockIndex) to not loop as much //deleting does not change array length uint32 nextUnlockIndex = userBalance.nextUnlockIndex; for (uint256 i = nextUnlockIndex; i < length; i++) { //unlock time must be less or equal to time if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break; //add to cumulative amounts locked = locked.add(locks[i].amount); boostedAmount = boostedAmount.add(locks[i].boosted); //check for kick reward //each epoch over due increases reward if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[i].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator) ); } //set next unlock index nextUnlockIndex++; } //update next unlock index userBalance.nextUnlockIndex = nextUnlockIndex; } require(locked > 0, "no exp locks"); //update user balances and total supplies userBalance.locked = userBalance.locked.sub(locked); userBalance.boosted = userBalance.boosted.sub(boostedAmount); lockedSupply = lockedSupply.sub(locked); boostedSupply = boostedSupply.sub(boostedAmount); emit Withdrawn(_account, locked, _relock); //send process incentive if (reward > 0) { //if theres a reward(kicked), it will always be a withdraw only //preallocate enough cvx from stake contract to pay for both reward and withdraw allocateCVXForTransfer(uint256(locked)); //reduce return amount by the kick reward locked = locked.sub(reward.to112()); //transfer reward transferCVX(_rewardAddress, reward, false); emit KickReward(_rewardAddress, _account, reward); } else if (_spendRatio > 0) { //preallocate enough cvx to transfer the boost cost allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) ); } //relock or return to user if (_relock) { _lock(_withdrawTo, locked, _spendRatio, true); } else { transferCVX(_withdrawTo, locked, true); } } // withdraw expired locks to a different address function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0); } // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0); } function kickExpiredLocks(address _account) external nonReentrant gacPausable { //allow kick after grace period of 'kickRewardEpochDelay' _processExpiredLocks( _account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay) ); } //pull required amount of cvx from staking for an upcoming transfer // dev: no-op function allocateCVXForTransfer(uint256 _amount) internal { uint256 balance = stakingToken.balanceOf(address(this)); } //transfer helper: pull enough from staking, transfer, updating staking ratio function transferCVX( address _account, uint256 _amount, bool _updateStake ) internal { //allocate enough cvx from staking for the transfer allocateCVXForTransfer(_amount); //transfer stakingToken.safeTransfer(_account, _amount); } //calculate how much cvx should be staked. update if needed function updateStakeRatio(uint256 _offset) internal { if (isShutdown) return; //get balances uint256 local = stakingToken.balanceOf(address(this)); uint256 staked = IStakingProxy(stakingProxy).getBalance(); uint256 total = local.add(staked); if (total == 0) return; //current staked ratio uint256 ratio = staked.mul(denominator).div(total); //mean will be where we reset to if unbalanced uint256 mean = maximumStake.add(minimumStake).div(2); uint256 max = maximumStake.add(_offset); uint256 min = MathUpgradeable.min(minimumStake, minimumStake - _offset); if (ratio > max) { //remove uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove); } else if (ratio < min) { //add uint256 increase = total.mul(mean).div(denominator).sub(staked); stakingToken.safeTransfer(stakingProxy, increase); IStakingProxy(stakingProxy).stake(); } } // Claim all pending rewards function getReward(address _account, bool _stake) public nonReentrant gacPausable updateReward(_account) { for (uint256 i; i < rewardTokens.length; i++) { address _rewardsToken = rewardTokens[i]; uint256 reward = rewards[_account][_rewardsToken]; if (reward > 0) { rewards[_account][_rewardsToken] = 0; IERC20Upgradeable(_rewardsToken).safeTransfer(_account, reward); emit RewardPaid(_account, _rewardsToken, reward); } } } // claim all pending rewards function getReward(address _account) external { getReward(_account, false); } /* ========== RESTRICTED FUNCTIONS ========== */ function _notifyReward(address _rewardsToken, uint256 _reward) internal { Reward storage rdata = rewardData[_rewardsToken]; if (block.timestamp >= rdata.periodFinish) { rdata.rewardRate = _reward.div(rewardsDuration).to208(); } else { uint256 remaining = uint256(rdata.periodFinish).sub( block.timestamp ); uint256 leftover = remaining.mul(rdata.rewardRate); rdata.rewardRate = _reward .add(leftover) .div(rewardsDuration) .to208(); } rdata.lastUpdateTime = block.timestamp.to40(); rdata.periodFinish = block.timestamp.add(rewardsDuration).to40(); } function notifyRewardAmount(address _rewardsToken, uint256 _reward) external gacPausable updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender]); require(_reward > 0, "No reward"); _notifyReward(_rewardsToken, _reward); // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the _reward amount IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); emit RewardAdded(_rewardsToken, _reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner gacPausable { require( _tokenAddress != address(stakingToken), "Cannot withdraw staking token" ); require( rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token" ); IERC20Upgradeable(_tokenAddress).safeTransfer(owner(), _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /* ========== MODIFIERS ========== */ modifier updateReward(address _account) { { //stack too deep Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < rewardTokens.length; i++) { address token = rewardTokens[i]; rewardData[token].rewardPerTokenStored = _rewardPerToken(token) .to208(); rewardData[token].lastUpdateTime = _lastTimeRewardApplicable( rewardData[token].periodFinish ).to40(); if (_account != address(0)) { //check if reward is boostable or not. use boosted or locked balance accordingly rewards[_account][token] = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); userRewardPerTokenPaid[_account][token] = rewardData[token] .rewardPerTokenStored; } } } _; } /* ========== EVENTS ========== */ event RewardAdded(address indexed _token, uint256 _reward); event Staked( address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount ); event Withdrawn(address indexed _user, uint256 _amount, bool _relocked); event KickReward( address indexed _user, address indexed _kicked, uint256 _reward ); event RewardPaid( address indexed _user, address indexed _rewardsToken, uint256 _reward ); event Recovered(address _token, uint256 _amount); }
handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the _reward amount
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external gacPausable updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender]); require(_reward > 0, "No reward"); _notifyReward(_rewardsToken, _reward); IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); emit RewardAdded(_rewardsToken, _reward); }
1,374,774
[ 1, 4110, 326, 7412, 434, 19890, 2430, 3970, 1375, 13866, 1265, 68, 358, 5459, 326, 1300, 434, 8938, 1931, 471, 3387, 3434, 4496, 434, 326, 389, 266, 2913, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5066, 17631, 1060, 6275, 12, 2867, 389, 266, 6397, 1345, 16, 2254, 5034, 389, 266, 2913, 13, 203, 3639, 3903, 203, 3639, 314, 1077, 16507, 16665, 203, 3639, 1089, 17631, 1060, 12, 2867, 12, 20, 3719, 203, 565, 288, 203, 3639, 2583, 12, 266, 2913, 1669, 665, 13595, 63, 67, 266, 6397, 1345, 6362, 3576, 18, 15330, 19226, 203, 3639, 2583, 24899, 266, 2913, 405, 374, 16, 315, 2279, 19890, 8863, 203, 203, 3639, 389, 12336, 17631, 1060, 24899, 266, 6397, 1345, 16, 389, 266, 2913, 1769, 203, 203, 3639, 467, 654, 39, 3462, 10784, 429, 24899, 266, 6397, 1345, 2934, 4626, 5912, 1265, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 389, 266, 2913, 203, 3639, 11272, 203, 203, 3639, 3626, 534, 359, 1060, 8602, 24899, 266, 6397, 1345, 16, 389, 266, 2913, 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 ]
contract NewPoll { //defines the poll struct Poll { address owner; string title; uint votelimit; string options; uint deadline; bool status; uint numVotes; } // event tracking of all votes event NewVote(string votechoice); // declare a public poll called p Poll public p; //initiator function that stores the necessary poll information function NewPoll(string _options, string _title, uint _votelimit, uint _deadline) { p.owner = msg.sender; p.options = _options; p.title = _title; p.votelimit = _votelimit; p.deadline = _deadline; p.status = true; p.numVotes = 0; } //function for user vote. input is a string choice function vote(string choice) returns (bool) { if (msg.sender != p.owner || p.status != true) { return false; } p.numVotes += 1; NewVote(choice); // if votelimit reached, end poll if (p.votelimit > 0) { if (p.numVotes >= p.votelimit) { endPoll(); } } return true; } //when time or vote limit is reached, set the poll status to false function endPoll() returns (bool) { if (msg.sender != p.owner) { return false; } p.status = false; return true; } }
function for user vote. input is a string choice if votelimit reached, end poll
function vote(string choice) returns (bool) { if (msg.sender != p.owner || p.status != true) { return false; } p.numVotes += 1; NewVote(choice); if (p.votelimit > 0) { if (p.numVotes >= p.votelimit) { endPoll(); } } return true; }
1,059,617
[ 1, 915, 364, 729, 12501, 18, 810, 353, 279, 533, 6023, 309, 331, 352, 19741, 8675, 16, 679, 7672, 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, 12501, 12, 1080, 6023, 13, 1135, 261, 6430, 13, 288, 203, 565, 309, 261, 3576, 18, 15330, 480, 293, 18, 8443, 747, 293, 18, 2327, 480, 638, 13, 288, 203, 1377, 327, 629, 31, 203, 565, 289, 203, 203, 565, 293, 18, 2107, 29637, 1011, 404, 31, 203, 565, 1166, 19338, 12, 11569, 1769, 203, 203, 565, 309, 261, 84, 18, 90, 352, 19741, 405, 374, 13, 288, 203, 1377, 309, 261, 84, 18, 2107, 29637, 1545, 293, 18, 90, 352, 19741, 13, 288, 203, 3639, 679, 19085, 5621, 203, 1377, 289, 203, 565, 289, 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 ]
./full_match/1/0x4c207f4acE27B9F29F7A2C9e4ECf8eb7dFe1cf7e/sources/contracts/NuCyberStaking.sol
* @notice Stakes a NuCyber token. @param tokenId_ the token being staked @param beneficiary_ an address that will benefit from the token being staked Requirements: - Caller must own `tokenId_` - Emits a {BenefitStarted} event if `beneficiary_` is not null - This contract must be allowed to transfer NuCyber tokens on behalf of the caller/
function stake(uint256 tokenId_, address beneficiary_, Rarity rarity_, Proof calldata proof_) public isState(ACTIVE) { if (fxChildTunnel == address(0)) { revert NCS_REWARDS_NOT_SET(); } Rarity _knownRarity_ = rarity[tokenId_]; if (_knownRarity_ == Rarity.NONE) { if (!_validateProof(tokenId_, uint8(rarity_), proof_)) { revert NCS_INCORRECT_RARITY(tokenId_); } rarity[tokenId_] = rarity_; _knownRarity_ = rarity_; } _stakeToken(msg.sender, tokenId_, beneficiary_/*, _knownRarity_*/); _sendMessage(msg.sender, _knownRarity_, 1, true); }
17,123,936
[ 1, 510, 3223, 279, 20123, 17992, 744, 1147, 18, 225, 1147, 548, 67, 326, 1147, 3832, 384, 9477, 225, 27641, 74, 14463, 814, 67, 392, 1758, 716, 903, 27641, 7216, 628, 326, 1147, 3832, 384, 9477, 29076, 30, 300, 20646, 1297, 4953, 1375, 2316, 548, 67, 68, 300, 7377, 1282, 279, 288, 38, 4009, 7216, 9217, 97, 871, 309, 1375, 70, 4009, 74, 14463, 814, 67, 68, 353, 486, 446, 300, 1220, 6835, 1297, 506, 2935, 358, 7412, 20123, 17992, 744, 2430, 603, 12433, 6186, 434, 326, 4894, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 384, 911, 12, 11890, 5034, 1147, 548, 67, 16, 1758, 27641, 74, 14463, 814, 67, 16, 534, 20498, 436, 20498, 67, 16, 1186, 792, 745, 892, 14601, 67, 13, 203, 565, 1071, 203, 565, 353, 1119, 12, 13301, 13, 288, 203, 1377, 309, 261, 19595, 1763, 20329, 422, 1758, 12, 20, 3719, 288, 203, 3639, 15226, 423, 4596, 67, 862, 16777, 3948, 67, 4400, 67, 4043, 5621, 203, 1377, 289, 203, 1377, 534, 20498, 389, 2994, 54, 20498, 67, 273, 436, 20498, 63, 2316, 548, 67, 15533, 203, 1377, 309, 261, 67, 2994, 54, 20498, 67, 422, 534, 20498, 18, 9826, 13, 288, 203, 3639, 309, 16051, 67, 5662, 20439, 12, 2316, 548, 67, 16, 2254, 28, 12, 86, 20498, 67, 3631, 14601, 67, 3719, 288, 203, 1850, 15226, 423, 4596, 67, 706, 9428, 4512, 67, 54, 985, 4107, 12, 2316, 548, 67, 1769, 203, 3639, 289, 203, 3639, 436, 20498, 63, 2316, 548, 67, 65, 273, 436, 20498, 67, 31, 203, 3639, 389, 2994, 54, 20498, 67, 273, 436, 20498, 67, 31, 203, 1377, 289, 203, 1377, 389, 334, 911, 1345, 12, 3576, 18, 15330, 16, 1147, 548, 67, 16, 27641, 74, 14463, 814, 67, 20308, 16, 389, 2994, 54, 20498, 67, 5549, 1769, 203, 1377, 389, 4661, 1079, 12, 3576, 18, 15330, 16, 389, 2994, 54, 20498, 67, 16, 404, 16, 638, 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 ]
./partial_match/1/0x6FAEB511989E280D3A51ca45ED756C90e736b012/sources/@violetprotocol/mauve-periphery/contracts/base/Multicall.sol
@inheritdoc IMulticall Next 5 lines from https:ethereum.stackexchange.com/a/83577
function multicall(bytes[] calldata data) public payable virtual override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } }
15,680,922
[ 1, 36, 10093, 467, 5049, 335, 454, 4804, 1381, 2362, 628, 2333, 30, 546, 822, 379, 18, 3772, 16641, 18, 832, 19, 69, 19, 28, 4763, 4700, 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, 1778, 335, 454, 12, 3890, 8526, 745, 892, 501, 13, 1071, 8843, 429, 5024, 3849, 1135, 261, 3890, 8526, 3778, 1686, 13, 288, 203, 3639, 1686, 273, 394, 1731, 8526, 12, 892, 18, 2469, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 501, 18, 2469, 31, 277, 27245, 288, 203, 5411, 261, 6430, 2216, 16, 1731, 3778, 563, 13, 273, 1758, 12, 2211, 2934, 22216, 1991, 12, 892, 63, 77, 19226, 203, 203, 5411, 309, 16051, 4768, 13, 288, 203, 7734, 309, 261, 2088, 18, 2469, 411, 23797, 13, 15226, 5621, 203, 7734, 19931, 288, 203, 10792, 563, 519, 527, 12, 2088, 16, 374, 92, 3028, 13, 203, 7734, 289, 203, 7734, 15226, 12, 21457, 18, 3922, 12, 2088, 16, 261, 1080, 3719, 1769, 203, 5411, 289, 203, 203, 5411, 1686, 63, 77, 65, 273, 563, 31, 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 ]
./full_match/80001/0x72C87B8B8afD695513C45601983647931f4Caa28/sources/contracts/DAO/SharedAddress/SharedAddress.sol
@inheritdoc ISharedAddress
function hasAccess( uint256 _hat, IDAO.Action[] calldata _actions ) public view returns (bool) { if (!fullAccess[_hat]) { for (uint i; i < _actions.length; ) { if (!_hasAccess(_hat, _actions[i])) { return false; } unchecked { ++i; } } } return true; }
862,462
[ 1, 36, 10093, 467, 7887, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24836, 12, 203, 3639, 2254, 5034, 389, 11304, 16, 203, 3639, 1599, 20463, 18, 1803, 8526, 745, 892, 389, 4905, 203, 565, 262, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 2854, 1862, 63, 67, 11304, 5717, 288, 203, 5411, 364, 261, 11890, 277, 31, 277, 411, 389, 4905, 18, 2469, 31, 262, 288, 203, 7734, 309, 16051, 67, 5332, 1862, 24899, 11304, 16, 389, 4905, 63, 77, 22643, 288, 203, 10792, 327, 629, 31, 203, 7734, 289, 203, 203, 7734, 22893, 288, 203, 10792, 965, 77, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; // 請使用solc 0.4.20編譯,否則會有問題 contract Owned { address owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { if(msg.sender!=owner) throw; _; } } // 存放清算銀行客戶的在債券數量,以便於使用清算銀行及客戶帳號為key來查詢 // 注意Owner為TransactionMatcher contract contract Bank_Account is Owned { bytes32 bank_id; uint customers_cnt; bool private isOwnedNode = false; // 使用private transaction來設定flag, // 每個Bank_Account Contract只有在自己跟央行才會設flag // 以便判斷是在那個節點上跑 struct customer { bytes32 [] ids; mapping(bytes32 => securities_account) securities_accounts; // 以id為index mapping(bytes32 => bool) hasCustomer; } struct securities_account { bytes32 [] securities; // 債券清單 uint securities_cnt; mapping(bytes32 => int) total_amounts; // 總數量 以債券代號為index mapping(bytes32 => int) position_amounts; // 持有部位 以債券代號為index mapping(bytes32 => bool) hasSecurities; } customer private customers; function Bank_Account(bytes32 _bank_id) { bank_id = _bank_id; } function setOwnedNode(bool _is_true) onlyOwner { isOwnedNode = _is_true; } function checkOwnedNode() constant returns(bool) { return isOwnedNode; } // 設定客戶擁有債券數量,注意,清算銀行自己本身也有帳號 客戶持有部位也要增加 function setCustomerOwnedSecuritiesAmount(bytes32 _customer_id, bytes32 _securities_id, int _amount_total, bool _is_increase) onlyOwner { if(!customers.hasCustomer[_customer_id]) { customers.ids.push(_customer_id); customers_cnt++; customers.hasCustomer[_customer_id] = true; } if(!customers.securities_accounts[_customer_id].hasSecurities[_securities_id]) { customers.securities_accounts[_customer_id].securities.push(_securities_id); customers.securities_accounts[_customer_id].securities_cnt++; customers.securities_accounts[_customer_id].hasSecurities[_securities_id] = true; } int total_amount = customers.securities_accounts[_customer_id].total_amounts[_securities_id]; if(_is_increase) { total_amount += _amount_total; }else { total_amount -= _amount_total; } customers.securities_accounts[_customer_id].total_amounts[_securities_id] = total_amount; } function setCustomerOwnedSecuritiesPosition(bytes32 _customer_id, bytes32 _securities_id, int _amount, bool _is_increase) onlyOwner { int position_amount = customers.securities_accounts[_customer_id].position_amounts[_securities_id]; if(_is_increase) { position_amount += _amount; }else { position_amount -= _amount; } customers.securities_accounts[_customer_id].position_amounts[_securities_id] = position_amount; } function getCustomerSecuritiesTotalAmount(bytes32 _customer_id, bytes32 _securities_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(customers.securities_accounts[_customer_id].total_amounts[_securities_id]); } function getCustomerSecuritiesPosition(bytes32 _customer_id, bytes32 _securities_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(customers.securities_accounts[_customer_id].position_amounts[_securities_id]); } function getCustomerSecuritiesList(bytes32 _customer_id, uint index) constant returns (bytes32) { return(customers.securities_accounts[_customer_id].securities[index]); } function getCustomerSecuritiesListLength(bytes32 _customer_id) constant returns (uint) { return(customers.securities_accounts[_customer_id].securities_cnt); } function getCustomerList(uint index) constant returns (bytes32) { return(customers.ids[index]); } function getCustomerListLength() constant returns (uint) { return(customers_cnt); } } // 注意Owner為TransactionMatcher contract contract Securities is Owned{ bytes32 securities_id; // 公債代號 bytes32 owned_bank; uint banks_cnt; int amount; int available; // 還剩多少債券 // int unit_price; int interest_rateX10K; // *10000 i.e 2% interest_rate = 200 精確到小數點第二位 int start_tm; int end_tm; int period; // 單位:Year(每年一期) struct bank { bytes32 [] bank_ids; // 清算銀行list mapping(bytes32 => customers_account) customers_accounts; // 客戶account 以清算銀行為index mapping(bytes32 => bool) hasBank; // 以清算銀行為index mapping(bytes32 => int) banks_total_amount; // 清算銀行總帳(計算利息) 以清算銀行為index mapping(bytes32 => int) banks_position_amount; // 清算銀行持有部位(總帳 - 被圈存總帳) 以清算銀行為index } struct customers_account { bytes32 [] customer_ids; // 客戶帳號list uint customers_cnt; mapping(bytes32 => int) total_amounts; // 客戶擁有數量 以客戶帳號為index mapping(bytes32 => int) position_amounts; // 客戶持有部位(總帳 - 被圈存數量) 以客戶帳號為index mapping(bytes32 => bool) hasCustomer; // 是否有此客戶 以客戶帳號為index } bank private banks; function Securities(bytes32 _securities_id, int _amount, int _interest_rateX10K, int _start_tm, int _end_tm, int _period) { securities_id = _securities_id; owned_bank = "CB"; // centeral bank is the initial owner amount = _amount; available = _amount; //unit_price = _unit_price; interest_rateX10K = _interest_rateX10K; start_tm = _start_tm; end_tm = _end_tm; period = _period; } // 變更客戶擁有債券數量,注意,清算銀行自己本身也有帳號 function setCustomerOwnedSecuritiesAmount(bytes32 _bank_id, bytes32 _customer_id, int _amount_total, bool _is_increase) onlyOwner { if(!banks.hasBank[_bank_id]) { banks.bank_ids.push(_bank_id); banks.hasBank[_bank_id] = true; banks_cnt++; } if(!banks.customers_accounts[_bank_id].hasCustomer[_customer_id]) { banks.customers_accounts[_bank_id].customer_ids.push(_customer_id); banks.customers_accounts[_bank_id].customers_cnt++; banks.customers_accounts[_bank_id].hasCustomer[_customer_id] = true; } int customer_amount = banks.customers_accounts[_bank_id].total_amounts[_customer_id]; int bank_amount = banks.banks_total_amount[_bank_id]; //int customer_position_amount = banks.customers_accounts[_bank_id].position_amounts[_customer_id]; //int bank_position_amount = banks.banks_position_amount[_bank_id]; if(_is_increase) { customer_amount += _amount_total; bank_amount += _amount_total; available -= _amount_total; //customer_position_amount += _amount_total; //bank_position_amount += _amount_total; }else { customer_amount -= _amount_total; bank_amount -= _amount_total; available += _amount_total; //customer_position_amount -= _amount_total; //bank_position_amount -= _amount_total; } banks.customers_accounts[_bank_id].total_amounts[_customer_id] = customer_amount; banks.banks_total_amount[_bank_id] = bank_amount; //banks.customers_accounts[_bank_id].position_amounts[_customer_id] = customer_position_amount; //banks.banks_position_amount[_bank_id] = bank_position_amount; } // 設定圈存 function setCustomerOwnedSecuritiesPosition(bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner { int customer_position_amount = banks.customers_accounts[_bank_id].position_amounts[_customer_id]; int bank_position_amount = banks.banks_position_amount[_bank_id]; if(_is_increase) { customer_position_amount += _amount; bank_position_amount += _amount; }else { customer_position_amount -= _amount; bank_position_amount -= _amount; } banks.customers_accounts[_bank_id].position_amounts[_customer_id] = customer_position_amount; banks.banks_position_amount[_bank_id] = bank_position_amount; } function getSecuritiesStatus() constant returns(int, int) { return(amount, available); } function getSecuritiesInfo() constant returns(int, int, int, int) { return(interest_rateX10K, start_tm, end_tm, period); } function getCustomerTotalAmount(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.customers_accounts[_bank_id].total_amounts[_customer_id]); } function getCustomerPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.customers_accounts[_bank_id].position_amounts[_customer_id]); } function getBankTotalAmount(bytes32 _bank_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.banks_total_amount[_bank_id]); } function getBankPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.banks_position_amount[_bank_id]); } function getBankList(uint index) constant returns(bytes32) { return(banks.bank_ids[index]); } function getBankListLength() constant returns(uint) { return(banks_cnt); } } // TransactionMatcher必須由央行deploy 如此央行才能成為owner contract TransactionMatcher is Owned { //address private owner; //uint private maxQueueDepth; //uint private timeout; uint ServiceState; // 1: 開機 2: 營業開始 3: 停止接收預告 // 4: 停止接收電文 5: 處理跨行交易 6: 發送結帳資料 7: 關機 bytes32[] shareQueue; // 跨行交易用的queue bytes32[] privateQueue; // 自行交易用的queue function TransactionMatcher() { owner = msg.sender; //maxQueueDepth = 100; } enum TxnState { Pending, Matched, Finished, Cancelled, Waiting4Payment } struct Transaction { bytes32 txnSerNo; // 交易代號 bytes32 from_bank_id; // 賣方清算銀行代號 bytes32 from_customer_id; // 賣方帳號 bytes32 to_bank_id; // 買方清算銀行代號 bytes32 to_customer_id; // 買方帳號 int securities_amount; // 交易面額 int blocked_amount; // 圈存面額 bytes32 securities_id; // 債券代號 int payment; // 紀錄實際成交金額 TxnState state; // 交易狀態 uint timestamp; // 交易發送時間 bytes32 digest; // 交易摘要(MD5) 買賣雙方的交易摘要需相同才可比對 address msg_sender; // 發送交易之區塊鏈帳戶 bytes32 rev_txnSerNo; // 紀錄被更正之交易代號 int return_code; // 紀錄傳回值 } bytes32[] transactionIdx; mapping (bytes32 => Transaction) transactions; mapping (bytes32 => bool) isTransactionWaitingForMatch; // has a transaction registered in the list mapping (bytes32 => bytes32) txnDigest_SerNo1; // txn digest => txnSerNo //mapping (bytes32 => bytes32) txnDigest_SerNo2; // txn digest => txnSerNo bytes32[] banks_list; mapping (bytes32 => address) bankRegistry; //mapping (address => bytes32) acc2Bank; //mapping (bytes32 => address) bankAdmins; bytes32[] securities_list; uint securities_cnt; mapping (bytes32 => address) securitiesRegistry; mapping (bytes32 => bool) hasSecurities; /* modifier isBankOwner(bytes32 _bank_id) { require(msg.sender == owner || acc2Bank[msg.sender] == _bank_id); _; } */ event EventForCreateBank(bytes32 _bank_id); event EventForSetOwnedNode(bytes32 _bank_id); event EventForIssueSecurities(bytes32 _securities_id); event EventForRegisterCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase); event EventForSetServiceState(uint state); //event EventForSetCustomerOwnedSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount_total, bool _is_increase); // privateFor[央行與所有清算行] function createBank(bytes32 _bank_id, address _bankOwner) onlyOwner { address bank = new Bank_Account(_bank_id); bankRegistry[_bank_id] = bank; // 清算銀行Bank_Account合約位址 banks_list.push(_bank_id); //bankAdmins[_bank_id] = _bankOwner; EventForCreateBank(_bank_id); } // privateFor[央行與被建立的清算行] // 可以讓被建立的清算行利用checkOwnedNode傳回true判斷是自己的節點 因為節點不會看到別人的Bank_Account Contract function setOwnedNode(bytes32 _bank_id, bool _is_true) onlyOwner { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setOwnedNode(true); //bank.setBankContract(_bank_contract); EventForSetOwnedNode(_bank_id); } function issueSecurities(bytes32 _securities_id, int _amount, int _interest_rateX10K, int _start_tm, int _end_tm, int _period) onlyOwner { if(!hasSecurities[_securities_id]) { securities_list.push(_securities_id); hasSecurities[_securities_id]=true; securities_cnt++; } address securities = new Securities(_securities_id, _amount, _interest_rateX10K, _start_tm, _end_tm, _period); securitiesRegistry[_securities_id] = securities; EventForIssueSecurities(_securities_id); } function registerCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner { setCustomerOwnedSecuritiesAmount(_securities_id,_bank_id,_customer_id,_amount,_is_increase); // 註冊時要順便增加/減少持有部位 setCustomerOwnedSecuritiesPosition(_securities_id,_bank_id,_customer_id,_amount,_is_increase); EventForRegisterCustomerOwnedSecuritiesAmount(_securities_id,_bank_id,_customer_id,_amount,_is_increase); } // 只能internal 呼叫,避免鏈外隨便可以改帳目 function setCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal { Securities securities = Securities(securitiesRegistry[_securities_id]); securities.setCustomerOwnedSecuritiesAmount(_bank_id, _customer_id, _amount, _is_increase); Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setCustomerOwnedSecuritiesAmount(_customer_id, _securities_id, _amount, _is_increase); //EventForSetCustomerOwnedSecuritiesAmount( _securities_id, _bank_id, _customer_id, _amount, _is_increase); } // 只能internal 呼叫,避免鏈外隨便可以改帳目 function setCustomerOwnedSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal { Securities securities = Securities(securitiesRegistry[_securities_id]); securities.setCustomerOwnedSecuritiesPosition(_bank_id, _customer_id, _amount, _is_increase); Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setCustomerOwnedSecuritiesPosition(_customer_id, _securities_id, _amount, _is_increase); //EventForSetCustomerOwnedSecuritiesPosition( _securities_id, _bank_id, _customer_id, _amount, _is_increase); } function getSecuritiesStatus(bytes32 _securities_id) constant returns(int,int) { Securities securities = Securities(securitiesRegistry[_securities_id]); var(a,b) = securities.getSecuritiesStatus(); return(a,b); } function getSecuritiesInfo(bytes32 _securities_id) constant returns(int,int,int,int) { Securities securities = Securities(securitiesRegistry[_securities_id]); var(a,b,c,d) = securities.getSecuritiesInfo(); return(a,b,c,d); } function getBankSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id) constant returns(int) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getBankTotalAmount(_bank_id)); } function getCustomerSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getCustomerTotalAmount(_bank_id, _customer_id)); } function getCustomerSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getCustomerPosition(_bank_id, _customer_id)); } function getCustomerSecuritiesListLength(bytes32 _bank_id, bytes32 _customer_id) constant returns(uint) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerSecuritiesListLength(_customer_id)); } function getCustomerSecuritiesList(bytes32 _bank_id, bytes32 _customer_id, uint index) constant returns(bytes32) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerSecuritiesList(_customer_id, index)); } function getBankListLength(bytes32 _securities_id) constant returns(uint) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getBankListLength()); } function getBankCustomerList(bytes32 _bank_id, uint index) constant returns(bytes32) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerList(index)); } function getBankCustomerListLength(bytes32 _bank_id) constant returns(uint) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerListLength()); } function getSecuritiesOwnedByBank(bytes32 _securities_id, uint index) constant returns(bytes32) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getBankList(index)); } function getSecuritiesListLength() constant returns(uint) { return(securities_cnt); } function getSecuritiesList(uint index) constant returns(bytes32) { return(securities_list[index]); } //event EventForSecuritiesTransactionPending(bytes32 _txSerNo); event EventForSecuritiesTransactionPending(bytes32 _txSerNo); event EventForSecuritiesTransactionCancelled(bytes32 _txSerNo, int rc, string _reason); //event EventForSecuritiesTransactionError(bytes32 _txSerNo, int rc); //event EventForSecuritiesTransactionMatched(bytes32 _txSerNo1, bytes32 _txSerNo2); event EventForSecuritiesTransactionFinished(bytes32 _txSerNo1, bytes32 _txSerNo2); event EventForSecuritiesTransactionWaitingForPayment(bytes32 _txSerNo1, bytes32 _txSerNo2); event EventForSecuritiesTransactionPaymentError(bytes32 _txSerNo1, bytes32 _txSerNo2, int rc); // 可能為賣方清算行或是買方清算行呼叫,寫code時需要配合Quorum的private transaction的運作模式,privateFor[對方行,央行] // 注意,每筆交易每個在privateFor的node都會執行,寫code時要有這個思維。 function submitInterBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id, bytes32 _to_bank_id, bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id, int _payment, bytes32 _digest) { Transaction memory this_txn; Bank_Account seller = Bank_Account(bankRegistry[_from_bank_id]); Bank_Account buyer = Bank_Account(bankRegistry[_to_bank_id]); if(seller.checkOwnedNode()) { // 賣方跟央行才能檢查,在買方節點無法檢查賣方的帳戶資料,這段code是必須的,否則在共識階段,買方節點上這交易會被cancel // 若Dapp有檢查,則這段程式跑不到,加這段檢查以防萬一 // 若為賣方清算行打進來的交易,則圈存賣方債券戶(DLT) 賣方跟央行才做這段 因為賣方跟央行都看得到賣方的Bank_Account Contract // 在共識階段,買方清算行節點會跳過這段,結果資料會跟賣方節點不同,但因為買方不需要也不能夠知道賣方的帳戶資料,因此這是必要的。 if(bytes1(uint8(uint(_txSerNo) / (2**((31 - 5) * 8)))) == 'S') { if( getCustomerSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id) < _securities_amount) { // 賣方(from)券數持有部位不足 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount,0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 3 ); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; EventForSecuritiesTransactionCancelled(_txSerNo, 3, ""); return; } setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); } } // 須處理買方先打交易 但是賣方券不夠 造成交易變成pending 賣方要打交易將買方節點該交易的狀態設為cancelled // matching transaction 交易比對 if( isTransactionWaitingForMatch[_digest]) { if (msg.sender == transactions[txnDigest_SerNo1[_digest]].msg_sender) { // 同一個msg.sender打相同交易進區塊鍊,設為Pending 因無法判斷是兩筆不同交易或是打錯 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; enShareQueue(_txSerNo); EventForSecuritiesTransactionPending(_txSerNo); return; }else { bytes32 _txSerNo1 = txnDigest_SerNo1[_digest]; setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Waiting4Payment)); // 將前一筆狀態設為Waiting4Payment isTransactionWaitingForMatch[_digest] = false; delete isTransactionWaitingForMatch[_digest]; delete txnDigest_SerNo1[_digest]; // 注意:紀錄圈存額度 // 不管買方或賣方都要記錄圈存數量 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Waiting4Payment, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; if(_payment == 0) { // FOP無款交易,不用到同資 // 更新DLT債券戶資訊 賣方跟央行才做這段 // 在共識階段,買方清算行節點會跳過這段,因此資料會跟賣方節點不同,但因為買方不需要也不能夠知道賣方的帳戶資料,因此這是必要的。 if(seller.checkOwnedNode()) { setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); // 賣方已圈存,不須再增加持有部位 } // 更新DLT債券戶資訊 買方跟央行才做這段 // 在共識階段,賣方清算行節點會跳過這段,因此資料會跟買方節點不同,但因為賣方不需要也不能夠知道買方的帳戶資料,因此這是必要的。 if(buyer.checkOwnedNode()) { setCustomerOwnedSecuritiesAmount(_securities_id, _to_bank_id, _to_customer_id, _securities_amount, true); // 增加買方持有部位 setCustomerOwnedSecuritiesPosition(_securities_id, _to_bank_id, _to_customer_id, _securities_amount, true); } setSecuritiesTransactionState(_txSerNo, uint(TxnState.Finished)); // 將Transaction設為Finished setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished // 移出Queue deShareQueue(_txSerNo); deShareQueue(_txSerNo1); EventForSecuritiesTransactionFinished(_txSerNo, _txSerNo1); }else { EventForSecuritiesTransactionWaitingForPayment(_txSerNo, _txSerNo1); } } }else { isTransactionWaitingForMatch[_digest] = true; // 不管買方或賣方都要記錄圈存數量 txnDigest_SerNo1[_digest] = _txSerNo; this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; enShareQueue(_txSerNo); EventForSecuritiesTransactionPending(_txSerNo); } } // privateFor [央行] (交易只會在清算行本身及央行節點上面執行) function submitIntraBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id, bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id, int _payment, bytes32 _digest) { Transaction memory this_txn; if(_from_customer_id == _to_customer_id) { // Do nothing // 賣方與買方為同一人 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 2); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; //enqueue(_txSerNo); //queued = true; EventForSecuritiesTransactionCancelled(_txSerNo, 2, ""); return; } // 賣方才檢查並圈存, if(bytes1(uint8(uint(_txSerNo) / (2**((31 - 5) * 8)))) == 'S') { if( getCustomerSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id) < _securities_amount) { // 賣方(from)券數持有部位不足 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 3); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; //enqueue(_txSerNo); //queued = true; EventForSecuritiesTransactionCancelled(_txSerNo, 3, ""); return; } //自行圈存賣方債券戶(DLT) setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); } // matching transaction 交易比對 if( isTransactionWaitingForMatch[_digest]) { //Transaction 是 atomic 不用擔心Double Spending的問題 bytes32 _txSerNo1 = txnDigest_SerNo1[_digest]; setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Matched)); isTransactionWaitingForMatch[_digest] = false; delete isTransactionWaitingForMatch[_digest]; delete txnDigest_SerNo1[_digest]; this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Matched, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; // 更新DLT債券戶資訊 setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _to_customer_id, _securities_amount, true); // 賣方已圈存,不須再增加持有部位 //setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _to_customer_id, _securities_amount, true); setSecuritiesTransactionState(_txSerNo, uint(TxnState.Finished)); // 將Transaction設為Finished setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished dePrivateQueue(_txSerNo); dePrivateQueue(_txSerNo1); EventForSecuritiesTransactionFinished(_txSerNo, _txSerNo1); }else { isTransactionWaitingForMatch[_digest] = true; txnDigest_SerNo1[_digest] = _txSerNo; this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; enPrivateQueue(_txSerNo); EventForSecuritiesTransactionPending(_txSerNo); } } // privateFor [央行] (交易只會在清算行本身及央行節點上面執行) // reason 不會存在Trsnactions裡面 但是在傳進來的過程中(Payload) 已經記錄在區塊裡 function submitSetTransactionCancelled(bytes32 _rev_txSerNo, bytes32 _txSerNo, int _rc, string _reason) { Transaction this_txn = transactions[_rev_txSerNo]; // 只有Pending與Waiting4Payment才處理 if( (this_txn.state == TxnState.Pending) || (this_txn.state == TxnState.Waiting4Payment) ) { // End-of-Day 時因為交易沒有發生,要解圈 //if(this_txn.state == TxnState.Waiting4Payment) { int _blocked_amount = this_txn.blocked_amount; bytes32 _securities_id = this_txn.securities_id; bytes32 _from_bank_id = this_txn.from_bank_id; bytes32 _from_customer_id = this_txn.from_customer_id; //買賣方跟央行都做這段,但買方做沒用,只是寫入無意義的別家清算行資料 //if(msg.sender == bankAdmins[_from_bank_id] || msg.sender == owner) { Bank_Account seller = Bank_Account(bankRegistry[_from_bank_id]); if(_rc == 5) { // 只有賣方發的交易才解圈 買方發的交易也會進來 因此用rc 分辨 if(seller.checkOwnedNode() && _blocked_amount > 0) { // 解除圈存 setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _blocked_amount, true); } } //} this_txn.rev_txnSerNo = _txSerNo; this_txn.state = TxnState.Cancelled; this_txn.return_code = _rc; bytes32 _digest = getTransactionDigest(_rev_txSerNo); isTransactionWaitingForMatch[_digest] = false; delete isTransactionWaitingForMatch[_digest]; //setSecuritiesTransactionState(_rev_txSerNo, uint(TxnState.Cancelled)); Transaction _txn = transactions[_txSerNo]; _txn.rev_txnSerNo = _rev_txSerNo; EventForSecuritiesTransactionCancelled(_rev_txSerNo, _rc, _reason); } } // 同資回應後央行節點呼叫,只有央行可發動 function settleInterBankTransaction(bytes32 _txSerNo1, bytes32 _txSerNo2, int _cb_return_code, bool _isNettingSuccess) onlyOwner returns(bool) { Transaction txn1 = transactions[_txSerNo1]; Transaction txn2 = transactions[_txSerNo2]; Bank_Account seller = Bank_Account(bankRegistry[txn1.from_bank_id]); Bank_Account buyer = Bank_Account(bankRegistry[txn1.to_bank_id]); if(_isNettingSuccess == true) { if(seller.checkOwnedNode()) { // 更新DLT債券戶資訊 setCustomerOwnedSecuritiesAmount(txn1.securities_id, txn1.from_bank_id, txn1.from_customer_id, txn1.securities_amount, false); } if(buyer.checkOwnedNode()) { setCustomerOwnedSecuritiesAmount(txn1.securities_id, txn1.to_bank_id, txn1.to_customer_id, txn1.securities_amount, true); // 增加買方持有部位 setCustomerOwnedSecuritiesPosition(txn1.securities_id, txn1.to_bank_id, txn1.to_customer_id, txn1.securities_amount, true); } setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished setSecuritiesTransactionState(_txSerNo2, uint(TxnState.Finished)); // 將Transaction設為Finished deShareQueue(_txSerNo1); deShareQueue(_txSerNo2); EventForSecuritiesTransactionFinished(_txSerNo1, _txSerNo2); }else { if(_cb_return_code == 500) { if(seller.checkOwnedNode()) { // 同資系統錯誤,解除圈存賣方債券戶(DLT) setCustomerOwnedSecuritiesPosition(txn1.securities_id, txn1.from_bank_id, txn1.from_customer_id, txn1.securities_amount, true); } setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Cancelled)); setSecuritiesTransactionState(_txSerNo2, uint(TxnState.Cancelled)); } txn1.return_code = _cb_return_code; // 設定同資錯誤碼 txn2.return_code = _cb_return_code; // 設定同資錯誤碼 EventForSecuritiesTransactionPaymentError(_txSerNo1, _txSerNo2, _cb_return_code); } return _isNettingSuccess; } function setServiceState(uint state) onlyOwner { ServiceState = state; EventForSetServiceState(state); } function getServiceState() returns(uint) { return ServiceState; } function setSecuritiesTransactionState(bytes32 _txSerNo, uint _txn_state) internal { Transaction this_txn = transactions[_txSerNo]; // Initiate, Confirmed, ReadyToSettle, Settled, Finished, Canceled if( _txn_state == uint(TxnState.Pending)) { this_txn.state = TxnState.Pending; }else if( _txn_state == uint(TxnState.Waiting4Payment)) { this_txn.state = TxnState.Waiting4Payment; }else if( _txn_state == uint(TxnState.Matched)) { this_txn.state = TxnState.Matched; }else if( _txn_state == uint(TxnState.Finished)) { this_txn.state = TxnState.Finished; }else if( _txn_state == uint(TxnState.Cancelled)) { this_txn.state = TxnState.Cancelled; } } /* function setSecuritiesTransactionBlockedAmount(bytes32 _txSerNo, int _blocked_amount) internal { Transaction this_txn = transactions[_txSerNo]; this_txn.blocked_amount = _blocked_amount; } */ function enShareQueue(bytes32 _txSerNo) internal { shareQueue.push(_txSerNo); } function deShareQueue(bytes32 _txSerNo) internal { for(uint i=0; i< shareQueue.length; i++) { if(_txSerNo == shareQueue[i]) { delete shareQueue[i]; break; } } } function enPrivateQueue(bytes32 _txSerNo) internal { privateQueue.push(_txSerNo); } function dePrivateQueue(bytes32 _txSerNo) internal { for(uint i=0; i< privateQueue.length; i++) { if(_txSerNo == privateQueue[i]) { delete privateQueue[i]; break; } } } function getShareQueueDepth() constant returns(uint) { return shareQueue.length; } function getPrivateQueueDepth() constant returns(uint) { return privateQueue.length; } function getShareQueueEntry(uint index) constant returns(bytes32) { return shareQueue[index]; } function getPrivateQueueEntry(uint index) constant returns(bytes32) { return privateQueue[index]; } function clearQueue() onlyOwner { // 清除ShareQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的 for (uint i=0; i< shareQueue.length; i++) { delete shareQueue[i]; } shareQueue.length = 0; // 清除PrivateQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的 for (uint j=0; j< privateQueue.length; j++) { delete privateQueue[j]; } privateQueue.length = 0; } function getTransactionListLength() constant returns(uint) { return transactionIdx.length; } function getTransactionList(uint index) constant returns(bytes32) { return transactionIdx[index]; } function getTransactionInfo(bytes32 _txSerNo) constant returns(bytes32, bytes32 , bytes32 , bytes32 , int , bytes32, int, uint) { Transaction this_txn = transactions[_txSerNo]; return(this_txn.from_bank_id, this_txn.from_customer_id, this_txn.to_bank_id, this_txn.to_customer_id, this_txn.securities_amount, this_txn.securities_id, this_txn.payment, this_txn.timestamp ); } function getTransactionReverseTxnSeq(bytes32 _txSerNo) constant returns(bytes32) { Transaction this_txn = transactions[_txSerNo]; return(this_txn.rev_txnSerNo); } function getTransactionDigest(bytes32 _txSerNo) constant returns(bytes32 _digest) { Transaction this_txn = transactions[_txSerNo]; return(this_txn.digest); } function getTransactionState(bytes32 _txSerNo) constant returns(uint, int) { Transaction this_txn = transactions[_txSerNo]; return(uint(this_txn.state), this_txn.return_code); } }
privateFor[央行與被建立的清算行] 可以讓被建立的清算行利用checkOwnedNode傳回true判斷是自己的節點 因為節點不會看到別人的Bank_Account Contractbank.setBankContract(_bank_contract);
function setOwnedNode(bytes32 _bank_id, bool _is_true) onlyOwner { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setOwnedNode(true); EventForSetOwnedNode(_bank_id); }
15,859,483
[ 1, 1152, 1290, 63, 166, 102, 111, 169, 99, 239, 169, 235, 234, 169, 100, 109, 166, 124, 123, 168, 109, 238, 168, 253, 231, 167, 121, 232, 168, 111, 250, 169, 99, 239, 65, 225, 166, 242, 112, 165, 124, 103, 169, 111, 246, 169, 100, 109, 166, 124, 123, 168, 109, 238, 168, 253, 231, 167, 121, 232, 168, 111, 250, 169, 99, 239, 166, 235, 107, 168, 247, 106, 1893, 5460, 329, 907, 166, 229, 116, 166, 254, 257, 3767, 166, 235, 102, 167, 249, 120, 167, 251, 112, 169, 234, 108, 166, 120, 114, 168, 253, 231, 168, 112, 227, 170, 124, 257, 225, 166, 254, 259, 168, 229, 123, 168, 112, 227, 170, 124, 257, 165, 121, 240, 167, 255, 230, 168, 255, 238, 166, 235, 113, 166, 235, 103, 165, 123, 123, 168, 253, 231, 16040, 67, 3032, 13456, 10546, 18, 542, 16040, 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, 444, 5460, 329, 907, 12, 3890, 1578, 389, 10546, 67, 350, 16, 1426, 389, 291, 67, 3767, 13, 1338, 5541, 288, 203, 1377, 25610, 67, 3032, 11218, 273, 25610, 67, 3032, 12, 10546, 4243, 63, 67, 10546, 67, 350, 19226, 203, 1377, 11218, 18, 542, 5460, 329, 907, 12, 3767, 1769, 203, 203, 1377, 2587, 1290, 694, 5460, 329, 907, 24899, 10546, 67, 350, 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 ]
pragma solidity ^0.6.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./cryptoblades.sol"; import "./characters.sol"; import "./weapons.sol"; import "./Promos.sol"; import "./util.sol"; import "./items/RaidTrinket.sol"; import "./items/KeyLootbox.sol"; import "./items/Junk.sol"; contract Raid1 is Initializable, AccessControlUpgradeable { /* Actual raids reimplementation Figured the old contract may have a lot of redundant variables and it's already deployed Maybe the raid interface isn't the way to go Either way it's probably fine to lay out the new one in a single file and compare The idea is to store all participants and raid details using an indexed mapping system And players get to claim their rewards as a derivative of a raid completion seed that a safe verifiable random source will provide (ideally) It may be better to convert the mappings using raidIndex into a struct Need to test gas impact or if stack limits are any different */ using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; bytes32 public constant GAME_ADMIN = keccak256("GAME_ADMIN"); uint8 public constant STATUS_UNSTARTED = 0; uint8 public constant STATUS_STARTED = 1; uint8 public constant STATUS_WON = 2; uint8 public constant STATUS_LOST = 3; uint8 public constant STATUS_PAUSED = 4; // in case of emergency // leaving link 0 empty intentionally uint256 public constant LINK_TRINKET = 1; uint256 public constant LINK_KEYBOX = 2; uint256 public constant LINK_JUNK = 3; uint256 public constant NUMBERPARAMETER_AUTO_DURATION = 1; uint256 public constant NUMBERPARAMETER_AUTO_BOSSPOWER_PERCENT = uint256(keccak256("BOSSPOWER_PERCENT")); CryptoBlades public game; Characters public characters; Weapons public weapons; Promos public promos; struct Raider { address owner; uint256 charID; uint256 wepID; uint24 power; uint24 traitsCWS;//char trait, wep trait, wep statpattern, unused for now } uint64 public staminaCost; uint64 public durabilityCost; int128 public joinCost; uint16 public xpReward; uint256 public raidIndex; // all (first) keys are raidIndex mapping(uint256 => uint8) public raidStatus; mapping(uint256 => uint256) public raidEndTime; mapping(uint256 => uint256) public raidSeed; mapping(uint256 => uint8) public raidBossTrait; mapping(uint256 => uint256) public raidBossPower; mapping(uint256 => uint256) public raidPlayerPower; mapping(uint256 => Raider[]) public raidParticipants; mapping(uint256 => mapping(address => uint256[])) public raidParticipantIndices; mapping(uint256 => mapping(address => bool)) public raidRewardClaimed; // link interface // the idea is to avoid littering the contract with variables for each type of reward mapping(uint256 => address) public links; // parameters to avoid littering the contract with more state vars mapping(uint256 => uint256) public numberParameters; event RaidStarted(uint256 indexed raidIndex, uint8 bossTrait, uint256 bossPower, uint256 endTime); event RaidJoined(uint256 raidIndex, address indexed user, uint256 indexed character, uint256 indexed weapon, uint256 skillPaid); event RaidCompleted(uint256 indexed raidIndex, uint8 outcome, uint256 bossRoll, uint256 playerRoll); // reward specific events for analytics event RewardClaimed(uint256 indexed raidIndex, address indexed user, uint256 characterCount); event RewardedXpBonus(uint256 indexed raidIndex, address indexed user, uint256 indexed charID, uint16 amount); event RewardedDustLB(uint256 indexed raidIndex, address indexed user, uint32 amount); event RewardedDust4B(uint256 indexed raidIndex, address indexed user, uint32 amount); event RewardedDust5B(uint256 indexed raidIndex, address indexed user, uint32 amount); event RewardedWeapon(uint256 indexed raidIndex, address indexed user, uint8 stars, uint256 indexed tokenID); event RewardedJunk(uint256 indexed raidIndex, address indexed user, uint8 stars, uint256 indexed tokenID); event RewardedTrinket(uint256 indexed raidIndex, address indexed user, uint8 stars, uint256 effect, uint256 indexed tokenID); event RewardedKeyBox(uint256 indexed raidIndex, address indexed user, uint256 indexed tokenID); function initialize(address gameContract) public initializer { __AccessControl_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(GAME_ADMIN, msg.sender); game = CryptoBlades(gameContract); characters = Characters(game.characters()); weapons = Weapons(game.weapons()); promos = Promos(game.promos()); staminaCost = 200; // 5 mins each, or 16.666 hours durabilityCost = 20; // 50 mins each, or 16.666 hours joinCost = 0;// free (was going to be 10 USD) xpReward = 128 * 2; // 13 hour 20 min worth of fight xp, but we had double xp active on launch } modifier restricted() { _restricted(); _; } function _restricted() internal view { require(hasRole(GAME_ADMIN, msg.sender), "Not game admin"); } function doRaidAuto() public restricted { uint256 seed = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))); uint256 power = ABDKMath64x64.divu(numberParameters[NUMBERPARAMETER_AUTO_BOSSPOWER_PERCENT],100) .mulu(raidPlayerPower[raidIndex]); uint8 trait = uint8(seed % 4); uint256 duration = numberParameters[NUMBERPARAMETER_AUTO_DURATION]; if(duration == 0) { duration = 480; // 8 hrs } doRaidWithSeed(power, trait, duration, seed); } function doRaid(uint256 bossPower, uint8 bossTrait, uint256 durationMinutes) public restricted { doRaidWithSeed(bossPower, bossTrait, durationMinutes, uint256(keccak256(abi.encodePacked(blockhash(block.number - 1))))); } function doRaidWithSeed(uint256 bossPower, uint8 bossTrait, uint256 durationMinutes, uint256 seed) public restricted { require(raidStatus[raidIndex] != STATUS_PAUSED, "Raid paused"); if(raidStatus[raidIndex] == STATUS_STARTED && raidParticipants[raidIndex].length > 0) { completeRaidWithSeed(seed); } startRaid(bossPower, bossTrait, durationMinutes); } function startRaid(uint256 bossPower, uint8 bossTrait, uint256 durationMinutes) public restricted { raidStatus[raidIndex] = STATUS_STARTED; raidBossPower[raidIndex] = bossPower; raidBossTrait[raidIndex] = bossTrait; uint256 endTime = now + (durationMinutes * 1 minutes); raidEndTime[raidIndex] = endTime; emit RaidStarted(raidIndex, bossTrait, bossPower, endTime); } function joinRaid(uint256 characterID, uint256 weaponID) public { require(characters.canRaid(msg.sender, characterID)); require(weapons.canRaid(msg.sender, weaponID)); /*require(characters.ownerOf(characterID) == msg.sender); require(weapons.ownerOf(weaponID) == msg.sender); require(characters.getStaminaPoints(characterID) > 0, "You cannot join with 0 character stamina"); require(weapons.getDurabilityPoints(weaponID) > 0, "You cannot join with 0 weapon durability");*/ require(raidStatus[raidIndex] == STATUS_STARTED, "Cannot join raid right now!"); require(raidEndTime[raidIndex] > now, "It is too late to join this raid!"); uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { require(raidParticipants[raidIndex][raiderIndices[i]].wepID != weaponID, "This weapon is already used in the raid"); require(raidParticipants[raidIndex][raiderIndices[i]].charID != characterID, "This character is already participating"); } (uint8 charTrait, uint24 basePowerLevel, /*uint64 timestamp*/) = unpackFightData(characters.getFightDataAndDrainStamina( characterID, uint8(staminaCost), true) ); (/*int128 weaponMultTarget*/, int128 weaponMultFight, uint24 weaponBonusPower, /*uint8 weaponTrait*/) = weapons.getFightDataAndDrainDurability(weaponID, charTrait, uint8(durabilityCost), true); uint24 power = getPlayerFinalPower( getPlayerPower(basePowerLevel, weaponMultFight, weaponBonusPower), charTrait, raidBossTrait[raidIndex] ); raidPlayerPower[raidIndex] += power; //uint8 wepStatPattern = weapons.getStatPattern(weaponID); raidParticipantIndices[raidIndex][msg.sender].push(raidParticipants[raidIndex].length); raidParticipants[raidIndex].push(Raider( msg.sender, characterID, weaponID, power, 0//uint24(charTrait) | (uint24(weaponTrait) << 8) | ((uint24(wepStatPattern)) << 16)//traitCWS )); uint256 joinCostPaid = 0; if(joinCost > 0) { joinCostPaid = game.usdToSkill(joinCost); game.payContractTokenOnly(msg.sender, joinCostPaid); } emit RaidJoined(raidIndex, msg.sender, characterID, weaponID, joinCostPaid); } function setRaidStatus(uint256 index, uint8 status) public restricted { // only use if absolutely necessary raidStatus[index] = status; } function completeRaid() public restricted { completeRaidWithSeed(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1))))); } function completeRaidWithSeed(uint256 seed) internal { raidSeed[raidIndex] = seed; raidEndTime[raidIndex] = now; uint256 bossPower = raidBossPower[raidIndex]; // we could also not include bossPower in the roll to have slightly higher chances of failure // with bosspower added to roll ceiling the likelyhood of a win is: playerPower / bossPower uint256 roll = RandomUtil.randomSeededMinMax(0,raidPlayerPower[raidIndex]+bossPower, seed); uint8 outcome = roll >= bossPower ? STATUS_WON : STATUS_LOST; raidStatus[raidIndex] = outcome; if(outcome == STATUS_WON) { // since we pay out exactly one trinket per raid, we might as well do it here Raider memory trinketWinner = raidParticipants[raidIndex][seed % raidParticipants[raidIndex].length]; uint8 trinketStars = getTrinketStarsFromSeed(seed); uint256 trinketEffect = (seed / 100) % 5; uint tokenID = RaidTrinket(links[LINK_TRINKET]).mint( trinketWinner.owner, trinketStars, trinketEffect ); emit RewardedTrinket(raidIndex, trinketWinner.owner, trinketStars, trinketEffect, tokenID); } emit RaidCompleted(raidIndex, outcome, bossPower, roll); raidIndex++; } function getTrinketStarsFromSeed(uint256 seed) private pure returns(uint8 stars) { uint256 roll = seed % 100; if(roll < 1) { return 4; // 5* at 1% } else if(roll < 6) { // 4* at 5% return 3; } else if(roll < 21) { // 3* at 15% return 2; } else if(roll < 56) { // 2* at 35% return 1; } else { return 0; // 1* at 44% } } function unpackFightData(uint96 playerData) public pure returns (uint8 charTrait, uint24 basePowerLevel, uint64 timestamp) { charTrait = uint8(playerData & 0xFF); basePowerLevel = uint24((playerData >> 8) & 0xFFFFFF); timestamp = uint64((playerData >> 32) & 0xFFFFFFFFFFFFFFFF); } function getPlayerPower( uint24 basePower, int128 weaponMultiplier, uint24 bonusPower ) public pure returns(uint24) { return uint24(weaponMultiplier.mulu(basePower) + bonusPower); } function isTraitEffectiveAgainst(uint8 attacker, uint8 defender) public pure returns (bool) { return (((attacker + 1) % 4) == defender); // Thanks to Tourist } function getPlayerFinalPower(uint24 playerPower, uint8 charTrait, uint8 bossTrait) public pure returns(uint24) { if(isTraitEffectiveAgainst(charTrait, bossTrait)) return uint24(ABDKMath64x64.divu(1075,1000).mulu(uint256(playerPower))); return playerPower; } function claimReward(uint256 claimRaidIndex) public { // NOTE: this function is stack limited //claimRaidIndex can act as a version integer if future rewards change bool victory = raidStatus[claimRaidIndex] == STATUS_WON; require(victory || raidStatus[claimRaidIndex] == STATUS_LOST, "Raid not over"); require(raidRewardClaimed[claimRaidIndex][msg.sender] == false, "Already claimed"); uint256[] memory raiderIndices = raidParticipantIndices[claimRaidIndex][msg.sender]; require(raiderIndices.length > 0, "None of your characters participated"); uint256 earlyBonusCutoff = raidParticipants[claimRaidIndex].length/2+1; // first half of players // we grab raider info (power) and give out xp and raid stats for(uint i = 0; i < raiderIndices.length; i++) { uint256 raiderIndex = raiderIndices[i]; Raider memory raider = raidParticipants[claimRaidIndex][raiderIndex]; int128 earlyMultiplier = ABDKMath64x64.fromUInt(1).add( raiderIndex < earlyBonusCutoff ? ABDKMath64x64.divu(1,10).mul( // early bonus, 10% (earlyBonusCutoff-raiderIndex).divu(earlyBonusCutoff) ) : ABDKMath64x64.fromUInt(0) ); if(victory) { distributeRewards( claimRaidIndex, raiderIndex, ABDKMath64x64.divu(earlyMultiplier.mulu(raider.power), raidPlayerPower[claimRaidIndex]/raidParticipants[claimRaidIndex].length) ); } characters.processRaidParticipation(raider.charID, victory, uint16(earlyMultiplier.mulu(xpReward))); } raidRewardClaimed[claimRaidIndex][msg.sender] = true; emit RewardClaimed(claimRaidIndex, msg.sender, raiderIndices.length); } function distributeRewards( uint256 claimRaidIndex, uint256 raiderIndex, int128 comparedToAverage ) private { // at most 2 types of rewards // common: Lb dust, 1-3 star junk, 3 star wep // rare: 4-5b dust, 4-5 star wep, 4-5 star junk, keybox // chances are a bit generous compared to weapon mints because stamina cost equals lost skill // That being said these rates stink if the oracle is 3x lower than real value. uint256 seed = uint256(keccak256(abi.encodePacked(raidSeed[claimRaidIndex], raiderIndex, uint256(msg.sender)))); uint256 commonRoll = RandomUtil.randomSeededMinMax(1, 15 + comparedToAverage.mulu(85), seed); if(commonRoll > 20) { // Expected: ~75% (at least 25% at bottom, 90+% past 65% power) uint mod = seed % 10; if(mod < 2) { // 1 star junk, 2 out of 10 (20%) distributeJunk(msg.sender, claimRaidIndex, 0); } else if(mod < 4) { // 2 star junk, 2 out of 10 (20%) distributeJunk(msg.sender, claimRaidIndex, 1); } else if(mod < 6) { // 2 star weapon, 2 out of 10 (20%) distributeWeapon(msg.sender, claimRaidIndex, seed, 1); } else if(mod == 6) { // 3 star junk, 1 out of 10 (10%) distributeJunk(msg.sender, claimRaidIndex, 2); } else if(mod == 7) { // 1x LB Dust, 1 out of 10 (10%) distributeLBDust(msg.sender, claimRaidIndex, 1); } else if(mod == 8) { // 2x LB Dust, 1 out of 10 (10%) distributeLBDust(msg.sender, claimRaidIndex, 2); } else { // 3 star weapon, 1 out of 10 (10%) distributeWeapon(msg.sender, claimRaidIndex, seed, 2); } } uint256 rareRoll = RandomUtil.randomSeededMinMax(1, 950 + comparedToAverage.mulu(50), seed + 1); if(rareRoll > 950) { // Expected: ~5% (0.72% at bottom, 15% at top, 8.43% middle) uint mod = (seed / 10) % 20; if(mod < 8) { // key box, 8 out of 20 (40%) distributeKeyBox(msg.sender, claimRaidIndex); } else if(mod == 8) { // 5 star sword, 1 out of 20 (5%) distributeWeapon(msg.sender, claimRaidIndex, seed, 4); } else if(mod == 9) { // 5 star junk, 1 out of 20 (5%) distributeJunk(msg.sender, claimRaidIndex, 4); } else if(mod < 14) { // 4 star sword, 4 out of 20 (20%) distributeWeapon(msg.sender, claimRaidIndex, seed, 3); } else if(mod == 14) { // 1x 4B Dust, 1 out of 20 (5%) distribute4BDust(msg.sender, claimRaidIndex, 1); } else if(mod == 15) { // 1x 5B Dust, 1 out of 20 (5%) distribute5BDust(msg.sender, claimRaidIndex, 1); } else { // 4 star junk, 4 out of 20 (20%) distributeJunk(msg.sender, claimRaidIndex, 3); } } uint256 bonusXpRoll = RandomUtil.randomSeededMinMax(1, 2000, seed + 2); // 0.05% per point if(bonusXpRoll <= 100) { // 5% for any bonus xp result if(bonusXpRoll > 50) { // 2.5% for +25% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(25,100).mulu(xpReward))); } else if(bonusXpRoll > 20) { // 1.5% for +150% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(150,100).mulu(xpReward))); } else if(bonusXpRoll > 10) { // 0.5% for +275% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(275,100).mulu(xpReward))); } else if(bonusXpRoll > 4) { // 0.3% for +525% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(525,100).mulu(xpReward))); } else if(bonusXpRoll > 1) { // 0.15% for +1150% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(1150,100).mulu(xpReward))); } else { // 0.05% for +2400% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(2400,100).mulu(xpReward))); } } } function distributeBonusXp(address claimant, uint256 claimRaidIndex, uint256 raiderIndex, uint16 amount) private { uint256 charID = raidParticipants[claimRaidIndex][raiderIndex].charID; characters.gainXp(charID, amount); emit RewardedXpBonus(claimRaidIndex, claimant, charID, amount); } function distributeKeyBox(address claimant, uint256 claimRaidIndex) private { uint tokenID = KeyLootbox(links[LINK_KEYBOX]).mint(claimant); emit RewardedKeyBox(claimRaidIndex, claimant, tokenID); } function distributeJunk(address claimant, uint256 claimRaidIndex, uint8 stars) private { uint tokenID = Junk(links[LINK_JUNK]).mint(claimant, stars); emit RewardedJunk(claimRaidIndex, claimant, stars, tokenID); } function distributeWeapon(address claimant, uint256 claimRaidIndex, uint256 seed, uint8 stars) private { uint tokenID = weapons.mintWeaponWithStars(claimant, stars, seed / 100, 100); emit RewardedWeapon(claimRaidIndex, claimant, stars, tokenID); } function distributeLBDust(address claimant, uint256 claimRaidIndex, uint32 amount) private { weapons.incrementDustSupplies(claimant, amount, 0, 0); emit RewardedDustLB(claimRaidIndex, claimant, amount); } function distribute4BDust(address claimant, uint256 claimRaidIndex, uint32 amount) private { weapons.incrementDustSupplies(claimant, 0, amount, 0); emit RewardedDust4B(claimRaidIndex, claimant, amount); } function distribute5BDust(address claimant, uint256 claimRaidIndex, uint32 amount) private { weapons.incrementDustSupplies(claimant, 0, 0, amount); emit RewardedDust5B(claimRaidIndex, claimant, amount); } function registerLink(address addr, uint256 index) public restricted { links[index] = addr; } function setStaminaPointCost(uint8 points) public restricted { staminaCost = points; } function setDurabilityPointCost(uint8 points) public restricted { durabilityCost = points; } function setJoinCostInCents(uint256 cents) public restricted { joinCost = ABDKMath64x64.divu(cents, 100); } function getJoinCostInSkill() public view returns(uint256) { return game.usdToSkill(joinCost); } function setXpReward(uint16 xp) public restricted { xpReward = xp; } function setNumberParameter(uint256 paramIndex, uint256 value) public restricted { numberParameters[paramIndex] = value; } function getNumberParameter(uint256 paramIndex) public view returns(uint256) { return numberParameters[paramIndex]; } function getRaidStatus(uint256 index) public view returns(uint8) { return raidStatus[index]; } function getRaidEndTime(uint256 index) public view returns(uint256) { return raidEndTime[index]; } function getRaidBossTrait(uint256 index) public view returns(uint8) { return raidBossTrait[index]; } function getRaidBossPower(uint256 index) public view returns(uint256) { return raidBossPower[index]; } function getRaidPlayerPower(uint256 index) public view returns(uint256) { return raidPlayerPower[index]; } function getRaidParticipantCount(uint256 index) public view returns(uint256) { return raidParticipants[index].length; } function getEligibleRewardIndexes(uint256 startIndex, uint256 endIndex) public view returns(uint256[] memory) { uint indexCount = 0; for(uint i = startIndex; i <= endIndex; i++) { if(isEligibleForReward(i)) { indexCount++; } } uint256[] memory result = new uint256[](indexCount); uint currentIndex = 0; for(uint i = startIndex; i <= endIndex; i++) { if(isEligibleForReward(i)) { result[currentIndex++] = i; } } return result; } function isEligibleForReward(uint256 index) public view returns(bool) { uint8 status = raidStatus[index]; return (status == STATUS_WON || status == STATUS_LOST) && raidParticipantIndices[index][msg.sender].length > 0 && raidRewardClaimed[index][msg.sender] == false; } function getParticipatingCharacters() public view returns(uint256[] memory) { uint256[] memory indices = raidParticipantIndices[raidIndex][msg.sender]; uint256[] memory chars = new uint256[](indices.length); for(uint i = 0; i < indices.length; i++) { chars[i] = raidParticipants[raidIndex][indices[i]].charID; } return chars; } function getParticipatingWeapons() public view returns(uint256[] memory) { uint256[] memory indices = raidParticipantIndices[raidIndex][msg.sender]; uint256[] memory weps = new uint256[](indices.length); for(uint i = 0; i < indices.length; i++) { weps[i] = raidParticipants[raidIndex][indices[i]].wepID; } return weps; } function getAccountsRaiderIndexes(uint256 index) public view returns(uint256[] memory){ return raidParticipantIndices[index][msg.sender]; } function getAccountsPower(uint256 index) public view returns(uint256) { uint256 totalAccountPower = 0; uint256[] memory raiderIndexes = getAccountsRaiderIndexes(index); for(uint256 i = 0; i < raiderIndexes.length; i++) { totalAccountPower += raidParticipants[index][raiderIndexes[i]].power; } return totalAccountPower; } function canJoinRaid(uint256 characterID, uint256 weaponID) public view returns(bool) { return isRaidStarted() && haveEnoughEnergy(characterID, weaponID) && !isCharacterRaiding(characterID) && !isWeaponRaiding(weaponID); } function haveEnoughEnergy(uint256 characterID, uint256 weaponID) public view returns(bool) { return characters.getStaminaPoints(characterID) > 0 && weapons.getDurabilityPoints(weaponID) > 0; } function isRaidStarted() public view returns(bool) { return raidStatus[raidIndex] == STATUS_STARTED && raidEndTime[raidIndex] > now; } function isWeaponRaiding(uint256 weaponID) public view returns(bool) { uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { if(raidParticipants[raidIndex][raiderIndices[i]].wepID == weaponID) { return true; } } return false; } function isCharacterRaiding(uint256 characterID) public view returns(bool) { uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { if(raidParticipants[raidIndex][raiderIndices[i]].charID == characterID) { return true; } } return false; } function getLinkAddress(uint256 linkIndex) public view returns (address) { return links[linkIndex]; } function getRaidData() public view returns( uint256 index, uint256 endTime, uint256 raiderCount, uint256 playerPower, uint256 bossPower, uint8 trait, uint8 status, uint256 joinSkill, uint64 stamina, uint64 durability, uint64 xp, uint256 accountPower ) { index = raidIndex; endTime = raidEndTime[raidIndex]; raiderCount = getRaidParticipantCount(raidIndex); playerPower = getRaidPlayerPower(raidIndex); bossPower = getRaidBossPower(raidIndex); trait = getRaidBossTrait(raidIndex); status = getRaidStatus(raidIndex); joinSkill = getJoinCostInSkill(); stamina = staminaCost; durability = durabilityCost; xp = xpReward; accountPower = getAccountsPower(raidIndex); } }
1x LB Dust, 1 out of 10 (10%)
else if(mod == 7) {
1,752,084
[ 1, 21, 92, 511, 38, 463, 641, 16, 404, 596, 434, 1728, 261, 2163, 9, 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 ]
[ 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, 5411, 469, 309, 12, 1711, 422, 2371, 13, 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, -100, -100, -100, -100 ]
./full_match/1/0xf7ceAC9f71b415f683eDfa9D1b9baf479995F91E/sources/PayForMinting.sol
@param dragonWallet The Dragon Wallet string that is receiving payment.
function payForMinting(string calldata dragonWallet) external payable { require(msg.value == costToCustomize || msg.value == costToMint); emit PaidForMinting(dragonWallet, dragonWallet, msg.value == costToCustomize ? 2 : 1); }
17,112,634
[ 1, 15997, 265, 16936, 1021, 28425, 265, 20126, 533, 716, 353, 15847, 5184, 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, 8843, 1290, 49, 474, 310, 12, 1080, 745, 892, 8823, 265, 16936, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 6991, 774, 3802, 554, 747, 1234, 18, 1132, 422, 6991, 774, 49, 474, 1769, 203, 203, 3639, 3626, 453, 20736, 1290, 49, 474, 310, 12, 15997, 265, 16936, 16, 8823, 265, 16936, 16, 1234, 18, 1132, 422, 6991, 774, 3802, 554, 692, 576, 294, 404, 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 ]
// File: hardhat/console.sol pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File: @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/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/Lottery.sol pragma solidity ^0.8.0; contract Lottery is Ownable { //events event JoinEvent(uint256 _length, uint _qty); event DrawEvent(address winner); //uint256 uint256 public MAX_TICKETS = 999; uint256 public PRICE = 5000000000000000000; //the price is 50 stack uint256 public number; //addresses address public TOKEN_ADDRESS; address public WINNER; address[] public TICKETBAG; IERC20 public stackAddress; //bools bool public LOTTO_LIVE; //mappings mapping(address => uint256) public AMOUNT_MAPPING; //constructor constructor(address _stackAddress) public { LOTTO_LIVE = false; stackAddress = IERC20(_stackAddress); } function setNumber(uint _num) public { number = _num; } function checkNotStarted() public view returns (bool) { return LOTTO_LIVE; } function getMax() public view returns (uint256) { return MAX_TICKETS; } function getPrice() public view returns (uint256) { return PRICE; } function startLotto() public onlyOwner () { require(!LOTTO_LIVE); LOTTO_LIVE = true; } function setMaxTickets(uint256 amount) public onlyOwner() { MAX_TICKETS = amount; } function setPrice(uint256 _price) public onlyOwner() { //must set price with 18 decimals PRICE = _price; } //all stack users can buy tickets function buyTickets(uint256 _qty) public { require(LOTTO_LIVE); require(_qty > 0); require(TICKETBAG.length + _qty <= MAX_TICKETS); AMOUNT_MAPPING[msg.sender] = _qty; stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty); for (uint256 i = 0; i < _qty; i++) { TICKETBAG.push(msg.sender); } emit JoinEvent (TICKETBAG.length, _qty); if(TICKETBAG.length == MAX_TICKETS) { endLotto(); } } //roll for a winner function draw() public onlyOwner returns(address){ require(TICKETBAG.length > 0); require(LOTTO_LIVE); uint256 randomNum = uint256(block.timestamp) % uint256(TICKETBAG.length-1); WINNER = TICKETBAG[randomNum]; emit DrawEvent(WINNER); return WINNER; } function getTicketsSold() external view returns(uint256) { return TICKETBAG.length; } //pay out the winner and reset the lottery function endLotto() public onlyOwner returns(address){ require(LOTTO_LIVE); WINNER = draw(); LOTTO_LIVE = false; delete TICKETBAG; return WINNER; } //after lottery function withdrawTokens() external onlyOwner { uint256 tokenSupply = stackAddress.balanceOf(address(this)); stackAddress.transferFrom(address(this), msg.sender, tokenSupply); } }
eventsuint256addressesboolsmappingsconstructor
contract Lottery is Ownable { event JoinEvent(uint256 _length, uint _qty); event DrawEvent(address winner); uint256 public MAX_TICKETS = 999; uint256 public number; address public TOKEN_ADDRESS; address public WINNER; address[] public TICKETBAG; IERC20 public stackAddress; bool public LOTTO_LIVE; mapping(address => uint256) public AMOUNT_MAPPING; constructor(address _stackAddress) public { LOTTO_LIVE = false; stackAddress = IERC20(_stackAddress); } function setNumber(uint _num) public { number = _num; } function checkNotStarted() public view returns (bool) { return LOTTO_LIVE; } function getMax() public view returns (uint256) { return MAX_TICKETS; } function getPrice() public view returns (uint256) { return PRICE; } function startLotto() public onlyOwner () { require(!LOTTO_LIVE); LOTTO_LIVE = true; } function setMaxTickets(uint256 amount) public onlyOwner() { MAX_TICKETS = amount; } function setPrice(uint256 _price) public onlyOwner() { PRICE = _price; } function buyTickets(uint256 _qty) public { require(LOTTO_LIVE); require(_qty > 0); require(TICKETBAG.length + _qty <= MAX_TICKETS); AMOUNT_MAPPING[msg.sender] = _qty; stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty); for (uint256 i = 0; i < _qty; i++) { TICKETBAG.push(msg.sender); } emit JoinEvent (TICKETBAG.length, _qty); if(TICKETBAG.length == MAX_TICKETS) { endLotto(); } } function buyTickets(uint256 _qty) public { require(LOTTO_LIVE); require(_qty > 0); require(TICKETBAG.length + _qty <= MAX_TICKETS); AMOUNT_MAPPING[msg.sender] = _qty; stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty); for (uint256 i = 0; i < _qty; i++) { TICKETBAG.push(msg.sender); } emit JoinEvent (TICKETBAG.length, _qty); if(TICKETBAG.length == MAX_TICKETS) { endLotto(); } } function buyTickets(uint256 _qty) public { require(LOTTO_LIVE); require(_qty > 0); require(TICKETBAG.length + _qty <= MAX_TICKETS); AMOUNT_MAPPING[msg.sender] = _qty; stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty); for (uint256 i = 0; i < _qty; i++) { TICKETBAG.push(msg.sender); } emit JoinEvent (TICKETBAG.length, _qty); if(TICKETBAG.length == MAX_TICKETS) { endLotto(); } } function draw() public onlyOwner returns(address){ require(TICKETBAG.length > 0); require(LOTTO_LIVE); uint256 randomNum = uint256(block.timestamp) % uint256(TICKETBAG.length-1); WINNER = TICKETBAG[randomNum]; emit DrawEvent(WINNER); return WINNER; } function getTicketsSold() external view returns(uint256) { return TICKETBAG.length; } function endLotto() public onlyOwner returns(address){ require(LOTTO_LIVE); WINNER = draw(); LOTTO_LIVE = false; delete TICKETBAG; return WINNER; } function withdrawTokens() external onlyOwner { uint256 tokenSupply = stackAddress.balanceOf(address(this)); stackAddress.transferFrom(address(this), msg.sender, tokenSupply); } }
322,389
[ 1, 5989, 11890, 5034, 13277, 1075, 3528, 16047, 12316, 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, 16351, 511, 352, 387, 93, 353, 14223, 6914, 288, 203, 377, 203, 565, 871, 4214, 1133, 12, 11890, 5034, 389, 2469, 16, 2254, 389, 85, 4098, 1769, 203, 565, 871, 10184, 1133, 12, 2867, 5657, 1224, 1769, 203, 203, 565, 2254, 5034, 1071, 4552, 67, 56, 16656, 1584, 55, 273, 22249, 31, 203, 565, 2254, 5034, 1071, 1300, 31, 203, 565, 1758, 1071, 14275, 67, 15140, 31, 203, 565, 1758, 1071, 678, 25000, 31, 203, 565, 1758, 8526, 1071, 399, 16656, 1584, 38, 1781, 31, 203, 565, 467, 654, 39, 3462, 1071, 2110, 1887, 31, 203, 203, 565, 1426, 1071, 1806, 1470, 51, 67, 2053, 3412, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 432, 5980, 5321, 67, 20450, 31, 203, 203, 203, 565, 3885, 12, 2867, 389, 3772, 1887, 13, 1071, 288, 203, 3639, 1806, 1470, 51, 67, 2053, 3412, 273, 629, 31, 203, 3639, 2110, 1887, 273, 467, 654, 39, 3462, 24899, 3772, 1887, 1769, 203, 565, 289, 203, 565, 445, 444, 1854, 12, 11890, 389, 2107, 13, 1071, 288, 203, 3639, 1300, 273, 389, 2107, 31, 203, 565, 289, 203, 565, 445, 866, 1248, 9217, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1806, 1470, 51, 67, 2053, 3412, 31, 203, 565, 289, 203, 565, 445, 7288, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 4552, 67, 56, 16656, 1584, 55, 31, 203, 565, 289, 203, 565, 445, 25930, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2 ]
//Address: 0x4994e81897a920c0fea235eb8cedeed3c6fff697 //Contract name: SikobaContinuousSale //Balance: 0 Ether //Verification Date: 5/29/2017 //Transacion Count: 123 // CODE STARTS HERE pragma solidity ^0.4.10; // ---------------------------------------------------------------------------- // // Important information // // For details about the Sikoba continuous token sale, and in particular to find // out about risks and limitations, please visit: // // http://www.sikoba.com/www/presale/index.html // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // Owned contract // // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender != newOwner) throw; OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ---------------------------------------------------------------------------- // // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() constant returns (uint256 totalSupply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // ---------------------------------------------------------------------------- // // ERC Token Standard #20 // // ---------------------------------------------------------------------------- contract ERC20Token is Owned, ERC20Interface { uint256 _totalSupply = 0; // ------------------------------------------------------------------------ // 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)) allowed; // ------------------------------------------------------------------------ // Get the total token supply // ------------------------------------------------------------------------ function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // ------------------------------------------------------------------------ // Get the account balance of another account with address _owner // ------------------------------------------------------------------------ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer the balance from owner's account to another account // ------------------------------------------------------------------------ function transfer( address _to, uint256 _amount ) returns (bool success) { if (balances[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. If this function is called again it overwrites the // current allowance with _value. // ------------------------------------------------------------------------ function approve( address _spender, uint256 _amount ) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner's // balance to another account. The owner of the tokens must already // have approve(...)-d this transfer // ------------------------------------------------------------------------ function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount // From a/c has balance && allowed[_from][msg.sender] >= _amount // Transfer approved && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance( address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } // ---------------------------------------------------------------------------- // // Accept funds and mint tokens // // ---------------------------------------------------------------------------- contract SikobaContinuousSale is ERC20Token { // ------------------------------------------------------------------------ // Token information // ------------------------------------------------------------------------ string public constant symbol = "SKO1"; string public constant name = "Sikoba Continuous Sale"; uint8 public constant decimals = 18; // Thursday, 01-Jun-17 00:00:00 UTC uint256 public constant START_DATE = 1496275200; // Tuesday, 31-Oct-17 23:59:59 UTC uint256 public constant END_DATE = 1509494399; // Number of SKO1 units per ETH at beginning and end uint256 public constant START_SKO1_UNITS = 1650; uint256 public constant END_SKO1_UNITS = 1200; // Minimum contribution amount is 0.01 ETH uint256 public constant MIN_CONTRIBUTION = 10**16; // One day soft time limit if max contribution reached uint256 public constant ONE_DAY = 24*60*60; // Max funding and soft end date uint256 public constant MAX_USD_FUNDING = 400000; uint256 public totalUsdFunding; bool public maxUsdFundingReached = false; uint256 public usdPerHundredEth; uint256 public softEndDate = END_DATE; // Ethers contributed and withdrawn uint256 public ethersContributed = 0; // Status variables bool public mintingCompleted = false; bool public fundingPaused = false; // Multiplication factor for extra integer multiplication precision uint256 public constant MULT_FACTOR = 10**18; // ------------------------------------------------------------------------ // Events // ------------------------------------------------------------------------ event UsdRateSet(uint256 _usdPerHundredEth); event TokensBought(address indexed buyer, uint256 ethers, uint256 tokens, uint256 newTotalSupply, uint256 unitsPerEth); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SikobaContinuousSale(uint256 _usdPerHundredEth) { setUsdPerHundredEth(_usdPerHundredEth); } // ------------------------------------------------------------------------ // Owner sets the USD rate per 100 ETH - used to determine the funding cap // If coinmarketcap $131.14 then set 13114 // ------------------------------------------------------------------------ function setUsdPerHundredEth(uint256 _usdPerHundredEth) onlyOwner { usdPerHundredEth = _usdPerHundredEth; UsdRateSet(_usdPerHundredEth); } // ------------------------------------------------------------------------ // Calculate the number of tokens per ETH contributed // Linear (START_DATE, START_SKO1_UNITS) -> (END_DATE, END_SKO1_UNITS) // ------------------------------------------------------------------------ function unitsPerEth() constant returns (uint256) { return unitsPerEthAt(now); } function unitsPerEthAt(uint256 at) constant returns (uint256) { if (at < START_DATE) { return START_SKO1_UNITS * MULT_FACTOR; } else if (at > END_DATE) { return END_SKO1_UNITS * MULT_FACTOR; } else { return START_SKO1_UNITS * MULT_FACTOR - ((START_SKO1_UNITS - END_SKO1_UNITS) * MULT_FACTOR * (at - START_DATE)) / (END_DATE - START_DATE); } } // ------------------------------------------------------------------------ // Buy tokens from the contract // ------------------------------------------------------------------------ function () payable { buyTokens(); } function buyTokens() payable { // Check conditions if (fundingPaused) throw; if (now < START_DATE) throw; if (now > END_DATE) throw; if (now > softEndDate) throw; if (msg.value < MIN_CONTRIBUTION) throw; // Issue tokens uint256 _unitsPerEth = unitsPerEth(); uint256 tokens = msg.value * _unitsPerEth / MULT_FACTOR; _totalSupply += tokens; balances[msg.sender] += tokens; Transfer(0x0, msg.sender, tokens); // Approximative funding in USD totalUsdFunding += msg.value * usdPerHundredEth / 10**20; if (!maxUsdFundingReached && totalUsdFunding > MAX_USD_FUNDING) { softEndDate = now + ONE_DAY; maxUsdFundingReached = true; } ethersContributed += msg.value; TokensBought(msg.sender, msg.value, tokens, _totalSupply, _unitsPerEth); // Send balance to owner if (!owner.send(this.balance)) throw; } // ------------------------------------------------------------------------ // Pause and restart funding // ------------------------------------------------------------------------ function pause() external onlyOwner { fundingPaused = true; } function restart() external onlyOwner { fundingPaused = false; } // ------------------------------------------------------------------------ // Owner can mint tokens for contributions made outside the ETH contributed // to this token contract. This can only occur until mintingCompleted is // true // ------------------------------------------------------------------------ function mint(address participant, uint256 tokens) onlyOwner { if (mintingCompleted) throw; balances[participant] += tokens; _totalSupply += tokens; Transfer(0x0, participant, tokens); } function setMintingCompleted() onlyOwner { mintingCompleted = true; } // ------------------------------------------------------------------------ // Transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token( address tokenAddress, uint256 amount ) onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, amount); } }
------------------------------------------------------------------------ Pause and restart funding ------------------------------------------------------------------------
function pause() external onlyOwner { fundingPaused = true; }
6,368,891
[ 1, 29461, 31357, 471, 7870, 22058, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11722, 1435, 3903, 1338, 5541, 288, 203, 3639, 22058, 28590, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x07445312dB273589dcb0fd2bd57aa815A5Afb8CC/sources/contracts/DPT/DividendPayingToken.sol
* @dev Destroys `amount` tokens from `account`, reducing the total supply. 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"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; magnifiedDividendCorrections[account] = magnifiedDividendCorrections[ account ].add((magnifiedDividendPerShare.mul(amount)).toInt256Safe()); }
16,503,562
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 1375, 4631, 9191, 9299, 2822, 326, 2078, 14467, 18, 29076, 30, 300, 1375, 4631, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 4631, 68, 1297, 1240, 622, 4520, 1375, 8949, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 18305, 628, 326, 3634, 1758, 8863, 203, 3639, 2254, 5034, 2236, 13937, 273, 389, 70, 26488, 63, 4631, 15533, 203, 3639, 2583, 12, 4631, 13937, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 11013, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 70, 26488, 63, 4631, 65, 273, 2236, 13937, 300, 3844, 31, 203, 3639, 289, 203, 3639, 389, 4963, 3088, 1283, 3947, 3844, 31, 203, 203, 3639, 28160, 939, 7244, 26746, 20884, 87, 63, 4631, 65, 273, 28160, 939, 7244, 26746, 20884, 87, 63, 203, 5411, 2236, 203, 3639, 308, 18, 1289, 12443, 4527, 82, 939, 7244, 26746, 2173, 9535, 18, 16411, 12, 8949, 13, 2934, 869, 1702, 5034, 9890, 10663, 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 ]
./partial_match/42/0x14a99c8d0578aA732271552a253E64f18ab4AB92/sources/EtherCollateral.sol
Views Mutative functions Inheritance Libraries Internal references https:docs.synthetix.io/contracts/source/contracts/ethercollateral ========== CONSTANTS ========== Where fees are pooled in sUSD. ========== SETTER STATE VARIABLES ========== The ratio of Collateral to synths issued If updated, all outstanding loans will pay this interest rate in on closure of the loan. Default 5% Minting fee for issuing the synths. Default 50 bips. Maximum amount of sETH that can be issued by the EtherCollateral contract. Default 5000 Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 1ETH = 0.8 sETH Maximum number of loans an account can create If true then any wallet addres can close a loan not just the loan creator. Time when remaining loans can be liquidated ========== STATE VARIABLES ========== The total number of synths issued by the collateral in this contract Total number of loans ever created Total number of open loans Synth loan storage struct
contract EtherCollateral is Owned, Pausable, ReentrancyGuard, MixinResolver, IEtherCollateral { using SafeMath for uint256; using SafeDecimalMath for uint256; uint256 internal constant ONE_THOUSAND = 1e18 * 1000; uint256 internal constant ONE_HUNDRED = 1e18 * 100; address internal constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; uint256 public interestRate = (5 * SafeDecimalMath.unit()) / 100; uint256 public interestPerSecond = interestRate.div(SECONDS_IN_A_YEAR); uint256 public issueFeeRate = (5 * SafeDecimalMath.unit()) / 1000; uint256 public issueLimit = SafeDecimalMath.unit() * 5000; uint256 public minLoanSize = SafeDecimalMath.unit() * 1; uint256 public accountLoanLimit = 50; bool public loanLiquidationOpen = false; uint256 public liquidationDeadline; uint256 public totalIssuedSynths; uint256 public totalLoansCreated; uint256 public totalOpenLoanCount; function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); function freezeRate(bytes32 currencyKey) external; } struct SynthLoanStruct { address account; uint256 collateralAmount; uint256 loanAmount; uint256 timeCreated; uint256 loanID; uint256 timeClosed; } bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_SYNTHSETH = "SynthsETH"; bytes32 private constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 private constant CONTRACT_DEPOT = "Depot"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; mapping(address => SynthLoanStruct[]) public accountsSynthLoans; mapping(address => uint256) public accountOpenLoanCounter; constructor(address _owner, address _resolver) public Owned(_owner) Pausable() MixinResolver(_resolver) { } function setCollateralizationRatio(uint256 ratio) external onlyOwner { require(ratio <= ONE_THOUSAND, "Too high"); require(ratio >= ONE_HUNDRED, "Too low"); collateralizationRatio = ratio; emit CollateralizationRatioUpdated(ratio); } function setInterestRate(uint256 _interestRate) external onlyOwner { require(_interestRate > SECONDS_IN_A_YEAR, "Interest rate cannot be less that the SECONDS_IN_A_YEAR"); require(_interestRate <= SafeDecimalMath.unit(), "Interest cannot be more than 100% APR"); interestRate = _interestRate; interestPerSecond = _interestRate.div(SECONDS_IN_A_YEAR); emit InterestRateUpdated(interestRate); } function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner { issueFeeRate = _issueFeeRate; emit IssueFeeRateUpdated(issueFeeRate); } function setIssueLimit(uint256 _issueLimit) external onlyOwner { issueLimit = _issueLimit; emit IssueLimitUpdated(issueLimit); } function setMinLoanSize(uint256 _minLoanSize) external onlyOwner { minLoanSize = _minLoanSize; emit MinLoanSizeUpdated(minLoanSize); } function setAccountLoanLimit(uint256 _loanLimit) external onlyOwner { uint256 HARD_CAP = 1000; require(_loanLimit < HARD_CAP, "Owner cannot set higher than HARD_CAP"); accountLoanLimit = _loanLimit; emit AccountLoanLimitUpdated(accountLoanLimit); } function setLoanLiquidationOpen(bool _loanLiquidationOpen) external onlyOwner { require(now > liquidationDeadline, "Before liquidation deadline"); loanLiquidationOpen = _loanLiquidationOpen; emit LoanLiquidationOpenUpdated(loanLiquidationOpen); } function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](5); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_SYNTHSETH; addresses[2] = CONTRACT_SYNTHSUSD; addresses[3] = CONTRACT_DEPOT; addresses[4] = CONTRACT_EXRATES; } function getContractInfo() external view returns ( uint256 _collateralizationRatio, uint256 _issuanceRatio, uint256 _interestRate, uint256 _interestPerSecond, uint256 _issueFeeRate, uint256 _issueLimit, uint256 _minLoanSize, uint256 _totalIssuedSynths, uint256 _totalLoansCreated, uint256 _totalOpenLoanCount, uint256 _ethBalance, uint256 _liquidationDeadline, bool _loanLiquidationOpen ) { _collateralizationRatio = collateralizationRatio; _issuanceRatio = issuanceRatio(); _interestRate = interestRate; _interestPerSecond = interestPerSecond; _issueFeeRate = issueFeeRate; _issueLimit = issueLimit; _minLoanSize = minLoanSize; _totalIssuedSynths = totalIssuedSynths; _totalLoansCreated = totalLoansCreated; _totalOpenLoanCount = totalOpenLoanCount; _ethBalance = address(this).balance; _liquidationDeadline = liquidationDeadline; _loanLiquidationOpen = loanLiquidationOpen; } function issuanceRatio() public view returns (uint256) { return ONE_HUNDRED.divideDecimalRound(collateralizationRatio); } function loanAmountFromCollateral(uint256 collateralAmount) public view returns (uint256) { return collateralAmount.multiplyDecimal(issuanceRatio()); } function collateralAmountForLoan(uint256 loanAmount) external view returns (uint256) { return loanAmount.multiplyDecimal(collateralizationRatio.divideDecimalRound(ONE_HUNDRED)); } function currentInterestOnLoan(address _account, uint256 _loanID) external view returns (uint256) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); uint256 loanLifeSpan = _loanLifeSpan(synthLoan); return accruedInterestOnLoan(synthLoan.loanAmount, loanLifeSpan); } function accruedInterestOnLoan(uint256 _loanAmount, uint256 _seconds) public view returns (uint256 interestAmount) { interestAmount = _loanAmount.multiplyDecimalRound(interestPerSecond.mul(_seconds)); } function calculateMintingFee(address _account, uint256 _loanID) external view returns (uint256) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); return _calculateMintingFee(synthLoan); } function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } } function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } } function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } } uint256[] memory _result = new uint256[](_counter); function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } } return _result; function getLoan(address _account, uint256 _loanID) external view returns ( address account, uint256 collateralAmount, uint256 loanAmount, uint256 timeCreated, uint256 loanID, uint256 timeClosed, uint256 interest, uint256 totalFees ) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); account = synthLoan.account; collateralAmount = synthLoan.collateralAmount; loanAmount = synthLoan.loanAmount; timeCreated = synthLoan.timeCreated; loanID = synthLoan.loanID; timeClosed = synthLoan.timeClosed; interest = accruedInterestOnLoan(synthLoan.loanAmount, _loanLifeSpan(synthLoan)); totalFees = interest.add(_calculateMintingFee(synthLoan)); } function loanLifeSpan(address _account, uint256 _loanID) external view returns (uint256 loanLifeSpanResult) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); loanLifeSpanResult = _loanLifeSpan(synthLoan); } function openLoan() external payable notPaused nonReentrant sETHRateNotInvalid returns (uint256 loanID) { systemStatus().requireIssuanceActive(); require(msg.value >= minLoanSize, "Not enough ETH to create this loan. Please see the minLoanSize"); require(loanLiquidationOpen == false, "Loans are now being liquidated"); require(accountsSynthLoans[msg.sender].length < accountLoanLimit, "Each account is limted to 50 loans"); uint256 loanAmount = loanAmountFromCollateral(msg.value); require(totalIssuedSynths.add(loanAmount) < issueLimit, "Loan Amount exceeds the supply cap."); loanID = _incrementTotalLoansCounter(); SynthLoanStruct memory synthLoan = SynthLoanStruct({ account: msg.sender, collateralAmount: msg.value, loanAmount: loanAmount, timeCreated: now, loanID: loanID, timeClosed: 0 }); } function openLoan() external payable notPaused nonReentrant sETHRateNotInvalid returns (uint256 loanID) { systemStatus().requireIssuanceActive(); require(msg.value >= minLoanSize, "Not enough ETH to create this loan. Please see the minLoanSize"); require(loanLiquidationOpen == false, "Loans are now being liquidated"); require(accountsSynthLoans[msg.sender].length < accountLoanLimit, "Each account is limted to 50 loans"); uint256 loanAmount = loanAmountFromCollateral(msg.value); require(totalIssuedSynths.add(loanAmount) < issueLimit, "Loan Amount exceeds the supply cap."); loanID = _incrementTotalLoansCounter(); SynthLoanStruct memory synthLoan = SynthLoanStruct({ account: msg.sender, collateralAmount: msg.value, loanAmount: loanAmount, timeCreated: now, loanID: loanID, timeClosed: 0 }); } accountsSynthLoans[msg.sender].push(synthLoan); totalIssuedSynths = totalIssuedSynths.add(loanAmount); synthsETH().issue(msg.sender, loanAmount); emit LoanCreated(msg.sender, loanID, loanAmount); function closeLoan(uint256 loanID) external nonReentrant sETHRateNotInvalid { _closeLoan(msg.sender, loanID); } function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant sETHRateNotInvalid { require(loanLiquidationOpen, "Liquidation is not open"); _closeLoan(_loanCreatorsAddress, _loanID); emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender); } function _closeLoan(address account, uint256 loanID) private { systemStatus().requireIssuanceActive(); SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); require(synthLoan.loanID > 0, "Loan does not exist"); require(synthLoan.timeClosed == 0, "Loan already closed"); require( IERC20(address(synthsETH())).balanceOf(msg.sender) >= synthLoan.loanAmount, "You do not have the required Synth balance to close this loan." ); _recordLoanClosure(synthLoan); totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount); uint256 interestAmount = accruedInterestOnLoan(synthLoan.loanAmount, _loanLifeSpan(synthLoan)); uint256 mintingFee = _calculateMintingFee(synthLoan); uint256 totalFeeETH = interestAmount.add(mintingFee); synthsETH().burn(msg.sender, synthLoan.loanAmount); require( IERC20(address(synthsUSD())).balanceOf(address(depot())) >= depot().synthsReceivedForEther(totalFeeETH), "The sUSD Depot does not have enough sUSD to buy for fees" ); depot().exchangeEtherForSynths.value(totalFeeETH)(); IERC20(address(synthsUSD())).transfer(FEE_ADDRESS, IERC20(address(synthsUSD())).balanceOf(address(this))); address(msg.sender).transfer(synthLoan.collateralAmount.sub(totalFeeETH)); emit LoanClosed(account, loanID, totalFeeETH); } function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { return synthLoans[i]; } } } function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { return synthLoans[i]; } } } function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { return synthLoans[i]; } } } function _recordLoanClosure(SynthLoanStruct memory synthLoan) private { SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { synthLoans[i].timeClosed = now; } } } function _recordLoanClosure(SynthLoanStruct memory synthLoan) private { SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { synthLoans[i].timeClosed = now; } } } function _recordLoanClosure(SynthLoanStruct memory synthLoan) private { SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { synthLoans[i].timeClosed = now; } } } totalOpenLoanCount = totalOpenLoanCount.sub(1); function _incrementTotalLoansCounter() private returns (uint256) { totalOpenLoanCount = totalOpenLoanCount.add(1); totalLoansCreated = totalLoansCreated.add(1); return totalLoansCreated; } function _calculateMintingFee(SynthLoanStruct memory synthLoan) private view returns (uint256 mintingFee) { mintingFee = synthLoan.loanAmount.multiplyDecimalRound(issueFeeRate); } function _loanLifeSpan(SynthLoanStruct memory synthLoan) private view returns (uint256 loanLifeSpanResult) { bool loanClosed = synthLoan.timeClosed > 0; loanLifeSpanResult = loanClosed ? synthLoan.timeClosed.sub(synthLoan.timeCreated) : now.sub(synthLoan.timeCreated); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function synthsETH() internal view returns (ISynth) { return ISynth(requireAndGetAddress(CONTRACT_SYNTHSETH)); } function synthsUSD() internal view returns (ISynth) { return ISynth(requireAndGetAddress(CONTRACT_SYNTHSUSD)); } function depot() internal view returns (IDepot) { return IDepot(requireAndGetAddress(CONTRACT_DEPOT)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } modifier sETHRateNotInvalid() { require(!exchangeRates().rateIsInvalid("sETH"), "Blocked as sETH rate is invalid"); _; } event CollateralizationRatioUpdated(uint256 ratio); event InterestRateUpdated(uint256 interestRate); event IssueFeeRateUpdated(uint256 issueFeeRate); event IssueLimitUpdated(uint256 issueLimit); event MinLoanSizeUpdated(uint256 minLoanSize); event AccountLoanLimitUpdated(uint256 loanLimit); event LoanLiquidationOpenUpdated(bool loanLiquidationOpen); event LoanCreated(address indexed account, uint256 loanID, uint256 amount); event LoanClosed(address indexed account, uint256 loanID, uint256 feesPaid); event LoanLiquidated(address indexed account, uint256 loanID, address liquidator); }
3,405,247
[ 1, 9959, 14138, 1535, 4186, 25953, 1359, 10560, 11042, 3186, 5351, 2333, 30, 8532, 18, 11982, 451, 278, 697, 18, 1594, 19, 16351, 87, 19, 3168, 19, 16351, 87, 19, 2437, 12910, 2045, 287, 422, 1432, 24023, 55, 422, 1432, 12177, 1656, 281, 854, 25007, 316, 272, 3378, 40, 18, 422, 1432, 3174, 11976, 7442, 22965, 55, 422, 1432, 1021, 7169, 434, 17596, 2045, 287, 358, 6194, 451, 87, 16865, 971, 3526, 16, 777, 20974, 437, 634, 903, 8843, 333, 16513, 4993, 316, 603, 7213, 434, 326, 28183, 18, 2989, 1381, 9, 490, 474, 310, 14036, 364, 3385, 22370, 326, 6194, 451, 87, 18, 2989, 6437, 324, 7146, 18, 18848, 3844, 434, 272, 1584, 44, 716, 848, 506, 16865, 635, 326, 512, 1136, 13535, 2045, 287, 6835, 18, 2989, 20190, 23456, 3844, 434, 512, 2455, 358, 752, 28183, 5309, 310, 314, 17802, 310, 471, 16189, 24550, 18, 5444, 404, 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, 16351, 512, 1136, 13535, 2045, 287, 353, 14223, 11748, 16, 21800, 16665, 16, 868, 8230, 12514, 16709, 16, 490, 10131, 4301, 16, 10897, 1136, 13535, 2045, 287, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 5749, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 15623, 67, 2455, 21667, 4307, 273, 404, 73, 2643, 380, 4336, 31, 203, 565, 2254, 5034, 2713, 5381, 15623, 67, 44, 5240, 5879, 273, 404, 73, 2643, 380, 2130, 31, 203, 203, 203, 565, 1758, 2713, 5381, 478, 9383, 67, 15140, 273, 374, 26947, 41, 8090, 41, 21386, 74, 41, 73, 14667, 74, 9383, 8090, 41, 74, 41, 73, 14667, 74, 9383, 14667, 8090, 41, 8090, 73, 42, 31, 203, 203, 203, 203, 565, 2254, 5034, 1071, 16513, 4727, 273, 261, 25, 380, 14060, 5749, 10477, 18, 4873, 10756, 342, 2130, 31, 203, 565, 2254, 5034, 1071, 16513, 2173, 8211, 273, 16513, 4727, 18, 2892, 12, 11609, 67, 706, 67, 37, 67, 15137, 1769, 203, 203, 565, 2254, 5034, 1071, 5672, 14667, 4727, 273, 261, 25, 380, 14060, 5749, 10477, 18, 4873, 10756, 342, 4336, 31, 203, 203, 565, 2254, 5034, 1071, 5672, 3039, 273, 14060, 5749, 10477, 18, 4873, 1435, 380, 20190, 31, 203, 203, 565, 2254, 5034, 1071, 1131, 1504, 304, 1225, 273, 14060, 5749, 10477, 18, 4873, 1435, 380, 404, 31, 203, 203, 565, 2254, 5034, 1071, 2236, 1504, 304, 3039, 273, 6437, 31, 203, 203, 565, 1426, 1071, 28183, 48, 18988, 350, 367, 3678, 273, 629, 2 ]
./partial_match/1/0x98fdeC842DbDB4c11Bd4c57B1683F105472fcd69/sources/CyberGorillaBabies.sol
@notice The address which is allowed to breed Cyber Gorillas. @notice Base URI pointing to CyberGorillaBabies metadata. @notice Returns true if the requested gorilla baby has the genesis trait, false otherwise.
{ baseURI = initialBaseURI; }
15,995,936
[ 1, 1986, 1758, 1492, 353, 2935, 358, 324, 15656, 22337, 744, 611, 280, 737, 345, 18, 225, 3360, 3699, 17022, 358, 22337, 744, 43, 280, 10745, 38, 378, 606, 1982, 18, 225, 2860, 638, 309, 326, 3764, 10330, 10745, 324, 24383, 711, 326, 21906, 13517, 16, 629, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 288, 203, 3639, 1026, 3098, 273, 2172, 2171, 3098, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /** * @authors: [@fnanni-0] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] * @tools: [] */ /** * @title Implementation of the Evidence Standard with Moderated Submissions */ pragma solidity ^0.8; // TODO: standard interfaces should be placed in a separated repo (?) import "../arbitration/IArbitrable.sol"; import "../arbitration/IArbitrator.sol"; import "./IMetaEvidence.sol"; import "../libraries/CappedMath.sol"; contract ModeratedEvidenceModule is IArbitrable, IMetaEvidence { using CappedMath for uint256; uint256 public constant AMOUNT_OF_CHOICES = 2; uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. /** Enums */ enum Party { None, Submitter, Moderator } /* Structs */ struct EvidenceData { address payable submitter; // Address that submitted the evidence. bool disputed; // Whether the evidence submission has been disputed. Party ruling; // Final status of the evidence. If not disputed, can be changed by opening another round of moderation. uint256 disputeID; // The ID of the dispute. An evidence submission can only be disputed once. Moderation[] moderations; // Stores the data of each moderation event. An evidence submission can be moderated many times. } struct Moderation { uint256[3] paidFees; // Tracks the fees paid by each side in this moderation. uint256 feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint256[3]) contributions; // Maps contributors to their contributions for each side. bool closed; // Moderation happens over a bounded period of time after which it is considered closed. If so, a new moderation round should be opened. Party currentWinner; // The current winner of this moderation round. uint256 bondDeadline; // The deadline until which the loser party can stake to overturn the current status. uint256 arbitratorDataID; // The index of the relevant arbitratorData struct. } struct ArbitratorData { uint256 metaEvidenceUpdates; // The meta evidence to be used in disputes. bytes arbitratorExtraData; // Extra data for the arbitrator. } /* Storage */ mapping(bytes32 => EvidenceData) evidences; // Maps the evidence ID to its data. evidences[evidenceID]. mapping(uint256 => bytes32) public disputeIDtoEvidenceID; // One-to-one relationship between the dispute and the evidence. ArbitratorData[] public arbitratorDataList; // Stores the arbitrator data of the contract. Updated each time the data is changed. IArbitrator public immutable arbitrator; // The trusted arbitrator to resolve potential disputes. If it needs to be changed, a new contract can be deployed. address public governor; // The address that can make governance changes to the parameters of the contract. uint256 public bondTimeout; // The time in seconds during which the last moderation status can be challenged. uint256 public totalCostMultiplier; // Multiplier of arbitration fees that must be ultimately paid as fee stake. In basis points. uint256 public initialDepositMultiplier; // Multiplier of arbitration fees that must be paid as initial stake for submitting evidence. In basis points. /* Modifiers */ modifier onlyGovernor() { require(msg.sender == governor, "The caller must be the governor"); _; } /* Events */ /** @dev Indicate that a party has to pay a fee or would otherwise be considered as losing. * @param _evidenceID The ID of the evidence being moderated. * @param _currentWinner The party who is currently winning. */ event ModerationStatusChanged(bytes32 indexed _evidenceID, Party _currentWinner); /** @dev Constructor. * @param _arbitrator The trusted arbitrator to resolve potential disputes. * @param _governor The trusted governor of the contract. * @param _totalCostMultiplier Multiplier of arbitration fees that must be ultimately paid as fee stake. In basis points. * @param _initialDepositMultiplier Multiplier of arbitration fees that must be paid as initial stake for submitting evidence. In basis points. * @param _bondTimeout The time in seconds during which the last moderation status can be challenged. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _metaEvidence The URI of the meta evidence object for evidence submissions requests. */ constructor( IArbitrator _arbitrator, address _governor, uint256 _totalCostMultiplier, uint256 _initialDepositMultiplier, uint256 _bondTimeout, bytes memory _arbitratorExtraData, string memory _metaEvidence ) { arbitrator = _arbitrator; governor = _governor; totalCostMultiplier = _totalCostMultiplier; // For example 15000, which would provide a 100% reward to the dispute winner. initialDepositMultiplier = _initialDepositMultiplier; // For example 63, which equals 1/16. bondTimeout = _bondTimeout; // For example 24 hs. ArbitratorData storage arbitratorData = arbitratorDataList.push(); arbitratorData.arbitratorExtraData = _arbitratorExtraData; emit MetaEvidence(0, _metaEvidence); } /** @dev Change the governor of the contract. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the proportion of arbitration fees that must be paid as fee stake by parties when there is no winner or loser (e.g. when the arbitrator refused to rule). * @param _initialDepositMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeInitialDepositMultiplier(uint256 _initialDepositMultiplier) external onlyGovernor { initialDepositMultiplier = _initialDepositMultiplier; } /** @dev Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round. * @param _totalCostMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeTotalCostMultiplier(uint256 _totalCostMultiplier) external onlyGovernor { totalCostMultiplier = _totalCostMultiplier; } /** @dev Change the the time window within which evidence submissions and removals can be contested. * Ongoing moderations will start using the latest bondTimeout available after calling moderate() again. * @param _bondTimeout Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeBondTimeout(uint256 _bondTimeout) external onlyGovernor { bondTimeout = _bondTimeout; } /** @dev Update the meta evidence used for disputes. * @param _newMetaEvidence The meta evidence to be used for future registration request disputes. */ function changeMetaEvidence(string calldata _newMetaEvidence) external onlyGovernor { ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1]; uint256 newMetaEvidenceUpdates = arbitratorData.metaEvidenceUpdates + 1; arbitratorDataList.push( ArbitratorData({ metaEvidenceUpdates: newMetaEvidenceUpdates, arbitratorExtraData: arbitratorData.arbitratorExtraData }) ); emit MetaEvidence(newMetaEvidenceUpdates, _newMetaEvidence); } /** @dev Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal period and not reenter. * @param _arbitratorExtraData The extra data used by the new arbitrator. */ function changeArbitratorExtraData(bytes calldata _arbitratorExtraData) external onlyGovernor { ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1]; arbitratorDataList.push( ArbitratorData({ metaEvidenceUpdates: arbitratorData.metaEvidenceUpdates, arbitratorExtraData: _arbitratorExtraData }) ); } /** @dev Submits evidence. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. It's the submitter responsability to submit the right evidence group ID. * @param _evidence IPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'. */ function submitEvidence(uint256 _evidenceGroupID, string calldata _evidence) external payable { // Optimization opportunity: map evidenceID to an incremental index that can be safely assumed to be less than a small uint. bytes32 evidenceID = keccak256(abi.encodePacked(_evidenceGroupID, _evidence)); EvidenceData storage evidenceData = evidences[evidenceID]; require(evidenceData.submitter == address(0x0), "Evidence already submitted."); evidenceData.submitter = payable(msg.sender); ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1]; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData); uint256 totalCost = arbitrationCost.mulCap(totalCostMultiplier) / MULTIPLIER_DIVISOR; uint256 depositRequired = totalCost.mulCap(initialDepositMultiplier) / MULTIPLIER_DIVISOR; Moderation storage moderation = evidenceData.moderations.push(); // Overpaying is allowed. contribute(moderation, Party.Submitter, payable(msg.sender), msg.value, totalCost); require(moderation.paidFees[uint256(Party.Submitter)] >= depositRequired, "Insufficient funding."); moderation.bondDeadline = block.timestamp + bondTimeout; moderation.currentWinner = Party.Submitter; moderation.arbitratorDataID = arbitratorDataList.length - 1; // When evidence is submitted for a foreign arbitrable, the arbitrator field of Evidence is ignored. emit Evidence(arbitrator, _evidenceGroupID, msg.sender, _evidence); } /** @dev Moderates an evidence submission. Requires the contester to at least double the accumulated stake of the oposing party. * Optimization opportunity: use `bytes calldata args` and compress _evidenceID and _side (only for optimistic rollups). * @param _evidenceID Unique identifier of the evidence submission. * @param _side The side to contribute to. */ function moderate(bytes32 _evidenceID, Party _side) external payable { EvidenceData storage evidenceData = evidences[_evidenceID]; require(evidenceData.submitter != address(0x0), "Evidence does not exist."); require(!evidenceData.disputed, "Evidence already disputed."); require(_side != Party.None, "Invalid side."); Moderation storage moderation = evidenceData.moderations[evidenceData.moderations.length - 1]; if (moderation.closed) { // Start another round of moderation. moderation = evidenceData.moderations.push(); moderation.arbitratorDataID = arbitratorDataList.length - 1; } require(_side != moderation.currentWinner, "Only the current loser can fund."); require( block.timestamp < moderation.bondDeadline || moderation.bondDeadline == 0, "Moderation market is closed." ); ArbitratorData storage arbitratorData = arbitratorDataList[moderation.arbitratorDataID]; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData); uint256 totalCost = arbitrationCost.mulCap(totalCostMultiplier) / MULTIPLIER_DIVISOR; uint256 opposition = 3 - uint256(_side); uint256 depositRequired = moderation.paidFees[opposition] * 2; if (depositRequired == 0) { depositRequired = totalCost.mulCap(initialDepositMultiplier) / MULTIPLIER_DIVISOR; } else if (depositRequired > totalCost) { depositRequired = totalCost; } // Overpaying is allowed. contribute(moderation, _side, payable(msg.sender), msg.value, totalCost); require(moderation.paidFees[uint256(_side)] >= depositRequired, "Insufficient funding."); if (moderation.paidFees[uint256(_side)] >= totalCost && moderation.paidFees[opposition] >= totalCost) { moderation.feeRewards = moderation.feeRewards - arbitrationCost; evidenceData.disputeID = arbitrator.createDispute{value: arbitrationCost}( AMOUNT_OF_CHOICES, arbitratorData.arbitratorExtraData ); disputeIDtoEvidenceID[evidenceData.disputeID] = _evidenceID; emit Dispute(arbitrator, evidenceData.disputeID, arbitratorData.metaEvidenceUpdates, uint256(_evidenceID)); evidenceData.disputed = true; moderation.bondDeadline = 0; moderation.currentWinner = Party.None; } else { moderation.bondDeadline = block.timestamp + bondTimeout; moderation.currentWinner = _side; } emit ModerationStatusChanged(_evidenceID, moderation.currentWinner); } /** @dev Resolves a moderation event once the timeout has passed. * @param _evidenceID Unique identifier of the evidence submission. */ function resolveModerationMarket(bytes32 _evidenceID) external { // Moderation market resolutions are not final. // Evidence can be reported/accepted again in the future. // Only an arbitrator's ruling after a dispute is final. EvidenceData storage evidenceData = evidences[_evidenceID]; Moderation storage moderation = evidenceData.moderations[evidenceData.moderations.length - 1]; require(!evidenceData.disputed, "Evidence already disputed."); require(block.timestamp > moderation.bondDeadline, "Moderation still ongoing."); moderation.closed = true; evidenceData.ruling = moderation.currentWinner; } /** @dev Make a fee contribution. * @param _moderation The moderation to contribute to. * @param _side The side to contribute to. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. * @return The amount of fees contributed. */ function contribute( Moderation storage _moderation, Party _side, address payable _contributor, uint256 _amount, uint256 _totalRequired ) internal returns (uint256) { uint256 contribution; uint256 remainingETH; uint256 requiredAmount = _totalRequired.subCap(_moderation.paidFees[uint256(_side)]); (contribution, remainingETH) = calculateContribution(_amount, requiredAmount); _moderation.contributions[_contributor][uint256(_side)] += contribution; _moderation.paidFees[uint256(_side)] += contribution; _moderation.feeRewards += contribution; if (remainingETH != 0) _contributor.send(remainingETH); return contribution; } /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint256 _available, uint256 _requiredAmount) internal pure returns (uint256 taken, uint256 remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Withdraws contributions of moderations. Reimburses contributions if the appeal was not fully funded. * If the appeal was fully funded, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * Optimization opportunity: use `bytes calldata args` and compress _evidenceID and _moderationID (only for optimistic rollups). * @param _beneficiary The address that made contributions. * @param _evidenceID The ID of the associated evidence submission. * @param _moderationID The ID of the moderatino occurence. */ function withdrawFeesAndRewards( address payable _beneficiary, bytes32 _evidenceID, uint256 _moderationID ) external returns (uint256 reward) { EvidenceData storage evidenceData = evidences[_evidenceID]; Moderation storage moderation = evidenceData.moderations[_moderationID]; require(moderation.closed, "Moderation must be closed."); uint256[3] storage contributionTo = moderation.contributions[_beneficiary]; if (evidenceData.ruling == Party.None) { // Reimburse unspent fees proportionally if there is no winner and loser. uint256 totalFeesPaid = moderation.paidFees[uint256(Party.Submitter)] + moderation.paidFees[uint256(Party.Moderator)]; uint256 totalBeneficiaryContributions = contributionTo[uint256(Party.Submitter)] + contributionTo[uint256(Party.Moderator)]; reward = totalFeesPaid > 0 ? (totalBeneficiaryContributions * moderation.feeRewards) / totalFeesPaid : 0; } else { // Reward the winner. uint256 paidFees = moderation.paidFees[uint256(evidenceData.ruling)]; reward = paidFees > 0 ? (contributionTo[uint256(evidenceData.ruling)] * moderation.feeRewards) / paidFees : 0; } contributionTo[uint256(Party.Submitter)] = 0; contributionTo[uint256(Party.Moderator)] = 0; _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Give a ruling for a dispute. Must be called by the arbitrator to enforce the final ruling. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint256 _disputeID, uint256 _ruling) public override { bytes32 evidenceID = disputeIDtoEvidenceID[_disputeID]; EvidenceData storage evidenceData = evidences[evidenceID]; Moderation storage moderation = evidenceData.moderations[evidenceData.moderations.length - 1]; require( evidenceData.disputed && !moderation.closed && msg.sender == address(arbitrator) && _ruling <= AMOUNT_OF_CHOICES, "Ruling can't be processed." ); evidenceData.ruling = Party(_ruling); moderation.closed = true; emit Ruling(arbitrator, _disputeID, _ruling); } // **************************** // // * Constant getters * // // **************************** // /** @dev Gets the number of moderation events of the specific evidence submission. * @param _evidenceID The ID of the evidence submission. * @return The number of moderations. */ function getNumberOfModerations(bytes32 _evidenceID) external view returns (uint256) { EvidenceData storage evidenceData = evidences[_evidenceID]; return evidenceData.moderations.length; } /** @dev Gets the contributions made by a party for a given moderation. * @param _evidenceID The ID of the evidence submission. * @param _moderationID The ID of the moderation occurence. * @param _contributor The address of the contributor. * @return contributions The contributions. */ function getContributions( bytes32 _evidenceID, uint256 _moderationID, address _contributor ) external view returns (uint256[3] memory contributions) { EvidenceData storage evidenceData = evidences[_evidenceID]; Moderation storage moderation = evidenceData.moderations[_moderationID]; contributions = moderation.contributions[_contributor]; } /** @dev Gets the information of a moderation event. * @param _evidenceID The ID of the evidence submission. * @param _moderationID The ID of the moderation occurence. * @return paidFees currentWinner feeRewards The moderation information. */ function getModerationInfo(bytes32 _evidenceID, uint256 _moderationID) external view returns ( uint256[3] memory paidFees, Party currentWinner, uint256 feeRewards ) { EvidenceData storage evidenceData = evidences[_evidenceID]; Moderation storage moderation = evidenceData.moderations[_moderationID]; return (moderation.paidFees, moderation.currentWinner, moderation.feeRewards); } /** @dev Gets the last arbitrator data index, which is used for current new submissions. * @return The last arbitrator data index. */ function getCurrentArbitratorIndex() external view returns (uint256) { return arbitratorDataList.length - 1; } }
* @dev Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round. @param _totalCostMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points./
function changeTotalCostMultiplier(uint256 _totalCostMultiplier) external onlyGovernor { totalCostMultiplier = _totalCostMultiplier; }
6,368,767
[ 1, 3043, 326, 23279, 434, 10056, 7034, 1656, 281, 716, 1297, 506, 30591, 487, 14036, 384, 911, 635, 326, 5657, 1224, 434, 326, 2416, 3643, 18, 282, 389, 4963, 8018, 23365, 5991, 5742, 434, 10056, 7034, 1656, 281, 716, 1297, 506, 30591, 487, 14036, 384, 911, 18, 657, 10853, 3143, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 5269, 8018, 23365, 12, 11890, 5034, 389, 4963, 8018, 23365, 13, 3903, 1338, 43, 1643, 29561, 288, 203, 3639, 2078, 8018, 23365, 273, 389, 4963, 8018, 23365, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 // author: Rahul Saxena | Github, Twitter: @saxenism /* Functions to implement: 1. function enlistItem() 2. function sellItem() 3. function changePriceForItem() Lower Priority 4. function handleCancelRequestForItem() 5. function getCurrentStateForItem() */ pragma solidity >=0.8.0 <0.9.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract TokenizedShop { address public shopOwner; uint256 public itemID; struct ShopItem { string shopItemName; string shopItemDescription; string shopItemImage; uint256 shopItemPrice; uint256 shopItemQuantity; uint256 shopItemID; } mapping(uint256 => ShopItem) public shopItems; ShopItem[] public shopItemsArray; constructor() { shopOwner = tx.origin; } modifier onlyShopOwner() { require(tx.origin == shopOwner, "Function can only be called by the shopOwner"); _; } function enlistItem(string memory name, string memory description, string memory image, uint256 price, uint256 quantity) public returns (uint256) { ShopItem memory item; item.shopItemName = name; item.shopItemDescription = description; item.shopItemImage = image; item.shopItemPrice = price; item.shopItemQuantity = quantity; item.shopItemID = itemID; shopItems[itemID] = item; return (itemID++); } function displayItemByID(uint256 id) public view returns(ShopItem memory) { return shopItems[id]; } function displayAllItems() public returns(ShopItem[] memory) { if(shopItemsArray.length != itemID) { for(uint256 i = shopItemsArray.length; i < itemID; i++) { shopItemsArray.push(shopItems[i]); } } return shopItemsArray; } function sellItem(uint256 id) payable public returns(bool) { require(id < itemID, "ID out of bounds"); uint256 amountInUSD = shopItems[id].shopItemPrice; uint256 ratioOfPrices = uint256(getDerivedPrice()); uint256 priceInMatic = ratioOfPrices * amountInUSD; require(msg.value >= priceInMatic, "Amount transferred is insufficient"); if(msg.value > priceInMatic) { uint256 amountToReturn = msg.value - priceInMatic; payable(msg.sender).transfer(amountToReturn); } --shopItems[id].shopItemQuantity; return true; } function changePriceForItem(uint256 id, uint256 newPrice) public returns (ShopItem memory) { shopItems[id].shopItemPrice = newPrice; return shopItems[id]; } function getShopOwner() public view returns(address) { return shopOwner; } function getDerivedPrice() public view returns (int256) { address _base = 0x572dDec9087154dC5dfBB1546Bb62713147e0Ab0; // USDC/USD Polygon Mumbai Oracle Address address _quote = 0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada; // MATIC/USD Polygon Mumbai Oracle Address uint8 _decimals = 18; // Decimal precision of Matic require(_decimals > uint8(0) && _decimals <= uint8(18), "Invalid _decimals"); int256 decimals = int256(10 ** uint256(_decimals)); ( , int256 basePrice, , , ) = AggregatorV3Interface(_base).latestRoundData(); uint8 baseDecimals = AggregatorV3Interface(_base).decimals(); basePrice = scalePrice(basePrice, baseDecimals, _decimals); ( , int256 quotePrice, , , ) = AggregatorV3Interface(_quote).latestRoundData(); uint8 quoteDecimals = AggregatorV3Interface(_quote).decimals(); quotePrice = scalePrice(quotePrice, quoteDecimals, _decimals); return basePrice * decimals / quotePrice; } function scalePrice(int256 _price, uint8 _priceDecimals, uint8 _decimals) internal pure returns (int256) { if (_priceDecimals < _decimals) { return _price * int256(10 ** uint256(_decimals - _priceDecimals)); } else if (_priceDecimals > _decimals) { return _price / int256(10 ** uint256(_priceDecimals - _decimals)); } return _price; } function contractBalance() public view returns (uint256) { return address(this).balance; } function sendMatic(address payable gareeb) external { uint256 contractAmount = address(this).balance; gareeb.transfer(contractAmount); } }
MATIC/USD Polygon Mumbai Oracle Address
address _quote = 0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada;
14,049,740
[ 1, 49, 11781, 19, 3378, 40, 12681, 490, 3592, 10658, 28544, 5267, 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, 1758, 389, 6889, 273, 374, 7669, 20, 40, 25, 73, 23, 2290, 6334, 1639, 6260, 41, 29, 42, 5540, 24, 9676, 20, 69, 23, 70, 9383, 69, 42, 4630, 20, 1639, 3247, 1871, 69, 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 ]
./partial_match/7700/0xb9a907A0c5160FaA86d0B942dc5fd4a3d3051d89/sources/contracts/CypherSkulls.sol
get all active games
function getActiveGames() public view returns(ActiveGame[] memory){ return activeGames; }
3,508,017
[ 1, 588, 777, 2695, 28422, 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, 225, 445, 11960, 43, 753, 1435, 1071, 1476, 1135, 12, 3896, 12496, 8526, 3778, 15329, 203, 4202, 327, 2695, 43, 753, 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, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // File: contracts/Bankroll.sol interface Bankroll { //Customer functions /// @dev Stores ETH funds for customer function credit(address _customerAddress, uint256 amount) external returns (uint256); /// @dev Debits address by an amount function debit(address _customerAddress, uint256 amount) external returns (uint256); /// @dev Withraws balance for address; returns amount sent function withdraw(address _customerAddress) external returns (uint256); /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) external view returns (uint256); /// @dev Stats of any single address function statsOf(address _customerAddress) external view returns (uint256[8]); // System functions // @dev Deposit funds function deposit() external payable; // @dev Deposit on behalf of an address; it is not a credit function depositBy(address _customerAddress) external payable; // @dev Distribute house profit function houseProfit(uint256 amount) external; /// @dev Get all the ETH stored in contract minus credits to customers function netEthereumBalance() external view returns (uint256); /// @dev Get all the ETH stored in contract function totalEthereumBalance() external view returns (uint256); } // File: contracts/P4RTYRelay.sol /* * Visit: https://p4rty.io * Discord: https://discord.gg/7y3DHYF */ interface P4RTYRelay { /** * @dev Will relay to internal implementation * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function relay(address beneficiary, uint256 tokenAmount) external; } // File: contracts/SessionQueue.sol /// A FIFO queue for storing addresses contract SessionQueue { mapping(uint256 => address) private queue; uint256 private first = 1; uint256 private last = 0; /// @dev Push into queue function enqueue(address data) internal { last += 1; queue[last] = data; } /// @dev Returns true if the queue has elements in it function available() internal view returns (bool) { return last >= first; } /// @dev Returns the size of the queue function depth() internal view returns (uint256) { return last - first + 1; } /// @dev Pops from the head of the queue function dequeue() internal returns (address data) { require(last >= first); // non-empty queue data = queue[first]; delete queue[first]; first += 1; } /// @dev Returns the head of the queue without a pop function peek() internal view returns (address data) { require(last >= first); // non-empty queue data = queue[first]; } } // 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'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/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. */ 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; } } // File: openzeppelin-solidity/contracts/ownership/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } // File: contracts/P6.sol // solhint-disable-line /* * Visit: https://p4rty.io * Discord: https://discord.gg/7y3DHYF * Stable + DIVIS: Whale and Minow Friendly * Fees balanced for maximum dividends for ALL * Active depositors rewarded with P4RTY tokens * 50% of ETH value in earned P4RTY token rewards * 2% of dividends fund a gaming bankroll; gaming profits are paid back into P6 * P4RTYRelay is notified on all dividend producing transactions * Smart Launch phase which is anti-whale & anti-snipe * * P6 * The worry free way to earn A TON OF ETH & P4RTY reward tokens * * -> What? * The first Ethereum Bonded Pure Dividend Token: * [✓] The only dividend printing press that is part of the P4RTY Entertainment Network * [✓] Earn ERC20 P4RTY tokens on all ETH deposit activities * [✓] 3% P6 Faucet for free P6 / P4RTY * [✓] Auto-Reinvests * [✓] 10% exchange fees on buys and sells * [✓] 100 tokens to activate faucet * * -> How? * To replay or use the faucet the contract must be fully launched * To sell or transfer you need to be vested (maximum of 3 days) after a reinvest */ contract P6 is Whitelist, SessionQueue { /*================================= = MODIFIERS = =================================*/ /// @dev Only people with tokens modifier onlyTokenHolders { require(myTokens() > 0); _; } /// @dev Only people with profits modifier onlyDivis { require(myDividends(true) > 0); _; } /// @dev Only invested; If participating in prelaunch have to buy tokens modifier invested { require(stats[msg.sender].invested > 0, "Must buy tokens once to withdraw"); _; } /// @dev After every reinvest features are protected by a cooloff to vest funds modifier cooledOff { require(msg.sender == owner && !contractIsLaunched || now - bot[msg.sender].coolOff > coolOffPeriod); _; } /// @dev The faucet has a rewardPeriod modifier teamPlayer { require(msg.sender == owner || now - lastReward[msg.sender] > rewardProcessingPeriod, "No spamming"); _; } /// @dev Functions only available after launch modifier launched { require(contractIsLaunched || msg.sender == owner, "Contract not lauched"); _; } /*============================== = EVENTS = ==============================*/ event onLog( string heading, address caller, address subj, uint val ); event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onCommunityReward( address indexed sourceAddress, address indexed destinationAddress, uint256 ethereumEarned ); event onReinvestmentProxy( address indexed customerAddress, address indexed destinationAddress, uint256 ethereumReinvested ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onDeposit( address indexed customerAddress, uint256 ethereumDeposited ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ /// @dev 10% dividends for token purchase uint256 internal entryFee_ = 10; /// @dev 1% dividends for token transfer uint256 internal transferFee_ = 1; /// @dev 10% dividends for token selling uint256 internal exitFee_ = 10; /// @dev 3% of entryFee_ is given to faucet /// traditional referral mechanism repurposed as a many to many faucet /// powers auto reinvest uint256 internal referralFee_ = 30; /// @dev 20% of entryFee/exit fee is given to Bankroll uint256 internal maintenanceFee_ = 20; address internal maintenanceAddress; //Advanced Config uint256 constant internal bankrollThreshold = 0.5 ether; uint256 constant internal botThreshold = 0.01 ether; uint256 constant rewardProcessingPeriod = 6 hours; uint256 constant reapPeriod = 7 days; uint256 public maxProcessingCap = 10; uint256 public coolOffPeriod = 3 days; uint256 public launchETHMaximum = 20 ether; bool public contractIsLaunched = false; uint public lastReaped; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; /// @dev proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; /*================================= = DATASETS = ================================*/ // bookkeeping for autoreinvest struct Bot { bool active; bool queued; uint256 lastBlock; uint256 coolOff; } // Onchain Stats!!! struct Stats { uint invested; uint reinvested; uint withdrawn; uint rewarded; uint contributed; uint transferredTokens; uint receivedTokens; uint xInvested; uint xReinvested; uint xRewarded; uint xContributed; uint xWithdrawn; uint xTransferredTokens; uint xReceivedTokens; } // amount of shares for each address (scaled number) mapping(address => uint256) internal lastReward; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => Bot) internal bot; mapping(address => Stats) internal stats; //on chain referral tracking mapping(address => address) public referrals; uint256 internal tokenSupply_; uint256 internal profitPerShare_; P4RTYRelay public relay; Bankroll public bankroll; bool internal bankrollEnabled = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor(address relayAddress) public { relay = P4RTYRelay(relayAddress); updateMaintenanceAddress(msg.sender); } //Maintenance Functions /// @dev Minted P4RTY tokens are sent to the maintenance address function updateMaintenanceAddress(address maintenance) onlyOwner public { maintenanceAddress = maintenance; } /// @dev Update the bankroll; 2% of dividends go to the bankroll function updateBankrollAddress(address bankrollAddress) onlyOwner public { bankroll = Bankroll(bankrollAddress); } /// @dev The cap determines the amount of addresses processed when a user runs the faucet function updateProcessingCap(uint cap) onlyOwner public { require(cap >= 5 && cap <= 15, "Capacity set outside of policy range"); maxProcessingCap = cap; } /// @dev Updates the coolOff period where reinvest must vest function updateCoolOffPeriod(uint coolOff) onlyOwner public { require(coolOff >= 5 minutes && coolOff <= 3 days); coolOffPeriod = coolOff; } /// @dev Opens the contract for public use outside of the launch phase function launchContract() onlyOwner public { contractIsLaunched = true; } //Bot Functions /* Activates the bot and queues if necessary; else removes */ function activateBot(bool auto) public { bot[msg.sender].active = auto; //Spam protection for customerAddress if (bot[msg.sender].active) { if (!bot[msg.sender].queued) { bot[msg.sender].queued = true; enqueue(msg.sender); } } } /* Returns if the sender has the reinvestment not enabled */ function botEnabled() public view returns (bool){ return bot[msg.sender].active; } function fundBankRoll(uint256 amount) internal { bankroll.deposit.value(amount)(); } /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) function buyFor(address _customerAddress) onlyWhitelisted public payable returns (uint256) { return purchaseTokens(_customerAddress, msg.value); } /// @dev Converts all incoming ethereum to tokens for the caller function buy() public payable returns (uint256) { if (contractIsLaunched){ //ETH sent during prelaunch needs to be processed if(stats[msg.sender].invested == 0 && referralBalance_[msg.sender] > 0){ reinvestFor(msg.sender); } return purchaseTokens(msg.sender, msg.value); } else { //Just deposit funds return deposit(); } } function deposit() internal returns (uint256) { require(msg.value > 0); //Just add to the referrals for sidelined ETH referralBalance_[msg.sender] = SafeMath.add(referralBalance_[msg.sender], msg.value); require(referralBalance_[msg.sender] <= launchETHMaximum, "Exceeded investment cap"); emit onDeposit(msg.sender, msg.value); return 0; } /** * @dev Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.sender, msg.value); } /// @dev Converts all of caller's dividends to tokens. function reinvest() onlyDivis launched public { reinvestFor(msg.sender); } /// @dev Allows owner to reinvest on behalf of a supporter function investSupporter(address _customerAddress) public onlyOwner { require(!contractIsLaunched, "Contract already opened"); reinvestFor(_customerAddress); } /// @dev Internal utility method for reinvesting function reinvestFor(address _customerAddress) internal { // fetch dividends uint256 _dividends = totalDividends(_customerAddress, false); // retrieve ref. bonus later in the code payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _dividends); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); //Stats stats[_customerAddress].reinvested = SafeMath.add(stats[_customerAddress].reinvested, _dividends); stats[_customerAddress].xReinvested += 1; //Refresh the coolOff bot[_customerAddress].coolOff = now; } /// @dev Withdraws all of the callers earnings. function withdraw() onlyDivis invested public { withdrawFor(msg.sender); } /// @dev Utility function for withdrawing earnings function withdrawFor(address _customerAddress) internal { // setup data uint256 _dividends = totalDividends(_customerAddress, false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); //stats stats[_customerAddress].withdrawn = SafeMath.add(stats[_customerAddress].withdrawn, _dividends); stats[_customerAddress].xWithdrawn += 1; // fire event emit onWithdraw(_customerAddress, _dividends); } /// @dev Liquifies tokens to ethereum. function sell(uint256 _amountOfTokens) onlyTokenHolders cooledOff public { address _customerAddress = msg.sender; //Selling deactivates auto reinvest bot[_customerAddress].active = false; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends, maintenanceFee_), 100); //maintenance and referral come out of the exitfee uint256 _dividends = SafeMath.sub(_undividedDividends, _maintenance); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _undividedDividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; //Apply maintenance fee to the bankroll fundBankRoll(_maintenance); // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); //GO!!! Bankroll Bot GO!!! brbReinvest(_customerAddress); } //@dev Bankroll Bot can only transfer 10% of funds during a reapPeriod //Its funds will always be locked because it always reinvests function reap(address _toAddress) public onlyOwner { require(now - lastReaped > reapPeriod, "Reap not available, too soon"); lastReaped = now; transferTokens(owner, _toAddress, SafeMath.div(balanceOf(owner), 10)); } /** * @dev Transfer tokens from the caller to a new holder. * Remember, there's a 1% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders cooledOff external returns (bool){ address _customerAddress = msg.sender; return transferTokens(_customerAddress, _toAddress, _amountOfTokens); } /// @dev Utility function for transfering tokens function transferTokens(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns (bool){ // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if (totalDividends(_customerAddress,true) > 0) { withdrawFor(_customerAddress); } // liquify a percentage of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event emit Transfer(_customerAddress, _toAddress, _taxedTokens); //Stats stats[_customerAddress].xTransferredTokens += 1; stats[_customerAddress].transferredTokens += _amountOfTokens; stats[_toAddress].receivedTokens += _taxedTokens; stats[_toAddress].xReceivedTokens += 1; // ERC20 return true; } /*===================================== = HELPERS AND CALCULATORS = =====================================*/ /** * @dev Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint256) { return address(this).balance; } /// @dev Retrieve the total token supply. function totalSupply() public view returns (uint256) { return tokenSupply_; } /// @dev Retrieve the tokens owned by the caller. function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { return totalDividends(msg.sender, _includeReferralBonus); } function totalDividends(address _customerAddress, bool _includeReferralBonus) internal view returns (uint256) { return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /// @dev Stats of any single address function statsOf(address _customerAddress) public view returns (uint256[14]){ Stats memory s = stats[_customerAddress]; uint256[14] memory statArray = [s.invested, s.withdrawn, s.rewarded, s.contributed, s.transferredTokens, s.receivedTokens, s.xInvested, s.xRewarded, s.xContributed, s.xWithdrawn, s.xTransferredTokens, s.xReceivedTokens, s.reinvested, s.xReinvested]; return statArray; } /// @dev Retrieve the dividend balance of any single address. function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /// @dev Return the sell price of 1 individual token. function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, exitFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Return the buy price of 1 individual token. function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, entryFee_); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /// @dev Internal function to actually purchase the tokens. function purchaseTokens(address _customerAddress, uint256 _incomingEthereum) internal returns (uint256) { // data setup address _referredBy = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends, maintenanceFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, referralFee_), 100); //maintenance and referral come out of the buyin uint256 _dividends = SafeMath.sub(_undividedDividends, SafeMath.add(_referralBonus, _maintenance)); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; uint256 _tokenAllocation = SafeMath.div(_incomingEthereum, 2); // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); //Apply maintenance fee to bankroll fundBankRoll(_maintenance); // is the user referred by a masternode? if ( // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); //Stats stats[_referredBy].rewarded = SafeMath.add(stats[_referredBy].rewarded, _referralBonus); stats[_referredBy].xRewarded += 1; stats[_customerAddress].contributed = SafeMath.add(stats[_customerAddress].contributed, _referralBonus); stats[_customerAddress].xContributed += 1; //It pays to play emit onCommunityReward(_customerAddress, _referredBy, _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / tokenSupply_); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really i know you think you do but you don't int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; //Notifying the relay is simple and should represent the total economic activity which is the _incomingEthereum //Every player is a customer and mints their own tokens when the buy or reinvest, relay P4RTY 50/50 relay.relay(maintenanceAddress, _tokenAllocation); relay.relay(_customerAddress, _tokenAllocation); // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); //Stats stats[_customerAddress].invested = SafeMath.add(stats[_customerAddress].invested, _incomingEthereum); stats[_customerAddress].xInvested += 1; //GO!!! Bankroll Bot GO!!! brbReinvest(_customerAddress); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + (((tokenPriceIncremental_) ** 2) * (tokenSupply_ ** 2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } /// @dev Returns true if the tokens are fully vested after a reinvest function isVested() public view returns (bool) { return now - bot[msg.sender].coolOff > coolOffPeriod; } /* Is end user eligible to process rewards? */ function rewardAvailable() public view returns (bool){ return available() && now - lastReward[msg.sender] > rewardProcessingPeriod && tokenBalanceLedger_[msg.sender] >= stakingRequirement; } /// @dev Returns timer info used for the vesting and the faucet function timerInfo() public view returns (uint, uint[2], uint[2]){ return (now, [bot[msg.sender].coolOff, coolOffPeriod], [lastReward[msg.sender], rewardProcessingPeriod]); } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // // BankRollBot Functions // //Reinvest on all buys and sells function brbReinvest(address _customerAddress) internal { if (_customerAddress != owner && bankrollEnabled) { if (totalDividends(owner, true) > bankrollThreshold) { reinvestFor(owner); } } } /* Can only be run once per day from the caller avoid bots Minimum of 100 P6 Minimum of 5 P4RTY + amount minted based on dividends processed in 24 hour period */ function processRewards() public teamPlayer launched { require(tokenBalanceLedger_[msg.sender] >= stakingRequirement, "Must meet staking requirement"); uint256 count = 0; address _customer; while (available() && count < maxProcessingCap) { //If this queue has already been processed in this block exit without altering the queue _customer = peek(); if (bot[_customer].lastBlock == block.number){ break; } //Pop dequeue(); //Update tracking bot[_customer].lastBlock = block.number; bot[_customer].queued = false; //User could have deactivated while still being queued if (bot[_customer].active) { //Reinvest divs; be gas efficient if (totalDividends(_customer, true) > botThreshold) { //No bankroll reinvest when processing the queue bankrollEnabled = false; reinvestFor(_customer); bankrollEnabled = true; } enqueue(_customer); bot[_customer].queued = true; } count++; } lastReward[msg.sender] = now; reinvestFor(msg.sender); } }
Notifying the relay is simple and should represent the total economic activity which is the _incomingEthereumEvery player is a customer and mints their own tokens when the buy or reinvest, relay P4RTY 50/50
relay.relay(maintenanceAddress, _tokenAllocation);
5,388,121
[ 1, 9168, 310, 326, 18874, 353, 4143, 471, 1410, 2406, 326, 2078, 425, 591, 24721, 5728, 1492, 353, 326, 389, 31033, 41, 18664, 379, 21465, 7291, 353, 279, 6666, 471, 312, 28142, 3675, 4953, 2430, 1347, 326, 30143, 578, 283, 5768, 395, 16, 18874, 453, 24, 54, 5538, 6437, 19, 3361, 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, 3639, 18874, 18, 2878, 528, 12, 29715, 1887, 16, 389, 2316, 17353, 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 ]
///////////////////////////////////////////////////////////////////////////////////// //version 3.0.0 //Author: Taurus, Samuel Pritchett //Copyright: [email protected] // //update from 2.1 -> 3.0, keep alignment with the project version v3.0, which is a stable release version. /////////////////////////////////////////////////////////////////////////////////////// //NOTE: //This design uses account address as the identifier, meaning each address could only have one req/prov associated. //When submit new or update existing req/prov, previous record are overwriten. //Each address could only have one req or prov, not at same time. //TODO: add conflict detection of the address. Check whether existing req or prov from your address is 'not complete',(being proccessed). //TODO: Aug.2019, add a hard-reset function. Totally remove one request or stop provider from the pool // , no matter their status (being processed or pending), because sometimes, one will stuck in the pool. //////////////////////////////////////////////////////////////////////////////////// pragma solidity >=0.5.1; pragma experimental ABIEncoderV2; //enable returning self-defined type, used in helper return provider and request //do not disable, provider is returned for debuging reason. contract bcaiReputation { mapping (address => reputation) public ratings; //user address -> reputation struct struct reputation{ uint128 numRatings; uint128 avgRating; uint128[5] lastFive; bool newUser; } function addRating (address user, uint128 rating) internal { if(ratings[user].numRatings != 0){ ratings[user].avgRating = (rating + (ratings[user].numRatings * ratings[user].avgRating)) / (ratings[user].numRatings + 1); ratings[user].numRatings++; for(uint8 i = 4; i != 0; i--){//shift the array so we can add newest rating ratings[user].lastFive[i] = ratings[user].lastFive[i - 1]; } ratings[user].lastFive[0] = rating; if(ratings[user].numRatings == 5){ ratings[user].newUser = false; } } else {//this is their first rating, simpler logic ratings[user].avgRating = rating; ratings[user].lastFive[0] = rating; ratings[user].numRatings++; } } function getNumRatings (address user) public view returns(uint128){ return ratings[user].numRatings; } function getAvgRating (address user) public view returns(uint128){ return ratings[user].avgRating; } function getLastFive (address user) public view returns(uint128[5] memory) { return ratings[user].lastFive; } } contract TaskContract is bcaiReputation{ uint256 price = 10000000000000000; // 10000000000000000 Wei = 0.01 ETH mapping (address => Provider) public providerList; //provAddr => provider struct mapping (address => Request) public requestList; //reqAddr => request struct struct Request { uint256 blockNumber; //record the time of submission address payable provider; //record the provider assigned to this request uint256 deposit; //the amount he put down for a deposit uint256 price; //the amount of wei provider is owed for the work (set to price for now) bytes dataID; //dataID used to fetch the off-chain data, interact with ipfs bytes resultID; //dataID to fetch the off-chain result, via ipfs address validator; //validators' addr, update when assigned the task to validators bool signature; //true or false array, update only when validator submit result bool isValid; //the final flag byte status; //one byte indicating the status: 0: 'pending', 1:'providing', 2: 'validating', 3: 'complete' } struct Provider { uint256 blockNumber; //record the time of submission bool available; //if ready to be assigned } //should try best to reduce type of events in order to remove unnecessary confusion. -> reuse events with same format //no need seperate events for each type, just put whatever info passed in bytes info event IPFSInfo (address payable reqAddr, bytes info, bytes extra); event SystemInfo (address payable reqAddr, bytes info); //systemInfo is only informative, not trigger anything. event PairingInfo (address payable reqAddr, address payable provAddr, bytes info); //NOTE: [by TaoLu] extra here are actually dataID, which can also be accessed via reqAddr. // extra may not be necessary but it makes easier of app to handle info. This retains the tradeoff of gas cost and easyness. event PairingInfoLong (address payable reqAddr, address payable provAddr, bytes info, bytes extra); //Pools stores the address of req or prov, thus indicate the stages. address payable[] providerPool; //provAddr only when more providers > req, or empty address payable[] pendingPool; //reqAddr only when more requests > prov, or empty address payable[] providingPool; //reqAddr address payable[] validatingPool; //reqAddr ///////////////////////////////////////////////////////////////////////////////////// // Function called to become a provider. Add address on List, and Pool if not instantly assigned. // TIPS on gas cost: don't create local copy and write back, modify the storage directly. // gas cost 165K without event / 167K with event / 92K overwrite function startProviding() public returns (bool) { if(providerList[msg.sender].blockNumber == 0){ //if this is new providerList[msg.sender].blockNumber = block.number; providerList[msg.sender].available = true; providerPool.push(msg.sender); emit SystemInfo (msg.sender, "Provider Added"); return true; } // else { //this address has been recorded before // return updateProvider(maxTime, maxTarget, minPrice); //this could be an update // } } // Stop a provider. Must be sent from the provider address or it will be failed. function stopProviding() public returns (bool) { // If the sender is currently an active provider if (providerList[msg.sender].available == true){ //can only stop available provider delete providerList[msg.sender]; //delete from List emit SystemInfo(msg.sender, 'Provider Stopped'); return ArrayPop(providerPool, msg.sender); //delete from Pool } else{ emit SystemInfo(msg.sender, 'Provider Unable to Stop'); return false; } } //update a provider, you must know the provAddr and must sent from right addr // function updateProvider(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) { // if(providerList[msg.sender].available == true){ //can only modify available provider // providerList[msg.sender].blockNumber = block.number; // providerList[msg.sender].maxTime = maxTime; // providerList[msg.sender].maxTarget = maxTarget; // providerList[msg.sender].minPrice = minPrice; // emit SystemInfo(msg.sender,'Provider Updated'); // return true; // } // else{ // emit SystemInfo(msg.sender, 'Provider Unable to Update'); // return false; // } // } // Send a request from user to blockchain. Assumes price is including the cost for verification // NOTE: use bytes memory as argument will increase the gas cost, one alternative will be uint type, may consifer in future. function startRequest(bytes memory dataID) public payable returns (bool) { require(msg.value >= price, 'Not enough ether'); if(requestList[msg.sender].blockNumber == 0){ //never submitted before //register on List requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].provider = address(0); requestList[msg.sender].validator = address(0); requestList[msg.sender].deposit = msg.value; //how much ether was sent to contract by the user, their "deposit" requestList[msg.sender].price = price; //set to price here, in future will need to be calculated and set later requestList[msg.sender].dataID = dataID; requestList[msg.sender].status = '0'; //pending = 0x30, is in ascii not number 0 pendingPool.push(msg.sender); emit IPFSInfo (msg.sender, "Request Added", dataID); return true; } else { //submitted before return updateRequest(dataID); } } function stopRequest() public returns (bool){ if (requestList[msg.sender].status == '0'){ //can only cancel owned pending request, ('0' = 0x30) delete requestList[msg.sender]; //delete from List emit SystemInfo(msg.sender, 'Request Stopped'); return ArrayPop(pendingPool, msg.sender); //delete from Pool } else{ emit SystemInfo(msg.sender, 'Request Unable to Stop'); return false; } } function updateRequest(bytes memory dataID) public payable returns (bool) { if(requestList[msg.sender].status == '0' ){ //can only update pending request requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].dataID = dataID; emit SystemInfo(msg.sender, 'Request Updated'); return true; } else{ emit SystemInfo(msg.sender, 'Request Unable to Update'); return false; } } //Add provAddr to request as a provider if they are available and their prices match up // Called by user who wants to choose provAddr to work for them // Returns '0' on success, '1' on failure function chooseProvider(address payable provAddr) public returns (byte){ if(requestList[msg.sender].status == '0'){ //Since this is ascii '0' its actually 0x30, users who have not submitted a task shouldn't get through here if(providerList[provAddr].available == true){ //if chosen provider is in the providerPool and their prices match providerList[provAddr].available = false; ArrayPop(providerPool, provAddr); requestList[msg.sender].provider = provAddr; requestList[msg.sender].status = '1'; ArrayPop(pendingPool, msg.sender); providingPool.push(msg.sender); emit PairingInfoLong(msg.sender, provAddr, "Request Assigned", requestList[msg.sender].dataID); return '0'; } else{ emit SystemInfo(msg.sender, 'Chosen provider is not available to work'); return '1'; } } else if(requestList[msg.sender].status == '2' && requestList[msg.sender].provider != provAddr){ providerList[provAddr].available = false; ArrayPop(providerPool, provAddr); requestList[msg.sender].validator = provAddr; requestList[msg.sender].signature = false; emit PairingInfoLong(msg.sender, provAddr, 'Validation Assigned to Provider', requestList[msg.sender].resultID); return '0'; } else{ if(requestList[msg.sender].status == '1'){ emit SystemInfo(msg.sender, 'Your request already has a provider assigned'); } else{ emit SystemInfo(msg.sender, 'You do not have a request'); } return '1'; } } // Provider will call this when they are done and the result data is available. // This will invoke the validation stage. Only when the request got enough validators, // that req could be moved from pool and marked. Or that req stays providing function completeRequest(address payable reqAddr, bytes memory resultID) public returns (bool) { // Confirm msg.sender is actually the provider of the task he claims if (msg.sender == requestList[reqAddr].provider) { //change request obj requestList[reqAddr].status = '2'; //validating requestList[reqAddr].resultID = resultID; //move from providing pool to validating Pool. ArrayPop(providingPool, reqAddr); validatingPool.push(reqAddr); //release provider (not necessarily depend on provider) back into providerPool providerList[msg.sender].available = true; providerPool.push(msg.sender); emit IPFSInfo(reqAddr, 'Request Computation Completed',requestList[reqAddr].resultID); //start validation process return true; } else { return false; } } // needs to be more secure by ensuring the submission is coming from someone legit // similar to completeTask but this will sign the validation list of the target Task // TODO: the money part is ommited for now function submitValidation(address payable reqAddr, bool result) public returns (bool) { if(msg.sender != requestList[reqAddr].provider) { //validator cannot be provider if(requestList[reqAddr].validator == msg.sender && requestList[reqAddr].signature == false){ // this is the validator and no signature yet //The way the project is coded right now, this is gauranteed to run. If this doesn't run something is wrong. if(requestList[reqAddr].deposit >= requestList[reqAddr].price){ //if the deposit is enough to pay requestList[reqAddr].provider.transfer(requestList[reqAddr].price); //send price to provider emit SystemInfo(requestList[reqAddr].provider, 'You have been paid'); //alert provider if(requestList[reqAddr].deposit >= requestList[reqAddr].price){ //if deposit was greater than price reqAddr.transfer(requestList[reqAddr].deposit - requestList[reqAddr].price); //return remaining eth back to user emit SystemInfo(reqAddr, 'You have recieved part of your deposit back'); //alert user } } // else { //deposit was not enough, need more ether // emit PairingInfo(reqAddr, requestList[reqAddr].provider, 'Deposit insufficient, ) // } requestList[reqAddr].signature = result; requestList[reqAddr].isValid = result; providerList[msg.sender].available = true; //release validator providerPool.push(msg.sender); emit PairingInfo(reqAddr, msg.sender, 'Validator Signed'); emit IPFSInfo(reqAddr, 'Validation Complete', requestList[reqAddr].resultID); } } else //submit vali from provider return false; } // finalize the completed result, move everything out of current pools function finalizeRequest(address payable reqAddr, bool toRate, uint8 rating) public returns (bool) { if(requestList[reqAddr].isValid){ ArrayPop(validatingPool, reqAddr); if(toRate){ //If user wishes to, let them rate the provider addRating(requestList[reqAddr].provider, rating); } delete requestList[reqAddr]; //delete user from mapping } } ///////////////////////////////////////////////////////////////////// // Used to dynamically remove elements from array of open provider spaces. // Using a swap and delete method, search for the desired addr throughout the whole array // delete the desired and swap the hole with last element function ArrayPop(address payable[] storage array, address payable target) private returns (bool) { for(uint64 i = 0; i < array.length; i++){ if (array[i] == target) { array[i] = array[array.length-1]; //swap last element with hole delete array[array.length-1]; //delete last item array.length -= 1; //decrease size return true; } } return false; //fail to search: no matching in pool } ///////////////////////////////////////////////////////////////////////////////// //some helpers defined here //NOTE: these helpers will use up the code space, (in Ethereum code lenght is limited) // can be removed in future to free up space. // function getProvider(address payable ID) public view returns(Provider memory){ // return providerList[ID]; // } // function getRequest(address payable ID) public view returns (Request memory){ // return requestList[ID]; // } function getProviderPool() public view returns (address payable[] memory){ return providerPool; } function getPendingPool() public view returns (address payable[] memory){ return pendingPool; } function getValidatingPool() public view returns (address payable[] memory){ return validatingPool; } function getProvidingPool() public view returns (address payable[] memory){ return providingPool; } // function getProviderPoolSize() public view returns (uint256){ // return providerPool.length; // } // function getRequestPoolSize() public view returns (uint256){ // return pendingPool.length; // } }
If user wishes to, let them rate the provider
if(toRate){
1,009,040
[ 1, 2047, 729, 14302, 281, 358, 16, 2231, 2182, 4993, 326, 2893, 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, 5411, 309, 12, 869, 4727, 15329, 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, -100, -100, -100 ]
pragma solidity ^0.4.24; // // .#########' // .###############+ // ,#################### // `#######################+ // ;########################## // #############################. // ###############################, // +##################, ###########` // .################### .########### // ##############, .###########+ // #############` .############` // ###########+ ############ // ###########; ########### // ##########' ########### // '########## '#. `, ########## // ########## ####' ####. :#########; // `#########' :#####; ###### ########## // :######### #######: ####### :######### // +######### :#######.######## #########` // #########; ###############' #########: // ######### #############+ '########' // ######### ############ :######### // ######### ########## ,######### // ######### :######## ,######### // ######### ,########## ,######### // ######### ,############ :########+ // ######### .#############+ '########' // #########: `###############' #########, // +########+ ;#######`;####### ######### // ,######### '######` '###### :######### // #########; .#####` '##### ########## // ########## '###` +### :#########: // ;#########+ ` ########## // ##########, ########### // ###########; ############ // +############ .############` // ###########+ ,#############; // `########### ;++################# // :##########, ################### // '###########.'################### // +############################## // '############################` // .########################## // #######################: // ###################+ // +##############: // :#######+` // // // // Play0x.com (The ONLY gaming platform for all ERC20 Tokens) // ------------------------------------------------------------------------------------------------------- // * Multiple types of game platforms // * Build your own game zone - Not only playing games, but also allowing other players to join your game. // * Support all ERC20 tokens. // // // // 0xC Token (Contract address : 0x60d8234a662651e586173c17eb45ca9833a7aa6c) // ------------------------------------------------------------------------------------------------------- // * 0xC Token is an ERC20 Token specifically for digital entertainment. // * No ICO and private sales,fair access. // * There will be hundreds of games using 0xC as a game token. // * Token holders can permanently get ETH's profit sharing. // /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address owner, address spender) public constant returns (uint256); function balanceOf(address who) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function transfer(address _to, uint256 _value) public; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Play0x_LottoBall { using SafeMath for uint256; using SafeMath for uint128; using SafeMath for uint40; using SafeMath for uint8; uint public jackpotSize; uint public MIN_BET; uint public MAX_BET; uint public MAX_AMOUNT; uint constant MAX_MODULO = 15; //Adjustable max bet profit. uint public maxProfit; //Fee percentage uint8 public platformFeePercentage = 15; uint8 public jackpotFeePercentage = 5; uint8 public ERC20rewardMultiple = 5; //0:ether 1:token uint8 public currencyType = 0; //Bets can be refunded via invoking refundBet. uint constant BetExpirationBlocks = 250; //Funds that are locked in potentially winning bets. uint public lockedInBets; //Standard contract ownership transfer. address public owner; address private nextOwner; address public secretSigner; address public refunder; //The address corresponding to a private key used to sign placeBet commits. address public ERC20ContractAddres; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //Single bet. struct Bet { //Amount in wei. uint amount; //place tx Block number. uint40 placeBlockNumber; // Address of a gambler. address gambler; // Game mode. uint8 machineMode; // Number of draws uint8 rotateTime; } //Mapping from commits mapping (uint => Bet) public bets; //Mapping from signer mapping(address => bool) public signerList; //Mapping from withdrawal mapping(uint8 => uint32) public withdrawalMode; //Admin Payment event ToManagerPayment(address indexed beneficiary, uint amount); event ToManagerFailedPayment(address indexed beneficiary, uint amount); event ToOwnerPayment(address indexed beneficiary, uint amount); event ToOwnerFailedPayment(address indexed beneficiary, uint amount); //Bet Payment event Payment(address indexed beneficiary, uint amount); event AllFundsPayment(address indexed beneficiary, uint amount); event AllTokenPayment(address indexed beneficiary, uint amount); event FailedPayment(address indexed beneficiary, uint amount); event TokenPayment(address indexed beneficiary, uint amount); //JACKPOT event JackpotBouns(address indexed beneficiary, uint amount); // Events that are issued to make statistic recovery easier. event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit); //Play0x_LottoBall_Event event BetRelatedData( address indexed player, uint playerBetAmount, uint playerGetAmount, bytes32 entropy, uint8 rotateTime ); //Refund_Event event RefundLog(address indexed player, uint commit, uint amount); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; refunder = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner); _; } modifier onlyRefunder { require (msg.sender == refunder); _; } modifier onlySigner { require (signerList[msg.sender] == true); _; } //Init Parameter. function initialParameter( // address _manager, address _secretSigner, address _erc20tokenAddress , address _refunder, uint _MIN_BET, uint _MAX_BET, uint _maxProfit, uint _MAX_AMOUNT, uint8 _platformFeePercentage, uint8 _jackpotFeePercentage, uint8 _ERC20rewardMultiple, uint8 _currencyType, address[] _signerList, uint32[] _withdrawalMode)public onlyOwner{ secretSigner = _secretSigner; ERC20ContractAddres = _erc20tokenAddress; refunder = _refunder; MIN_BET = _MIN_BET; MAX_BET = _MAX_BET; maxProfit = _maxProfit; MAX_AMOUNT = _MAX_AMOUNT; platformFeePercentage = _platformFeePercentage; jackpotFeePercentage = _jackpotFeePercentage; ERC20rewardMultiple = _ERC20rewardMultiple; currencyType = _currencyType; createSignerList(_signerList); createWithdrawalMode(_withdrawalMode); } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) public onlyOwner { require (_nextOwner != owner); nextOwner = _nextOwner; } function acceptNextOwner() public { require (msg.sender == nextOwner); owner = nextOwner; } // Fallback function deliberately left empty. function () public payable { } //Creat SignerList. function createSignerList(address[] _signerList)private onlyOwner { for (uint i=0; i<_signerList.length; i++) { address newSigner = _signerList[i]; signerList[newSigner] = true; } } //Creat WithdrawalMode. function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner { for (uint8 i=0; i<_withdrawalMode.length; i++) { uint32 newWithdrawalMode = _withdrawalMode[i]; uint8 mode = i + 1; withdrawalMode[mode] = newWithdrawalMode; } } //Set SecretSigner. function setSecretSigner(address _secretSigner) external onlyOwner { secretSigner = _secretSigner; } //Set settle signer. function setSigner(address signer,bool isActive )external onlyOwner{ signerList[signer] = isActive; } //Set Refunder. function setRefunder(address _refunder) external onlyOwner { refunder = _refunder; } //Set tokenAddress. function setTokenAddress(address _tokenAddress) external onlyOwner { ERC20ContractAddres = _tokenAddress; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) external onlyOwner { require (_maxProfit < MAX_AMOUNT && _maxProfit > 0); maxProfit = _maxProfit; } // Funds withdrawal. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance && withdrawAmount > 0); uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= address(this).balance); sendFunds(beneficiary, withdrawAmount ); } // Token withdrawal. function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); uint safetyAmount = jackpotSize.add(lockedInBets); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount); emit TokenPayment(beneficiary, withdrawAmount); } //Recovery of funds function withdrawAllFunds(address beneficiary) external onlyOwner { if (beneficiary.send(address(this).balance)) { lockedInBets = 0; jackpotSize = 0; emit AllFundsPayment(beneficiary, address(this).balance); } else { emit FailedPayment(beneficiary, address(this).balance); } } //Recovery of Token funds function withdrawAlltokenFunds(address beneficiary) external onlyOwner { ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); lockedInBets = 0; jackpotSize = 0; emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0); selfdestruct(owner); } function getContractInformation()public view returns( uint _jackpotSize, uint _MIN_BET, uint _MAX_BET, uint _MAX_AMOUNT, uint8 _platformFeePercentage, uint8 _jackpotFeePercentage, uint _maxProfit, uint _lockedInBets){ _jackpotSize = jackpotSize; _MIN_BET = MIN_BET; _MAX_BET = MAX_BET; _MAX_AMOUNT = MAX_AMOUNT; _platformFeePercentage = platformFeePercentage; _jackpotFeePercentage = jackpotFeePercentage; _maxProfit = maxProfit; _lockedInBets = lockedInBets; } function getContractAddress()public view returns( address _owner, address _ERC20ContractAddres, address _secretSigner, address _refunder ){ _owner = owner; _ERC20ContractAddres = ERC20ContractAddres; _secretSigner = secretSigner; _refunder = refunder; } //Bet by ether: Commits are signed with a block limit to ensure that they are used at most once. function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Check SecretSigner. bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit)); require (secretSigner == ecrecover(signatureHash, 27, r, s)); //Check rotateTime ,machineMode and commitLastBlock. require (_rotateTime > 0 && _rotateTime <= 20); //_machineMode: 1~15 require (_machineMode > 0 && _machineMode <= MAX_MODULO); require (block.number < _commitLastBlock ); lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) ); //Check the highest profit require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0); require (lockedInBets.add(jackpotSize) <= address(this).balance); //Amount should be within range require (msg.value >= MIN_BET && msg.value <= MAX_BET); emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit); // Store bet parameters on blockchain. bet.amount = msg.value; bet.placeBlockNumber = uint40(block.number); bet.gambler = msg.sender; bet.machineMode = uint8(_machineMode); bet.rotateTime = uint8(_rotateTime); } function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner { // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Check SecretSigner. bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit)); require (secretSigner == ecrecover(signatureHash, 27, r, s)); //Check rotateTime ,machineMode and commitLastBlock. require (_rotateTime > 0 && _rotateTime <= 20); //_machineMode: 1~15 require (_machineMode > 0 && _machineMode <= MAX_MODULO); require (block.number < _commitLastBlock ); //Token lockedInBets lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount)); //Check the highest profit require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0); require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this))); //Amount should be within range require (_amount >= MIN_BET && _amount <= MAX_BET); emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit); // Store bet parameters on blockchain. bet.amount = _amount; bet.placeBlockNumber = uint40(block.number); bet.gambler = _playerAddress; bet.machineMode = _machineMode; bet.rotateTime = _rotateTime; } function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{ // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); // Fetch bet parameters into local variables (to save gas). Bet storage bet = bets[commit]; // Check that bet is in 'active' state and check that bet has not expired yet. require (bet.amount != 0); require (bet.rotateTime > 0 && bet.rotateTime <= 20); require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO); require (block.number > bet.placeBlockNumber); require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks)); require (blockhash(bet.placeBlockNumber) == blockHash); //check possibleWinAmount require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit); require (luckySeed > 0); //The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256. bytes32 _entropy = keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( reveal, luckySeed ) ) ), blockHash ) ); //Player profit uint totalAmount = 0; //Player Token profit uint totalTokenAmount = 0; //Jackpot check default value bool isGetJackpot = false; //Settlement record bytes32 tmp_entropy = _entropy; //Billing mode uint8 machineMode = bet.machineMode; for (uint8 i = 0; i < bet.rotateTime; i++) { //every round result bool isWinThisRound = false; //Random number of must be less than the machineMode assembly { switch gt(machineMode,and(tmp_entropy, 0xf)) case 1 { isWinThisRound := 1 } } if (isWinThisRound == true ){ //bet win, get single round bonus totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime)); //Platform fee determination:Ether Game Winning players must pay platform fees totalAmount = totalAmount.sub( ( ( bet.amount.div(bet.rotateTime) ).mul(platformFeePercentage) ).div(1000) ); }else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ //Ether game lose, get token reward totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple)); } //Get jackpotWin Result, only one chance to win Jackpot in each game. if (isGetJackpot == false){ //getJackpotWinBonus assembly { let buf := and(tmp_entropy, 0xffff) switch buf case 0xffff { isGetJackpot := 1 } } } //This round is settled, shift settlement record. tmp_entropy = tmp_entropy >> 4; } //Player get Jackpot if (isGetJackpot == true ) { emit JackpotBouns(bet.gambler,jackpotSize); totalAmount = totalAmount.add(jackpotSize); jackpotSize = 0; } if (currencyType == 0) { //Ether game if (totalAmount != 0 && totalAmount < maxProfit){ sendFunds(bet.gambler, totalAmount ); } //Send ERC20 Token if (totalTokenAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount); emit TokenPayment(bet.gambler, totalTokenAmount); } } }else if(currencyType == 1){ //ERC20 game //Send ERC20 Token if (totalAmount != 0 && totalAmount < maxProfit){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount); emit TokenPayment(bet.gambler, totalAmount); } } } //Unlock the bet amount, regardless of the outcome. lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount)); //Save jackpotSize jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000)); emit BetRelatedData( bet.gambler, bet.amount, totalAmount, _entropy, bet.rotateTime ); //Move bet into 'processed' state already. bet.amount = 0; } function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) { bytes32 tmp_entropy = _entropy; isGetJackpot = false; uint8 machineMode = bet.machineMode; for (uint8 i = 0; i < bet.rotateTime; i++) { //every round result bool isWinThisRound = false; //Random number of must be less than the machineMode assembly { switch gt(machineMode,and(tmp_entropy, 0xf)) case 1 { isWinThisRound := 1 } } if (isWinThisRound == true ){ //bet win, get single round bonus totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime)); //Platform fee determination:Ether Game Winning players must pay platform fees totalAmount = totalAmount.sub( ( ( bet.amount.div(bet.rotateTime) ).mul(platformFeePercentage) ).div(1000) ); }else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ //Ether game lose, get token reward totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple)); } //Get jackpotWin Result, only one chance to win Jackpot in each game. if (isGetJackpot == false){ //getJackpotWinBonus assembly { let buf := and(tmp_entropy, 0xffff) switch buf case 0xffff { isGetJackpot := 1 } } } //This round is settled, shift settlement record. tmp_entropy = tmp_entropy >> 4; } if (isGetJackpot == true ) { //gambler get jackpot. totalAmount = totalAmount.add(jackpotSize); } } //Get deductedBalance function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) { //Win Amount possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000); } //Get deductedBalance function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) { //Platform Fee uint prePlatformFee = (senderValue).mul(platformFeePercentage); platformFee = (prePlatformFee).div(1000); //Get jackpotFee uint preJackpotFee = (senderValue).mul(jackpotFeePercentage); jackpotFee = (preJackpotFee).div(1000); //Win Amount uint preUserGetAmount = senderValue.mul(bonusPercentage); possibleWinAmount = preUserGetAmount.div(10000); } function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); // Fetch bet parameters into local variables (to save gas). Bet storage bet = bets[commit]; //The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256. _entropy = keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( reveal, luckySeed ) ) ), blockHash ) ); isGetJackpot = false; (totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime( bet, _entropy ); } // Refund transaction function refundBet(uint commit) external onlyRefunder{ // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; uint8 machineMode = bet.machineMode; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); //Amount unlock lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount)); //Refund emit RefundLog(bet.gambler,commit, amount); sendFunds(bet.gambler, amount ); // Move bet into 'processed' state, release funds. bet.amount = 0; } function refundTokenBet(uint commit) external onlyRefunder{ // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; uint8 machineMode = bet.machineMode; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); //Amount unlock lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount)); emit RefundLog(bet.gambler,commit, amount); //Refund emit TokenPayment(bet.gambler, amount); ERC20(ERC20ContractAddres).transfer(bet.gambler, amount); // Move bet into 'processed' state, release funds. bet.amount = 0; } // A helper routine to bulk clean the storage. function clearStorage(uint[] cleanCommits) external onlyRefunder { uint length = cleanCommits.length; for (uint i = 0; i < length; i++) { clearProcessedBet(cleanCommits[i]); } } // Helper routine to move 'processed' bets into 'clean' state. function clearProcessedBet(uint commit) private { Bet storage bet = bets[commit]; // Do not overwrite active bets with zeros if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) { return; } // Zero out the remaining storage bet.placeBlockNumber = 0; bet.gambler = address(0); bet.machineMode = 0; bet.rotateTime = 0; } // Helper routine to process the payment. function sendFunds(address receiver, uint amount ) private { if (receiver.send(amount)) { emit Payment(receiver, amount); } else { emit FailedPayment(receiver, amount); } } function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner { if (beneficiary.send(amount)) { emit ToOwnerPayment(beneficiary, amount); } else { emit ToOwnerFailedPayment(beneficiary, amount); } } //Update function updateMIN_BET(uint _uintNumber)external onlyOwner { MIN_BET = _uintNumber; } function updateMAX_BET(uint _uintNumber)external onlyOwner { MAX_BET = _uintNumber; } function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner { MAX_AMOUNT = _uintNumber; } function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{ withdrawalMode[_mode] = _modeValue; } function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{ platformFeePercentage = _platformFeePercentage; } function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{ jackpotFeePercentage = _jackpotFeePercentage; } function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{ ERC20rewardMultiple = _ERC20rewardMultiple; } function updateCurrencyType(uint8 _currencyType ) external onlyOwner{ currencyType = _currencyType; } function updateJackpot(uint newSize) external onlyOwner { require (newSize < address(this).balance && newSize > 0); jackpotSize = newSize; } }
Constructor. Deliberately does not take any parameters.
constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; refunder = DUMMY_ADDRESS; }
14,052,661
[ 1, 6293, 18, 6603, 14776, 5173, 1552, 486, 4862, 1281, 1472, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 4001, 15647, 273, 463, 2799, 22114, 67, 15140, 31, 7010, 3639, 4232, 39, 3462, 8924, 986, 455, 273, 463, 2799, 22114, 67, 15140, 31, 7010, 3639, 1278, 9341, 273, 463, 2799, 22114, 67, 15140, 31, 7010, 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 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title VestedToken * @dev The VestedToken contract implements ERC20 standard basics function and * - vesting for an address * - token tradability delay */ contract VestedToken { using SafeMath for uint256; // Vested wallet address address public vestedAddress; // Vesting time uint private constant VESTING_DELAY = 1 years; // Token will be tradable TOKEN_TRADABLE_DELAY after uint private constant TOKEN_TRADABLE_DELAY = 12 days; // True if aside tokens have already been minted after second round bool public asideTokensHaveBeenMinted = false; // When aside tokens have been minted ? uint public asideTokensMintDate; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; modifier transferAllowed { require(asideTokensHaveBeenMinted && now > asideTokensMintDate + TOKEN_TRADABLE_DELAY); _; } // Get the balance from an address function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } // transfer ERC20 function function transfer(address _to, uint256 _value) transferAllowed public returns (bool success) { require(_to != 0x0); // founders wallets is blocked 1 year if (msg.sender == vestedAddress && (now < (asideTokensMintDate + VESTING_DELAY))) { revert(); } return privateTransfer(_to, _value); } // transferFrom ERC20 function function transferFrom(address _from, address _to, uint256 _value) transferAllowed public returns (bool success) { require(_from != 0x0); require(_to != 0x0); // founders wallet is blocked 1 year if (_from == vestedAddress && (now < (asideTokensMintDate + VESTING_DELAY))) { revert(); } uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } // approve ERC20 function function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // allowance ERC20 function function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function privateTransfer (address _to, uint256 _value) private returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } // Events ERC20 event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title WhitelistsRegistration * @dev This is an extension to add 2 levels whitelists to the crowdsale */ contract WhitelistsRegistration is Ownable { // List of whitelisted addresses for KYC under 10 ETH mapping(address => bool) silverWhiteList; // List of whitelisted addresses for KYC over 10 ETH mapping(address => bool) goldWhiteList; // Different stage from the ICO enum WhiteListState { // This address is not whitelisted None, // this address is on the silver whitelist Silver, // this address is on the gold whitelist Gold } address public whiteLister; event SilverWhitelist(address indexed _address, bool _isRegistered); event GoldWhitelist(address indexed _address, bool _isRegistered); event SetWhitelister(address indexed newWhiteLister); /** * @dev Throws if called by any account other than the owner or the whitelister. */ modifier onlyOwnerOrWhiteLister() { require((msg.sender == owner) || (msg.sender == whiteLister)); _; } // Return registration status of an specified address function checkRegistrationStatus(address _address) public constant returns (WhiteListState) { if (goldWhiteList[_address]) { return WhiteListState.Gold; } if (silverWhiteList[_address]) { return WhiteListState.Silver; } return WhiteListState.None; } // Change registration status for an address in the whitelist for KYC under 10 ETH function changeRegistrationStatusForSilverWhiteList(address _address, bool _isRegistered) public onlyOwnerOrWhiteLister { silverWhiteList[_address] = _isRegistered; SilverWhitelist(_address, _isRegistered); } // Change registration status for an address in the whitelist for KYC over 10 ETH function changeRegistrationStatusForGoldWhiteList(address _address, bool _isRegistered) public onlyOwnerOrWhiteLister { goldWhiteList[_address] = _isRegistered; GoldWhitelist(_address, _isRegistered); } // Change registration status for several addresses in the whitelist for KYC under 10 ETH function massChangeRegistrationStatusForSilverWhiteList(address[] _targets, bool _isRegistered) public onlyOwnerOrWhiteLister { for (uint i = 0; i < _targets.length; i++) { changeRegistrationStatusForSilverWhiteList(_targets[i], _isRegistered); } } // Change registration status for several addresses in the whitelist for KYC over 10 ETH function massChangeRegistrationStatusForGoldWhiteList(address[] _targets, bool _isRegistered) public onlyOwnerOrWhiteLister { for (uint i = 0; i < _targets.length; i++) { changeRegistrationStatusForGoldWhiteList(_targets[i], _isRegistered); } } /** * @dev Allows the current owner or whiteLister to transfer control of the whitelist to a newWhitelister. * @param _newWhiteLister The address to transfer whitelist to. */ function setWhitelister(address _newWhiteLister) public onlyOwnerOrWhiteLister { require(_newWhiteLister != address(0)); SetWhitelister(_newWhiteLister); whiteLister = _newWhiteLister; } } /** * @title BCDToken * @dev The BCDT crowdsale */ contract BCDToken is VestedToken, WhitelistsRegistration { string public constant name = "Blockchain Certified Data Token"; string public constant symbol = "BCDT"; uint public constant decimals = 18; // Maximum contribution in ETH for silver whitelist uint private constant MAX_ETHER_FOR_SILVER_WHITELIST = 10 ether; // ETH/BCDT rate uint public rateETH_BCDT = 13000; // Soft cap, if not reached contributors can withdraw their ethers uint public softCap = 1800 ether; // Cap in ether of presale uint public presaleCap = 1800 ether; // Cap in ether of Round 1 (presale cap + 1800 ETH) uint public round1Cap = 3600 ether; // BCD Reserve/Community Wallets address public reserveAddress; address public communityAddress; // Different stage from the ICO enum State { // ICO isn't started yet, initial state Init, // Presale has started PresaleRunning, // Presale has ended PresaleFinished, // Round 1 has started Round1Running, // Round 1 has ended Round1Finished, // Round 2 has started Round2Running, // Round 2 has ended Round2Finished } // Initial state is Init State public currentState = State.Init; // BCDT total supply uint256 public totalSupply = MAX_TOTAL_BCDT_TO_SELL; // How much tokens have been sold uint256 public tokensSold; // Amount of ETH raised during ICO uint256 private etherRaisedDuringICO; // Maximum total of BCDT Token sold during ITS uint private constant MAX_TOTAL_BCDT_TO_SELL = 100000000 * 1 ether; // Token allocation per mille for reserve/community/founders uint private constant RESERVE_ALLOCATION_PER_MILLE_RATIO = 200; uint private constant COMMUNITY_ALLOCATION_PER_MILLE_RATIO = 103; uint private constant FOUNDERS_ALLOCATION_PER_MILLE_RATIO = 30; // List of contributors/contribution in ETH mapping(address => uint256) contributors; // Use to allow function call only if currentState is the one specified modifier inStateInit() { require(currentState == State.Init); _; } modifier inStateRound2Finished() { require(currentState == State.Round2Finished); _; } // Event call when aside tokens are minted event AsideTokensHaveBeenAllocated(address indexed to, uint256 amount); // Event call when a contributor withdraw his ethers event Withdraw(address indexed to, uint256 amount); // Event call when ICO state change event StateChanged(uint256 timestamp, State currentState); // Constructor function BCDToken() public { } function() public payable { require(currentState == State.PresaleRunning || currentState == State.Round1Running || currentState == State.Round2Running); // min transaction is 0.1 ETH if (msg.value < 100 finney) { revert(); } // If you're not in any whitelist, you cannot continue if (!silverWhiteList[msg.sender] && !goldWhiteList[msg.sender]) { revert(); } // ETH sent by contributor uint256 ethSent = msg.value; // how much ETH will be used for contribution uint256 ethToUse = ethSent; // Address is only in the silver whitelist: contribution is capped if (!goldWhiteList[msg.sender]) { // Check if address has already contributed for maximum allowance if (contributors[msg.sender] >= MAX_ETHER_FOR_SILVER_WHITELIST) { revert(); } // limit the total contribution to MAX_ETHER_FOR_SILVER_WHITELIST if (contributors[msg.sender].add(ethToUse) > MAX_ETHER_FOR_SILVER_WHITELIST) { ethToUse = MAX_ETHER_FOR_SILVER_WHITELIST.sub(contributors[msg.sender]); } } // Calculate how much ETH are available for this stage uint256 ethAvailable = getRemainingEthersForCurrentRound(); uint rate = getBCDTRateForCurrentRound(); // If cap of the round has been reached if (ethAvailable <= ethToUse) { // End the round privateSetState(getEndedStateForCurrentRound()); // Only available ethers will be used to reach the cap ethToUse = ethAvailable; } // Calculate token amount to send in accordance to rate uint256 tokenToSend = ethToUse.mul(rate); // Amount of tokens sold to the current contributors is added to total sold tokensSold = tokensSold.add(tokenToSend); // Amount of ethers used for the current contribution is added the total raised etherRaisedDuringICO = etherRaisedDuringICO.add(ethToUse); // Token balance updated for current contributor balances[msg.sender] = balances[msg.sender].add(tokenToSend); // Contribution is stored for an potential withdraw contributors[msg.sender] = contributors[msg.sender].add(ethToUse); // Send back the unused ethers if (ethToUse < ethSent) { msg.sender.transfer(ethSent.sub(ethToUse)); } // Log token transfer operation Transfer(0x0, msg.sender, tokenToSend); } // Allow contributors to withdraw after the end of the ICO if the softcap hasn't been reached function withdraw() public inStateRound2Finished { // Only contributors with positive ETH balance could Withdraw if(contributors[msg.sender] == 0) { revert(); } // Withdraw is possible only if softcap has not been reached require(etherRaisedDuringICO < softCap); // Get how much ethers sender has contribute uint256 ethToSendBack = contributors[msg.sender]; // Set contribution to 0 for the contributor contributors[msg.sender] = 0; // Send back ethers msg.sender.transfer(ethToSendBack); // Log withdraw operation Withdraw(msg.sender, ethToSendBack); } // At the end of the sale, mint the aside tokens for the reserve, community and founders function mintAsideTokens() public onlyOwner inStateRound2Finished { // Reserve, community and founders address have to be set before mint aside tokens require((reserveAddress != 0x0) && (communityAddress != 0x0) && (vestedAddress != 0x0)); // Aside tokens can be minted only if softcap is reached require(this.balance >= softCap); // Revert if aside tokens have already been minted if (asideTokensHaveBeenMinted) { revert(); } // Set minted flag and date asideTokensHaveBeenMinted = true; asideTokensMintDate = now; // If 100M sold, 50M more have to be mint (15 / 10 = * 1.5 = +50%) totalSupply = tokensSold.mul(15).div(10); // 20% of total supply is allocated to reserve uint256 _amountMinted = setAllocation(reserveAddress, RESERVE_ALLOCATION_PER_MILLE_RATIO); // 10.3% of total supply is allocated to community _amountMinted = _amountMinted.add(setAllocation(communityAddress, COMMUNITY_ALLOCATION_PER_MILLE_RATIO)); // 3% of total supply is allocated to founders _amountMinted = _amountMinted.add(setAllocation(vestedAddress, FOUNDERS_ALLOCATION_PER_MILLE_RATIO)); // the allocation is only 33.3%*150/100 = 49.95% of the token solds. It is therefore slightly higher than it should. // to avoid that, we correct the real total number of tokens totalSupply = tokensSold.add(_amountMinted); // Send the eth to the owner of the contract owner.transfer(this.balance); } function setTokenAsideAddresses(address _reserveAddress, address _communityAddress, address _founderAddress) public onlyOwner { require(_reserveAddress != 0x0 && _communityAddress != 0x0 && _founderAddress != 0x0); // Revert when aside tokens have already been minted if (asideTokensHaveBeenMinted) { revert(); } reserveAddress = _reserveAddress; communityAddress = _communityAddress; vestedAddress = _founderAddress; } function updateCapsAndRate(uint _presaleCapInETH, uint _round1CapInETH, uint _softCapInETH, uint _rateETH_BCDT) public onlyOwner inStateInit { // Caps and rate are updatable until ICO starts require(_round1CapInETH > _presaleCapInETH); require(_rateETH_BCDT != 0); presaleCap = _presaleCapInETH * 1 ether; round1Cap = _round1CapInETH * 1 ether; softCap = _softCapInETH * 1 ether; rateETH_BCDT = _rateETH_BCDT; } function getRemainingEthersForCurrentRound() public constant returns (uint) { require(currentState != State.Init); require(!asideTokensHaveBeenMinted); if((currentState == State.PresaleRunning) || (currentState == State.PresaleFinished)) { // Presale cap is fixed in ETH return presaleCap.sub(etherRaisedDuringICO); } if((currentState == State.Round1Running) || (currentState == State.Round1Finished)) { // Round 1 cap is fixed in ETH return round1Cap.sub(etherRaisedDuringICO); } if((currentState == State.Round2Running) || (currentState == State.Round2Finished)) { // Round 2 cap is limited in tokens, uint256 remainingTokens = totalSupply.sub(tokensSold); // ETH available is calculated from the number of remaining tokens regarding the rate return remainingTokens.div(rateETH_BCDT); } } function getBCDTRateForCurrentRound() public constant returns (uint) { require(currentState == State.PresaleRunning || currentState == State.Round1Running || currentState == State.Round2Running); // ETH/BCDT rate during presale: 20% bonus if(currentState == State.PresaleRunning) { return rateETH_BCDT + rateETH_BCDT * 20 / 100; } // ETH/BCDT rate during presale: 10% bonus if(currentState == State.Round1Running) { return rateETH_BCDT + rateETH_BCDT * 10 / 100; } if(currentState == State.Round2Running) { return rateETH_BCDT; } } function setState(State _newState) public onlyOwner { privateSetState(_newState); } function privateSetState(State _newState) private { // no way to go back if(_newState <= currentState) { revert(); } currentState = _newState; StateChanged(now, currentState); } function getEndedStateForCurrentRound() private constant returns (State) { require(currentState == State.PresaleRunning || currentState == State.Round1Running || currentState == State.Round2Running); if(currentState == State.PresaleRunning) { return State.PresaleFinished; } if(currentState == State.Round1Running) { return State.Round1Finished; } if(currentState == State.Round2Running) { return State.Round2Finished; } } function setAllocation(address _to, uint _ratio) private onlyOwner returns (uint256) { // Aside token is a percentage of totalSupply uint256 tokenAmountToTransfert = totalSupply.mul(_ratio).div(1000); balances[_to] = balances[_to].add(tokenAmountToTransfert); AsideTokensHaveBeenAllocated(_to, tokenAmountToTransfert); Transfer(0x0, _to, tokenAmountToTransfert); return tokenAmountToTransfert; } }
Amount of ETH raised during ICO
uint256 private etherRaisedDuringICO;
7,304,301
[ 1, 6275, 434, 512, 2455, 11531, 4982, 467, 3865, 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, 2254, 5034, 3238, 225, 2437, 12649, 5918, 26424, 2871, 51, 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 ]
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/Governor.sol
* @dev See {IGovernor-getVotes}./
function getVotes(address account, uint256 timepoint) public view virtual returns (uint256) { return _getVotes(account, timepoint, _defaultParams()); }
8,083,717
[ 1, 9704, 288, 3047, 1643, 29561, 17, 588, 29637, 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, 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, 565, 445, 11031, 6366, 12, 2867, 2236, 16, 2254, 5034, 813, 1153, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 588, 29637, 12, 4631, 16, 813, 1153, 16, 389, 1886, 1370, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IMultiVaultConverter { function token() external returns (address); function get_virtual_price() external view returns (uint); function convert_rate(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); function calc_token_amount_deposit(uint[] calldata _amounts) external view returns (uint _shareAmount); function calc_token_amount_withdraw(uint _shares, address _output) external view returns (uint _outputAmount); function convert(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); function convertAll(uint[] calldata _amounts) external returns (uint _outputAmount); } interface IValueVaultMaster { function bank(address) view external returns (address); function isVault(address) view external returns (bool); function isController(address) view external returns (bool); function isStrategy(address) view external returns (bool); function slippage(address) view external returns (uint); function convertSlippage(address _input, address _output) view external returns (uint); function valueToken() view external returns (address); function govVault() view external returns (address); function insuranceFund() view external returns (address); function performanceReward() view external returns (address); function govVaultProfitShareFee() view external returns (uint); function gasFee() view external returns (uint); function insuranceFee() view external returns (uint); function withdrawalProtectionFee() view external returns (uint); } // 0: DAI, 1: USDC, 2: USDT interface IStableSwap3Pool { function get_virtual_price() external view returns (uint); function balances(uint) external view returns (uint); function calc_token_amount(uint[3] calldata amounts, bool deposit) external view returns (uint); function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns (uint); function get_dy(int128 i, int128 j, uint dx) external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external; function exchange(int128 i, int128 j, uint dx, uint min_dy) external; } // 0: DAI, 1: USDC, 2: USDT, 3: BUSD interface IStableSwapBUSD { function get_virtual_price() external view returns (uint); function calc_token_amount(uint[4] calldata amounts, bool deposit) external view returns (uint); function get_dy_underlying(int128 i, int128 j, uint dx) external view returns (uint dy); function get_dx_underlying(int128 i, int128 j, uint dy) external view returns (uint dx); function exchange_underlying(int128 i, int128 j, uint dx, uint min_dy) external; } // 0: hUSD, 1: 3Crv interface IStableSwapHUSD { function get_virtual_price() external view returns (uint); function calc_token_amount(uint[2] calldata amounts, bool deposit) external view returns (uint); function get_dy(int128 i, int128 j, uint dx) external view returns (uint dy); function get_dy_underlying(int128 i, int128 j, uint dx) external view returns (uint dy); function get_dx_underlying(int128 i, int128 j, uint dy) external view returns (uint dx); function exchange_underlying(int128 i, int128 j, uint dx, uint min_dy) external; function exchange(int128 i, int128 j, uint dx, uint min_dy) external; function calc_withdraw_one_coin(uint amount, int128 i) external view returns (uint); function remove_liquidity_one_coin(uint amount, int128 i, uint minAmount) external returns (uint); function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external returns (uint); } // 0: DAI, 1: USDC, 2: USDT, 3: sUSD interface IStableSwapSUSD { function get_virtual_price() external view returns (uint); function calc_token_amount(uint[4] calldata amounts, bool deposit) external view returns (uint); function get_dy_underlying(int128 i, int128 j, uint dx) external view returns (uint dy); function get_dx_underlying(int128 i, int128 j, uint dy) external view returns (uint dx); function exchange_underlying(int128 i, int128 j, uint dx, uint min_dy) external; } // 0: DAI, 1: USDC interface IStableSwapCompound { function get_virtual_price() external view returns (uint); function calc_token_amount(uint[2] calldata amounts, bool deposit) external view returns (uint); function get_dy_underlying(int128 i, int128 j, uint dx) external view returns (uint dy); function get_dx_underlying(int128 i, int128 j, uint dy) external view returns (uint dx); function exchange_underlying(int128 i, int128 j, uint dx, uint min_dy) external; } interface IDepositCompound { function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns (uint); function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external; } interface CTokenInterface { function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); } // Supported Pool Tokens: // 0. 3pool [DAI, USDC, USDT] // 1. BUSD [(y)DAI, (y)USDC, (y)USDT, (y)BUSD] // 2. sUSD [DAI, USDC, USDT, sUSD] // 3. husd [HUSD, 3pool] // 4. Compound [(c)DAI, (c)USDC] // 5. Y [(y)DAI, (y)USDC, (y)USDT, (y)TUSD] // 6. Swerve [(y)DAI...(y)TUSD] contract StableSwapCompoundConverter is IMultiVaultConverter { using SafeMath for uint; using SafeERC20 for IERC20; IERC20[2] public cpoolTokens; // DAI, USDC CTokenInterface[2] public cpoolCTokens; IERC20 public tokenUSDT; IERC20 public tokenBUSD; // BUSD IERC20 public token3Crv; // 3Crv IERC20 public tokenSUSD; // sUSD IERC20 public tokenHUSD; // hUSD IERC20 public tokenCCrv; // cDAI+cUSDC ((c)DAI+(c)USDC) address public governance; IStableSwap3Pool public stableSwap3Pool; IStableSwapBUSD public stableSwapBUSD; IStableSwapSUSD public stableSwapSUSD; IStableSwapHUSD public stableSwapHUSD; IStableSwapCompound public stableSwapCompound; IDepositCompound public depositCompound; IValueVaultMaster public vaultMaster; uint public defaultSlippage = 1; // very small 0.01% // stableSwapUSD: 0. stableSwap3Pool, 1. stableSwapBUSD, 2. stableSwapSUSD, 3. stableSwapHUSD, 4. stableSwapCompound constructor (IERC20 _tokenDAI, IERC20 _tokenUSDC, IERC20 _tokenUSDT, IERC20 _token3Crv, IERC20 _tokenBUSD, IERC20 _tokenSUSD, IERC20 _tokenHUSD, IERC20 _tokenCCrv, CTokenInterface _tokenCDAI, CTokenInterface _tokenCUSDC, address[] memory _stableSwapUSD, IDepositCompound _depositCompound, IValueVaultMaster _vaultMaster) public { cpoolTokens[0] = _tokenDAI; cpoolTokens[1] = _tokenUSDC; tokenUSDT = _tokenUSDT; tokenBUSD = _tokenBUSD; token3Crv = _token3Crv; tokenSUSD = _tokenSUSD; tokenHUSD = _tokenHUSD; tokenCCrv = _tokenCCrv; cpoolCTokens[0] = _tokenCDAI; cpoolCTokens[1] = _tokenCUSDC; stableSwap3Pool = IStableSwap3Pool(_stableSwapUSD[0]); stableSwapBUSD = IStableSwapBUSD(_stableSwapUSD[1]); stableSwapSUSD = IStableSwapSUSD(_stableSwapUSD[2]); stableSwapHUSD = IStableSwapHUSD(_stableSwapUSD[3]); stableSwapCompound = IStableSwapCompound(_stableSwapUSD[4]); depositCompound = _depositCompound; cpoolTokens[0].safeApprove(address(stableSwap3Pool), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwap3Pool), type(uint256).max); tokenUSDT.safeApprove(address(stableSwap3Pool), type(uint256).max); token3Crv.safeApprove(address(stableSwap3Pool), type(uint256).max); cpoolTokens[0].safeApprove(address(stableSwapBUSD), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwapBUSD), type(uint256).max); tokenUSDT.safeApprove(address(stableSwapBUSD), type(uint256).max); tokenBUSD.safeApprove(address(stableSwapBUSD), type(uint256).max); cpoolTokens[0].safeApprove(address(stableSwapSUSD), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwapSUSD), type(uint256).max); tokenUSDT.safeApprove(address(stableSwapSUSD), type(uint256).max); tokenSUSD.safeApprove(address(stableSwapSUSD), type(uint256).max); token3Crv.safeApprove(address(stableSwapHUSD), type(uint256).max); tokenHUSD.safeApprove(address(stableSwapHUSD), type(uint256).max); cpoolTokens[0].safeApprove(address(stableSwapCompound), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwapCompound), type(uint256).max); tokenCCrv.safeApprove(address(stableSwapCompound), type(uint256).max); cpoolTokens[0].safeApprove(address(depositCompound), type(uint256).max); cpoolTokens[1].safeApprove(address(depositCompound), type(uint256).max); tokenCCrv.safeApprove(address(depositCompound), type(uint256).max); vaultMaster = _vaultMaster; governance = msg.sender; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setVaultMaster(IValueVaultMaster _vaultMaster) external { require(msg.sender == governance, "!governance"); vaultMaster = _vaultMaster; } function approveForSpender(IERC20 _token, address _spender, uint _amount) external { require(msg.sender == governance, "!governance"); _token.safeApprove(_spender, _amount); } function setDefaultSlippage(uint _defaultSlippage) external { require(msg.sender == governance, "!governance"); require(_defaultSlippage <= 100, "_defaultSlippage>1%"); defaultSlippage = _defaultSlippage; } function token() external override returns (address) { return address(tokenCCrv); } // Average dollar value of pool token function get_virtual_price() external override view returns (uint) { return stableSwapCompound.get_virtual_price(); } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; if (_output == address(tokenCCrv)) { // convert to CCrv uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { uint _dai = stableSwap3Pool.get_dy(int128(2), int128(0), _inputAmount); // convert to DAI _amounts[0] = _convert_underlying_to_ctoken(cpoolCTokens[0], _dai); // DAI -> cDAI _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); // cDAI -> CCrv } if (_input == address(tokenBUSD)) { uint _dai = stableSwapBUSD.get_dy_underlying(int128(3), int128(0), _inputAmount); // convert to DAI _amounts[0] = _convert_underlying_to_ctoken(cpoolCTokens[0], _dai); // DAI -> cDAI _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); // cDAI -> CCrv } if (_input == address(tokenSUSD)) { uint _dai = stableSwapSUSD.get_dy_underlying(int128(3), int128(0), _inputAmount); // convert to DAI _amounts[0] = _convert_underlying_to_ctoken(cpoolCTokens[0], _dai); // DAI -> cDAI _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); // cDAI -> CCrv } if (_input == address(tokenHUSD)) { uint _3crvAmount = stableSwapHUSD.get_dy(int128(0), int128(1), _inputAmount); // HUSD -> 3Crv uint _dai = stableSwap3Pool.calc_withdraw_one_coin(_3crvAmount, 0); // 3Crv -> DAI _amounts[0] = _convert_underlying_to_ctoken(cpoolCTokens[0], _dai); // DAI -> cDAI _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); // cDAI -> CCrv } if (_input == address(token3Crv)) { uint _dai = stableSwap3Pool.calc_withdraw_one_coin(_inputAmount, 0); // 3Crv -> DAI _amounts[0] = _convert_underlying_to_ctoken(cpoolCTokens[0], _dai); // DAI -> cDAI _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); // cDAI -> CCrv } } else if (_input == address(tokenCCrv)) { // convert from CCrv for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { uint _daiAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, 0); // convert to DAI _outputAmount = stableSwap3Pool.get_dy(int128(0), int128(2), _daiAmount); // DAI -> USDT } if (_output == address(tokenBUSD)) { uint _daiAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, 0); // convert to DAI _outputAmount = stableSwapBUSD.get_dy_underlying(int128(0), int128(3), _daiAmount); // DAI -> BUSD } if (_output == address(tokenSUSD)) { uint _daiAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, 0); // CCrv -> DAI _outputAmount = stableSwapSUSD.get_dy_underlying(int128(0), int128(3), _daiAmount); // DAI -> SUSD } if (_output == address(tokenHUSD)) { uint _3crvAmount = _convert_ccrv_to_3crv_rate(_inputAmount); // CCrv -> DAI -> 3Crv _outputAmount = stableSwapHUSD.get_dy(int128(1), int128(0), _3crvAmount); // 3Crv -> HUSD } } if (_outputAmount > 0) { uint _slippage = _outputAmount.mul(vaultMaster.convertSlippage(_input, _output)).div(10000); _outputAmount = _outputAmount.sub(_slippage); } } function _convert_ccrv_to_3crv_rate(uint _ccrvAmount) internal view returns (uint _3crv) { uint[3] memory _amounts; _amounts[0] = depositCompound.calc_withdraw_one_coin(_ccrvAmount, 0); // CCrv -> DAI _3crv = stableSwap3Pool.calc_token_amount(_amounts, true); // DAI -> 3Crv } // 0: DAI, 1: USDC, 2: USDT, 3: 3Crv, 4: BUSD, 5: sUSD, 6: husd function calc_token_amount_deposit(uint[] calldata _amounts) external override view returns (uint _shareAmount) { if (_amounts[0] > 0 || _amounts[1] > 0) { uint[2] memory _cpoolAmounts; _cpoolAmounts[0] = _convert_underlying_to_ctoken(cpoolCTokens[0], _amounts[0]); _cpoolAmounts[1] = _convert_underlying_to_ctoken(cpoolCTokens[1], _amounts[1]); _shareAmount = stableSwapCompound.calc_token_amount(_cpoolAmounts, true); } if (_amounts[2] > 0) { // usdt _shareAmount = _shareAmount.add(convert_rate(address(tokenUSDT), address(tokenCCrv), _amounts[2])); } if (_amounts[3] > 0) { // 3crv _shareAmount = _shareAmount.add(convert_rate(address(token3Crv), address(tokenCCrv), _amounts[3])); } if (_amounts[4] > 0) { // busd _shareAmount = _shareAmount.add(convert_rate(address(tokenBUSD), address(tokenCCrv), _amounts[4])); } if (_amounts[5] > 0) { // susd _shareAmount = _shareAmount.add(convert_rate(address(tokenSUSD), address(tokenCCrv), _amounts[5])); } if (_amounts[6] > 0) { // husd _shareAmount = _shareAmount.add(convert_rate(address(tokenHUSD), address(tokenCCrv), _amounts[6])); } return _shareAmount; } function calc_token_amount_withdraw(uint _shares, address _output) external override view returns (uint _outputAmount) { for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_shares, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(token3Crv)) { _outputAmount = _convert_ccrv_to_3crv_rate(_shares); // CCrv -> DAI -> 3Crv } else if (_output == address(tokenUSDT)) { uint _daiAmount = depositCompound.calc_withdraw_one_coin(_shares, 0); // CCrv -> DAI _outputAmount = stableSwap3Pool.get_dy(int128(0), int128(2), _daiAmount); // DAI -> USDT } else if (_output == address(tokenBUSD)) { uint _daiAmount = depositCompound.calc_withdraw_one_coin(_shares, 0); // CCrv -> DAI _outputAmount = stableSwapBUSD.get_dy_underlying(int128(0), int128(3), _daiAmount); // DAI -> BUSD } else if (_output == address(tokenSUSD)) { uint _daiAmount = depositCompound.calc_withdraw_one_coin(_shares, 0); // CCrv -> DAI _outputAmount = stableSwapSUSD.get_dy_underlying(int128(0), int128(3), _daiAmount); // DAI -> SUSD } else if (_output == address(tokenHUSD)) { uint _3crvAmount = _convert_ccrv_to_3crv_rate(_shares); // CCrv -> DAI -> 3Crv _outputAmount = stableSwapHUSD.get_dy(int128(1), int128(0), _3crvAmount); // 3Crv -> HUSD } if (_outputAmount > 0) { uint _slippage = _outputAmount.mul(vaultMaster.slippage(_output)).div(10000); _outputAmount = _outputAmount.sub(_slippage); } } function convert(address _input, address _output, uint _inputAmount) external override returns (uint _outputAmount) { require(vaultMaster.isVault(msg.sender) || vaultMaster.isController(msg.sender) || msg.sender == governance, "!(governance||vault||controller)"); if (_output == address(tokenCCrv)) { // convert to CCrv uint[2] memory amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { amounts[i] = _inputAmount; uint _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); uint _after = tokenCCrv.balanceOf(address(this)); _outputAmount = _after.sub(_before); tokenCCrv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } } if (_input == address(token3Crv)) { _outputAmount = _convert_3crv_to_shares(_inputAmount); tokenCCrv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_input == address(tokenUSDT)) { _outputAmount = _convert_usdt_to_shares(_inputAmount); tokenCCrv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_input == address(tokenBUSD)) { _outputAmount = _convert_busd_to_shares(_inputAmount); tokenCCrv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_input == address(tokenSUSD)) { _outputAmount = _convert_susd_to_shares(_inputAmount); tokenCCrv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_input == address(tokenHUSD)) { _outputAmount = _convert_husd_to_shares(_inputAmount); tokenCCrv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } } else if (_input == address(tokenCCrv)) { // convert from CCrv for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { uint _before = cpoolTokens[i].balanceOf(address(this)); depositCompound.remove_liquidity_one_coin(_inputAmount, i, 1); uint _after = cpoolTokens[i].balanceOf(address(this)); _outputAmount = _after.sub(_before); cpoolTokens[i].safeTransfer(msg.sender, _outputAmount); return _outputAmount; } } if (_output == address(token3Crv)) { // remove CCrv to DAI uint[3] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); depositCompound.remove_liquidity_one_coin(_inputAmount, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to 3pool to get back 3Crv _before = token3Crv.balanceOf(address(this)); stableSwap3Pool.add_liquidity(amounts, 1); _after = token3Crv.balanceOf(address(this)); _outputAmount = _after.sub(_before); token3Crv.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_output == address(tokenUSDT)) { // remove CCrv to DAI uint _before = cpoolTokens[0].balanceOf(address(this)); depositCompound.remove_liquidity_one_coin(_inputAmount, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); _outputAmount = _after.sub(_before); // convert DAI to USDT _before = tokenUSDT.balanceOf(address(this)); stableSwap3Pool.exchange(int128(0), int128(2), _outputAmount, 1); _after = tokenUSDT.balanceOf(address(this)); _outputAmount = _after.sub(_before); tokenUSDT.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_output == address(tokenBUSD)) { // remove CCrv to DAI uint _before = cpoolTokens[0].balanceOf(address(this)); depositCompound.remove_liquidity_one_coin(_inputAmount, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); _outputAmount = _after.sub(_before); // convert DAI to BUSD _before = tokenBUSD.balanceOf(address(this)); stableSwapBUSD.exchange_underlying(int128(0), int128(3), _outputAmount, 1); _after = tokenBUSD.balanceOf(address(this)); _outputAmount = _after.sub(_before); tokenBUSD.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_output == address(tokenSUSD)) { // remove CCrv to DAI uint _before = cpoolTokens[0].balanceOf(address(this)); depositCompound.remove_liquidity_one_coin(_inputAmount, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); _outputAmount = _after.sub(_before); // convert DAI to SUSD _before = tokenSUSD.balanceOf(address(this)); stableSwapSUSD.exchange_underlying(int128(0), int128(3), _outputAmount, 1); _after = tokenSUSD.balanceOf(address(this)); _outputAmount = _after.sub(_before); tokenSUSD.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } if (_output == address(tokenHUSD)) { _outputAmount = _convert_shares_to_husd(_inputAmount); tokenHUSD.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } } return 0; } function convertAll(uint[] calldata) external override returns (uint) { revert("Not implemented"); } // @dev convert from USDC to cUSDC (via DAI) function _convert_underlying_to_ctoken(CTokenInterface ctoken, uint _amount) internal view returns (uint _outputAmount) { _outputAmount = _amount.mul(10 ** 18).div(ctoken.exchangeRateStored()); } // @dev convert from 3Crv to CCrv (via DAI) function _convert_3crv_to_shares(uint _3crv) internal returns (uint _shares) { // convert to DAI uint[2] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); stableSwap3Pool.remove_liquidity_one_coin(_3crv, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); } // @dev convert from USDT to CCrv (via DAI) function _convert_usdt_to_shares(uint _usdt) internal returns (uint _shares) { // convert to DAI uint[2] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); stableSwap3Pool.exchange(2, 0, _usdt, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); } // @dev convert from BUSD to CCrv (via DAI) function _convert_busd_to_shares(uint _busd) internal returns (uint _shares) { // convert to DAI uint[2] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); stableSwapBUSD.exchange_underlying(3, 0, _busd, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); } // @dev convert from SUSD to CCrv (via DAI) function _convert_susd_to_shares(uint _amount) internal returns (uint _shares) { // convert to DAI uint[2] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); stableSwapSUSD.exchange_underlying(int128(3), int128(0), _amount, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); } // @dev convert from HUSD to CCrv (HUSD -> 3Crv -> DAI -> CCrv) function _convert_husd_to_shares(uint _amount) internal returns (uint _shares) { // convert to 3Crv uint _before = token3Crv.balanceOf(address(this)); stableSwapHUSD.exchange(int128(0), int128(1), _amount, 1); uint _after = token3Crv.balanceOf(address(this)); _amount = _after.sub(_before); // convert 3Crv to DAI uint[2] memory amounts; _before = cpoolTokens[0].balanceOf(address(this)); stableSwap3Pool.remove_liquidity_one_coin(_amount, 0, 1); _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); } // @dev convert from CCrv to HUSD (CCrv -> DAI -> 3Crv -> HUSD) function _convert_shares_to_husd(uint _amount) internal returns (uint _husd) { // convert to DAI uint[3] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); depositCompound.remove_liquidity_one_coin(_amount, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to 3pool to get back 3Crv _before = token3Crv.balanceOf(address(this)); stableSwap3Pool.add_liquidity(amounts, 1); _after = token3Crv.balanceOf(address(this)); _amount = _after.sub(_before); // convert 3Crv to HUSD _before = tokenHUSD.balanceOf(address(this)); stableSwapHUSD.exchange(int128(1), int128(0), _amount, 1); _after = tokenHUSD.balanceOf(address(this)); _husd = _after.sub(_before); } function governanceRecoverUnsupported(IERC20 _token, uint _amount, address _to) external { require(msg.sender == governance, "!governance"); _token.transfer(_to, _amount); } }
Supported Pool Tokens: 0. 3pool [DAI, USDC, USDT] 1. BUSD [(y)DAI, (y)USDC, (y)USDT, (y)BUSD] 2. sUSD [DAI, USDC, USDT, sUSD] 3. husd [HUSD, 3pool] 4. Compound [(c)DAI, (c)USDC] 5. Y [(y)DAI, (y)USDC, (y)USDT, (y)TUSD] 6. Swerve [(y)DAI...(y)TUSD] stableSwapUSD: 0. stableSwap3Pool, 1. stableSwapBUSD, 2. stableSwapSUSD, 3. stableSwapHUSD, 4. stableSwapCompound
contract StableSwapCompoundConverter is IMultiVaultConverter { using SafeMath for uint; using SafeERC20 for IERC20; CTokenInterface[2] public cpoolCTokens; IERC20 public tokenUSDT; address public governance; IStableSwap3Pool public stableSwap3Pool; IStableSwapBUSD public stableSwapBUSD; IStableSwapSUSD public stableSwapSUSD; IStableSwapHUSD public stableSwapHUSD; IStableSwapCompound public stableSwapCompound; IDepositCompound public depositCompound; IValueVaultMaster public vaultMaster; constructor (IERC20 _tokenDAI, IERC20 _tokenUSDC, IERC20 _tokenUSDT, IERC20 _token3Crv, IERC20 _tokenBUSD, IERC20 _tokenSUSD, IERC20 _tokenHUSD, IERC20 _tokenCCrv, CTokenInterface _tokenCDAI, CTokenInterface _tokenCUSDC, address[] memory _stableSwapUSD, IDepositCompound _depositCompound, IValueVaultMaster _vaultMaster) public { cpoolTokens[0] = _tokenDAI; cpoolTokens[1] = _tokenUSDC; tokenUSDT = _tokenUSDT; tokenBUSD = _tokenBUSD; token3Crv = _token3Crv; tokenSUSD = _tokenSUSD; tokenHUSD = _tokenHUSD; tokenCCrv = _tokenCCrv; cpoolCTokens[0] = _tokenCDAI; cpoolCTokens[1] = _tokenCUSDC; stableSwap3Pool = IStableSwap3Pool(_stableSwapUSD[0]); stableSwapBUSD = IStableSwapBUSD(_stableSwapUSD[1]); stableSwapSUSD = IStableSwapSUSD(_stableSwapUSD[2]); stableSwapHUSD = IStableSwapHUSD(_stableSwapUSD[3]); stableSwapCompound = IStableSwapCompound(_stableSwapUSD[4]); depositCompound = _depositCompound; cpoolTokens[0].safeApprove(address(stableSwap3Pool), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwap3Pool), type(uint256).max); tokenUSDT.safeApprove(address(stableSwap3Pool), type(uint256).max); token3Crv.safeApprove(address(stableSwap3Pool), type(uint256).max); cpoolTokens[0].safeApprove(address(stableSwapBUSD), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwapBUSD), type(uint256).max); tokenUSDT.safeApprove(address(stableSwapBUSD), type(uint256).max); tokenBUSD.safeApprove(address(stableSwapBUSD), type(uint256).max); cpoolTokens[0].safeApprove(address(stableSwapSUSD), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwapSUSD), type(uint256).max); tokenUSDT.safeApprove(address(stableSwapSUSD), type(uint256).max); tokenSUSD.safeApprove(address(stableSwapSUSD), type(uint256).max); token3Crv.safeApprove(address(stableSwapHUSD), type(uint256).max); tokenHUSD.safeApprove(address(stableSwapHUSD), type(uint256).max); cpoolTokens[0].safeApprove(address(stableSwapCompound), type(uint256).max); cpoolTokens[1].safeApprove(address(stableSwapCompound), type(uint256).max); tokenCCrv.safeApprove(address(stableSwapCompound), type(uint256).max); cpoolTokens[0].safeApprove(address(depositCompound), type(uint256).max); cpoolTokens[1].safeApprove(address(depositCompound), type(uint256).max); tokenCCrv.safeApprove(address(depositCompound), type(uint256).max); vaultMaster = _vaultMaster; governance = msg.sender; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setVaultMaster(IValueVaultMaster _vaultMaster) external { require(msg.sender == governance, "!governance"); vaultMaster = _vaultMaster; } function approveForSpender(IERC20 _token, address _spender, uint _amount) external { require(msg.sender == governance, "!governance"); _token.safeApprove(_spender, _amount); } function setDefaultSlippage(uint _defaultSlippage) external { require(msg.sender == governance, "!governance"); require(_defaultSlippage <= 100, "_defaultSlippage>1%"); defaultSlippage = _defaultSlippage; } function token() external override returns (address) { return address(tokenCCrv); } function get_virtual_price() external override view returns (uint) { return stableSwapCompound.get_virtual_price(); } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } function convert_rate(address _input, address _output, uint _inputAmount) public override view returns (uint _outputAmount) { if (_inputAmount == 0) return 0; uint[2] memory _amounts; for (uint8 i = 0; i < 2; i++) { if (_input == address(cpoolTokens[i])) { _amounts[i] = _convert_underlying_to_ctoken(cpoolCTokens[i], _inputAmount); _outputAmount = stableSwapCompound.calc_token_amount(_amounts, true); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_input == address(tokenUSDT)) { } if (_input == address(tokenBUSD)) { } if (_input == address(tokenSUSD)) { } if (_input == address(tokenHUSD)) { } if (_input == address(token3Crv)) { } for (uint8 i = 0; i < 2; i++) { if (_output == address(cpoolTokens[i])) { _outputAmount = depositCompound.calc_withdraw_one_coin(_inputAmount, i); return _outputAmount.mul(10000 - defaultSlippage).div(10000); } } if (_output == address(tokenUSDT)) { } if (_output == address(tokenBUSD)) { } if (_output == address(tokenSUSD)) { } if (_output == address(tokenHUSD)) { } } if (_outputAmount > 0) { uint _slippage = _outputAmount.mul(vaultMaster.convertSlippage(_input, _output)).div(10000); _outputAmount = _outputAmount.sub(_slippage); } }
7,006,520
[ 1, 7223, 8828, 13899, 30, 374, 18, 890, 6011, 306, 9793, 45, 16, 11836, 5528, 16, 11836, 9081, 65, 404, 18, 605, 3378, 40, 306, 12, 93, 13, 9793, 45, 16, 261, 93, 13, 3378, 5528, 16, 261, 93, 13, 3378, 9081, 16, 261, 93, 13, 3000, 9903, 65, 576, 18, 272, 3378, 40, 306, 9793, 45, 16, 11836, 5528, 16, 11836, 9081, 16, 272, 3378, 40, 65, 890, 18, 366, 407, 72, 306, 44, 3378, 40, 16, 890, 6011, 65, 1059, 18, 21327, 306, 12, 71, 13, 9793, 45, 16, 261, 71, 13, 3378, 5528, 65, 1381, 18, 1624, 306, 12, 93, 13, 9793, 45, 16, 261, 93, 13, 3378, 5528, 16, 261, 93, 13, 3378, 9081, 16, 261, 93, 13, 56, 3378, 40, 65, 1666, 18, 348, 2051, 537, 306, 12, 93, 13, 9793, 45, 2777, 12, 93, 13, 56, 3378, 40, 65, 14114, 12521, 3378, 40, 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, 16351, 934, 429, 12521, 16835, 5072, 353, 467, 5002, 12003, 5072, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 385, 1345, 1358, 63, 22, 65, 1071, 3283, 1371, 1268, 3573, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 1147, 3378, 9081, 31, 203, 203, 203, 203, 203, 203, 203, 565, 1758, 1071, 314, 1643, 82, 1359, 31, 203, 203, 565, 467, 30915, 12521, 23, 2864, 1071, 14114, 12521, 23, 2864, 31, 203, 565, 467, 30915, 12521, 3000, 9903, 1071, 14114, 12521, 3000, 9903, 31, 203, 565, 467, 30915, 12521, 55, 3378, 40, 1071, 14114, 12521, 55, 3378, 40, 31, 203, 565, 467, 30915, 12521, 44, 3378, 40, 1071, 14114, 12521, 44, 3378, 40, 31, 203, 565, 467, 30915, 12521, 16835, 1071, 14114, 12521, 16835, 31, 203, 203, 565, 467, 758, 1724, 16835, 1071, 443, 1724, 16835, 31, 203, 203, 565, 467, 620, 12003, 7786, 1071, 9229, 7786, 31, 203, 203, 203, 565, 3885, 261, 45, 654, 39, 3462, 389, 2316, 9793, 45, 16, 467, 654, 39, 3462, 389, 2316, 3378, 5528, 16, 467, 654, 39, 3462, 389, 2316, 3378, 9081, 16, 467, 654, 39, 3462, 389, 2316, 23, 39, 4962, 16, 203, 3639, 467, 654, 39, 3462, 389, 2316, 3000, 9903, 16, 467, 654, 39, 3462, 389, 2316, 55, 3378, 40, 16, 467, 654, 39, 3462, 389, 2316, 44, 3378, 40, 16, 203, 3639, 467, 654, 39, 3462, 389, 2316, 6743, 4962, 16, 385, 1345, 2 ]
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "./interfaces.sol"; import "./Verification.sol"; contract Sector is ISector { /// The reward queue. struct Queue { mapping(uint256 => uint256) q; uint256 start; uint256 len; uint256 total; uint256 maxSize; } Queue _rewards; /// The deposit of the sector struct Deposit{ uint256 shard; uint256 nShards; } Deposit _deposit; address payable public override owner; bytes28 public override afid; ITurboFil public turboFil; // @notice The sector has been punished and should not be used any more bool public dead; // @notice the latest verification for this sector Verification public verification; /// @notice VerificationResult event will be emitted every time a verification is settled for this sector. /// @param seed the afid of the seed used in this verification /// @param result whether the verification pass or fail /// @param reward the amount of TFC the sector get as reward in this verification (if pass) /// @param punish the amount of TFC the sector is punished in this verification (if fail) event VerificationResult(bytes28 seed, bool result, uint256 reward, uint256 punish); modifier onlyTurboFil { require(msg.sender == address(turboFil), "Sector: can only be called by TurboFil"); _; } modifier onlyOwner { require(msg.sender == owner, "Sector: can only be called by owner"); _; } modifier onlyVerification { require(address(verification) == msg.sender, "Sector: can only be called by correct verification"); _; } constructor(address payable owner_, bytes28 afid_, uint256 lockPeriod_) payable { turboFil = ITurboFil(msg.sender); owner = owner_; afid = afid_; uint256 shard = msg.value / lockPeriod_; _deposit.shard = shard; _deposit.nShards = lockPeriod_; } function setVerification(address verification_) onlyTurboFil external { verification=Verification(verification_); } function verificationResult(bytes28 seed_, bool result_) onlyVerification payable external override { uint256 reward; uint256 pun; if (result_){ reward = msg.value; _reward(reward); } else { pun = punish(); payable(address(turboFil)).transfer(msg.value); } emit VerificationResult(seed_, result_, reward, pun); } function _reward(uint256 amount_) internal returns (uint256 unlocked) { if (_deposit.nShards > 0) { unlocked += _deposit.shard; _deposit.nShards--; _rewards.maxSize++; } _rewards.q[_rewards.start+_rewards.len] = amount_; _rewards.total += amount_; if (_rewards.len < _rewards.maxSize) { _rewards.len += 1; } else { unlocked += _rewards.q[_rewards.start]; _rewards.start += 1; _rewards.total -= unlocked; } if (unlocked > 0){ owner.transfer(unlocked); } } // @dev Punish this sector. Only turboFil and verification contract can call this function. function punish() public returns (uint256 amount) { require(msg.sender == address(turboFil) || msg.sender == address(verification), "Sector: caller does not have privilege to punish"); amount += _deposit.shard * _deposit.nShards; amount += _rewards.total; if(amount > 0){ payable(address(turboFil)).transfer(amount); } dead = true; } /* View functions */ function lockedTFC() view public returns(uint256) { return _rewards.total + _deposit.shard * _deposit.nShards; } }
@notice The sector has been punished and should not be used any more
bool public dead;
1,052,577
[ 1, 1986, 16323, 711, 2118, 293, 318, 5992, 471, 1410, 486, 506, 1399, 1281, 1898, 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, 1426, 1071, 8363, 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, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-06 */ // SPDX-License-Identifier: MIXED // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT // Based on code and smartness by Ross Campbell and Keno // Uses immutable to store the domain separator to reduce gas usage // If the chain id changes due to a fork, the forked chain will calculate on the fly. pragma solidity 0.6.12; // solhint-disable no-inline-assembly contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this) ) ); } constructor() public { uint256 chainId; assembly {chainId := chainid()} _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash ) ); } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; } abstract contract ERC20 is IERC20, Domain { /// @notice owner > balance mapping. mapping(address => uint256) public override balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public override allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= amount, "ERC20: allowance too low"); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) == owner_, "ERC20: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } contract ERC20WithSupply is IERC20, ERC20 { uint256 public override totalSupply; function _mint(address user, uint256 amount) private { uint256 newTotalSupply = totalSupply + amount; require(newTotalSupply >= totalSupply, "Mint overflow"); totalSupply = newTotalSupply; balanceOf[user] += amount; } function _burn(address user, uint256 amount) private { require(balanceOf[user] >= amount, "Burn too much"); totalSupply -= amount; balanceOf[user] -= amount; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IMasterContract { /// @notice Init function that gets called from `BoringFactory.deploy`. /// Also kown as the constructor for cloned contracts. /// Any ETH send to `BoringFactory.deploy` ends up here. /// @param data Can be abi encoded arguments or anything else. function init(bytes calldata data) external payable; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; struct Rebase { uint128 elastic; uint128 base; } /// @notice A rebasing library using overflow-/underflow-safe math. library RebaseLibrary { using BoringMath for uint256; using BoringMath128 for uint128; /// @notice Calculates the base value in relationship to `elastic` and `total`. function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mul(total.base) / total.elastic; if (roundUp && base.mul(total.elastic) / total.base < elastic) { base = base.add(1); } } } /// @notice Calculates the elastic value in relationship to `base` and `total`. function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mul(total.elastic) / total.base; if (roundUp && elastic.mul(total.base) / total.elastic < base) { elastic = elastic.add(1); } } } /// @notice Add `elastic` to `total` and doubles `total.base`. /// @return (Rebase) The new total. /// @return base in relationship to `elastic`. function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return (total, base); } /// @notice Sub `base` from `total` and update `total.elastic`. /// @return (Rebase) The new total. /// @return elastic in relationship to `base`. function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return (total, elastic); } /// @notice Add `elastic` and `base` to `total`. function add( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return total; } /// @notice Subtract `elastic` and `base` to `total`. function sub( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return total; } /// @notice Add `elastic` to `total` and update storage. /// @return newElastic Returns updated `elastic`. function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.add(elastic.to128()); } /// @notice Subtract `elastic` from `total` and update storage. /// @return newElastic Returns updated `elastic`. function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.sub(elastic.to128()); } } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IBatchFlashBorrower { function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IFlashBorrower { function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IStrategy { // Send the assets to the Strategy and call skim to invest them function skim(uint256 amount) external; // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address sender) external returns (int256 amountAdded); // Withdraw assets. The returned amount can differ from the requested amount due to rounding. // The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for. function withdraw(uint256 amount) external returns (uint256 actualAmount); // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external returns (int256 amountAdded); } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBentoBoxV1 { event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress); event LogDeposit(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogFlashLoan(address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver); event LogRegisterProtocol(address indexed protocol); event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved); event LogStrategyDivest(address indexed token, uint256 amount); event LogStrategyInvest(address indexed token, uint256 amount); event LogStrategyLoss(address indexed token, uint256 amount); event LogStrategyProfit(address indexed token, uint256 amount); event LogStrategyQueued(address indexed token, address indexed strategy); event LogStrategySet(address indexed token, address indexed strategy); event LogStrategyTargetPercentage(address indexed token, uint256 targetPercentage); event LogTransfer(address indexed token, address indexed from, address indexed to, uint256 share); event LogWhiteListMasterContract(address indexed masterContract, bool approved); event LogWithdraw(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function balanceOf(IERC20, address) external view returns (uint256); function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results); function batchFlashLoan(IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data) external; function claimOwnership() external; function deploy(address masterContract, bytes calldata data, bool useCreate2) external payable; function deposit(IERC20 token_, address from, address to, uint256 amount, uint256 share) external payable returns (uint256 amountOut, uint256 shareOut); function flashLoan(IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data) external; function harvest(IERC20 token, bool balance, uint256 maxChangeAmount) external; function masterContractApproved(address, address) external view returns (bool); function masterContractOf(address) external view returns (address); function nonces(address) external view returns (uint256); function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingStrategy(IERC20) external view returns (IStrategy); function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function registerProtocol() external; function setMasterContractApproval(address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) external; function setStrategy(IERC20 token, IStrategy newStrategy) external; function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external; function strategy(IERC20) external view returns (IStrategy); function strategyData(IERC20) external view returns (uint64 strategyStartDate, uint64 targetPercentage, uint128 balance); function toAmount(IERC20 token, uint256 share, bool roundUp) external view returns (uint256 amount); function toShare(IERC20 token, uint256 amount, bool roundUp) external view returns (uint256 share); function totals(IERC20) external view returns (Rebase memory totals_); function transfer(IERC20 token, address from, address to, uint256 share) external; function transferMultiple(IERC20 token, address from, address[] calldata tos, uint256[] calldata shares) external; function transferOwnership(address newOwner, bool direct, bool renounce) external; function whitelistMasterContract(address masterContract, bool approved) external; function whitelistedMasterContracts(address) external view returns (bool); function withdraw(IERC20 token_, address from, address to, uint256 amount, uint256 share) external returns (uint256 amountOut, uint256 shareOut); } // File contracts/MagicInternetMoney.sol // License-Identifier: MIT // Magic Internet Money // ███╗ ███╗██╗███╗ ███╗ // ████╗ ████║██║████╗ ████║ // ██╔████╔██║██║██╔████╔██║ // ██║╚██╔╝██║██║██║╚██╔╝██║ // ██║ ╚═╝ ██║██║██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ // BoringCrypto, 0xMerlin pragma solidity 0.6.12; /// @title Cauldron /// @dev This contract allows contract calls to any contract (except BentoBox) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract MagicInternetMoney is ERC20, BoringOwnable { using BoringMath for uint256; // ERC20 'variables' string public constant symbol = "MIM"; string public constant name = "Magic Internet Money"; uint8 public constant decimals = 18; uint256 public override totalSupply; struct Minting { uint128 time; uint128 amount; } Minting public lastMint; uint256 private constant MINTING_PERIOD = 24 hours; uint256 private constant MINTING_INCREASE = 15000; uint256 private constant MINTING_PRECISION = 1e5; function mint(address to, uint256 amount) public onlyOwner { require(to != address(0), "MIM: no mint to zero address"); // Limits the amount minted per period to a convergence function, with the period duration restarting on every mint uint256 totalMintedAmount = uint256(lastMint.time < block.timestamp - MINTING_PERIOD ? 0 : lastMint.amount).add(amount); require(totalSupply == 0 || totalSupply.mul(MINTING_INCREASE) / MINTING_PRECISION >= totalMintedAmount); lastMint.time = block.timestamp.to128(); lastMint.amount = totalMintedAmount.to128(); totalSupply = totalSupply + amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } function mintToBentoBox(address clone, uint256 amount, IBentoBoxV1 bentoBox) public onlyOwner { mint(address(bentoBox), amount); bentoBox.deposit(IERC20(address(this)), address(bentoBox), clone, amount, 0); } function burn(uint256 amount) public { require(amount <= balanceOf[msg.sender], "MIM: not enough"); balanceOf[msg.sender] -= amount; totalSupply -= amount; emit Transfer(msg.sender, address(0), amount); } } // File contracts/interfaces/IOracle.sol // License-Identifier: MIT pragma solidity 0.6.12; interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); } // File contracts/interfaces/ISwapper.sol // License-Identifier: MIT pragma solidity 0.6.12; interface ISwapper { /// @notice Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for at least 'amountToMin' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Returns the amount of tokens 'to' transferred to BentoBox. /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) external returns (uint256 extraShare, uint256 shareReturned); /// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom), /// this should be less than or equal to amountFromMax. /// Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for exactly 'exactAmountTo' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Transfers allocated, but unused 'from' tokens within the BentoBox to 'refundTo' (amountFromMax - amountFrom). /// Returns the amount of 'from' tokens withdrawn from BentoBox (amountFrom). /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) external returns (uint256 shareUsed, uint256 shareReturned); } // File contracts/CauldronV2.sol // License-Identifier: UNLICENSED // Cauldron // ( ( ( // )\ ) ( )\ )\ ) ( // (((_) ( /( ))\ ((_)(()/( )( ( ( // )\___ )(_)) /((_) _ ((_))(()\ )\ )\ ) // ((/ __|((_)_ (_))( | | _| | ((_) ((_) _(_/( // | (__ / _` || || || |/ _` | | '_|/ _ \| ' \)) // \___|\__,_| \_,_||_|\__,_| |_| \___/|_||_| // Copyright (c) 2021 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // Special thanks to: // @0xKeno - for all his invaluable contributions // @burger_crypto - for the idea of trying to let the LPs benefit from liquidations pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly /// @title Cauldron /// @dev This contract allows contract calls to any contract (except BentoBox) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract CauldronV2Flat is BoringOwnable, IMasterContract { using BoringMath for uint256; using BoringMath128 for uint128; using RebaseLibrary for Rebase; using BoringERC20 for IERC20; event LogExchangeRate(uint256 rate); event LogAccrue(uint128 accruedAmount); event LogAddCollateral(address indexed from, address indexed to, uint256 share); event LogRemoveCollateral(address indexed from, address indexed to, uint256 share); event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part); event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part); event LogFeeTo(address indexed newFeeTo); event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction); // Immutables (for MasterContract and all clones) IBentoBoxV1 public immutable bentoBox; CauldronV2Flat public immutable masterContract; IERC20 public immutable magicInternetMoney; // MasterContract variables address public feeTo; // Per clone variables // Clone init settings IERC20 public collateral; IOracle public oracle; bytes public oracleData; // Total amounts uint256 public totalCollateralShare; // Total collateral supplied Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers // User balances mapping(address => uint256) public userCollateralShare; mapping(address => uint256) public userBorrowPart; /// @notice Exchange and interest rate tracking. /// This is 'cached' here because calls to Oracles can be very expensive. uint256 public exchangeRate; struct AccrueInfo { uint64 lastAccrued; uint128 feesEarned; uint64 INTEREST_PER_SECOND; } AccrueInfo public accrueInfo; // Settings uint256 public COLLATERIZATION_RATE; uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math) uint256 private constant EXCHANGE_RATE_PRECISION = 1e18; uint256 public LIQUIDATION_MULTIPLIER; uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5; uint256 public BORROW_OPENING_FEE; uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5; uint256 private constant DISTRIBUTION_PART = 10; uint256 private constant DISTRIBUTION_PRECISION = 100; /// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`. constructor(IBentoBoxV1 bentoBox_, IERC20 magicInternetMoney_) public { bentoBox = bentoBox_; magicInternetMoney = magicInternetMoney_; masterContract = this; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) function init(bytes calldata data) public payable override { require(address(collateral) == address(0), "Cauldron: already initialized"); (collateral, oracle, oracleData, accrueInfo.INTEREST_PER_SECOND, LIQUIDATION_MULTIPLIER, COLLATERIZATION_RATE, BORROW_OPENING_FEE) = abi.decode(data, (IERC20, IOracle, bytes, uint64, uint256, uint256, uint256)); require(address(collateral) != address(0), "Cauldron: bad pair"); } /// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees. function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; // Number of seconds since accrue was called uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { accrueInfo = _accrueInfo; return; } // Accrue interest uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128(); _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } /// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`. /// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls. function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) { // accrue must have already been called! uint256 borrowPart = userBorrowPart[user]; if (borrowPart == 0) return true; uint256 collateralShare = userCollateralShare[user]; if (collateralShare == 0) return false; Rebase memory _totalBorrow = totalBorrow; return bentoBox.toAmount( collateral, collateralShare.mul(EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION).mul(COLLATERIZATION_RATE), false ) >= // Moved exchangeRate here instead of dividing the other side to preserve more precision borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base; } /// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body. modifier solvent() { _; require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } /// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset. /// This function is supposed to be invoked if needed because Oracle queries can be expensive. /// @return updated True if `exchangeRate` was updated. /// @return rate The new exchange rate. function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } } /// @dev Helper function to move tokens. /// @param token The ERC-20 token. /// @param share The amount in shares to add. /// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True. /// Only used for accounting checks. /// @param skim If True, only does a balance check on this contract. /// False if tokens from msg.sender in `bentoBox` should be transferred. function _addTokens( IERC20 token, uint256 share, uint256 total, bool skim ) internal { if (skim) { require(share <= bentoBox.balanceOf(token, address(this)).sub(total), "Cauldron: Skim too much"); } else { bentoBox.transfer(token, msg.sender, address(this), share); } } /// @notice Adds `collateral` from msg.sender to the account `to`. /// @param to The receiver of the tokens. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.x /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param share The amount of shares to add for `to`. function addCollateral( address to, bool skim, uint256 share ) public { userCollateralShare[to] = userCollateralShare[to].add(share); uint256 oldTotalCollateralShare = totalCollateralShare; totalCollateralShare = oldTotalCollateralShare.add(share); _addTokens(collateral, share, oldTotalCollateralShare, skim); emit LogAddCollateral(skim ? address(bentoBox) : msg.sender, to, share); } /// @dev Concrete implementation of `removeCollateral`. function _removeCollateral(address to, uint256 share) internal { userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(share); totalCollateralShare = totalCollateralShare.sub(share); emit LogRemoveCollateral(msg.sender, to, share); bentoBox.transfer(collateral, address(this), to, share); } /// @notice Removes `share` amount of collateral and transfers it to `to`. /// @param to The receiver of the shares. /// @param share Amount of shares to remove. function removeCollateral(address to, uint256 share) public solvent { // accrue must be called because we check solvency accrue(); _removeCollateral(to, share); } /// @dev Concrete implementation of `borrow`. function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount)); userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part); // As long as there are tokens on this contract you can 'mint'... this enables limiting borrows share = bentoBox.toShare(magicInternetMoney, amount, false); bentoBox.transfer(magicInternetMoney, address(this), to, share); emit LogBorrow(msg.sender, to, amount.add(feeAmount), part); } /// @notice Sender borrows `amount` and transfers it to `to`. /// @return part Total part of the debt held by borrowers. /// @return share Total amount in shares borrowed. function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); } /// @dev Concrete implementation of `repay`. function _repay( address to, bool skim, uint256 part ) internal returns (uint256 amount) { (totalBorrow, amount) = totalBorrow.sub(part, true); userBorrowPart[to] = userBorrowPart[to].sub(part); uint256 share = bentoBox.toShare(magicInternetMoney, amount, true); bentoBox.transfer(magicInternetMoney, skim ? address(bentoBox) : msg.sender, address(this), share); emit LogRepay(skim ? address(bentoBox) : msg.sender, to, amount, part); } /// @notice Repays a loan. /// @param to Address of the user this payment should go. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param part The amount to repay. See `userBorrowPart`. /// @return amount The total amount repayed. function repay( address to, bool skim, uint256 part ) public returns (uint256 amount) { accrue(); amount = _repay(to, skim, part); } // Functions that need accrue to be called uint8 internal constant ACTION_REPAY = 2; uint8 internal constant ACTION_REMOVE_COLLATERAL = 4; uint8 internal constant ACTION_BORROW = 5; uint8 internal constant ACTION_GET_REPAY_SHARE = 6; uint8 internal constant ACTION_GET_REPAY_PART = 7; uint8 internal constant ACTION_ACCRUE = 8; // Functions that don't need accrue to be called uint8 internal constant ACTION_ADD_COLLATERAL = 10; uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11; // Function on BentoBox uint8 internal constant ACTION_BENTO_DEPOSIT = 20; uint8 internal constant ACTION_BENTO_WITHDRAW = 21; uint8 internal constant ACTION_BENTO_TRANSFER = 22; uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23; uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24; // Any external call (except to BentoBox) uint8 internal constant ACTION_CALL = 30; int256 internal constant USE_VALUE1 = -1; int256 internal constant USE_VALUE2 = -2; /// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`. function _num( int256 inNum, uint256 value1, uint256 value2 ) internal pure returns (uint256 outNum) { outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2); } /// @dev Helper function for depositing into `bentoBox`. function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors share = int256(_num(share, value1, value2)); return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share)); } /// @dev Helper function to withdraw from the `bentoBox`. function _bentoWithdraw( bytes memory data, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); return bentoBox.withdraw(token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2)); } /// @dev Helper function to perform a contract call and eventually extracting revert messages on failure. /// Calls to `bentoBox` are not allowed for obvious security reasons. /// This also means that calls made from this contract shall *not* be trusted. function _call( uint256 value, bytes memory data, uint256 value1, uint256 value2 ) internal returns (bytes memory, uint8) { (address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) = abi.decode(data, (address, bytes, bool, bool, uint8)); if (useValue1 && !useValue2) { callData = abi.encodePacked(callData, value1); } else if (!useValue1 && useValue2) { callData = abi.encodePacked(callData, value2); } else if (useValue1 && useValue2) { callData = abi.encodePacked(callData, value1, value2); } require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call"); (bool success, bytes memory returnData) = callee.call{value: value}(callData); require(success, "Cauldron: call failed"); return (returnData, returnValues); } struct CookStatus { bool needsSolvencyCheck; bool hasAccrued; } /// @notice Executes a set of actions and allows composability (contract calls) to other contracts. /// @param actions An array with a sequence of actions to execute (see ACTION_ declarations). /// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions. /// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`. /// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments. /// @return value1 May contain the first positioned return value of the last executed action (if applicable). /// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable). function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); } else if (action == ACTION_REPAY) { (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); } else if (action == ACTION_REMOVE_COLLATERAL) { (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_BORROW) { (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_UPDATE_EXCHANGE_RATE) { (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); } else if (action == ACTION_BENTO_SETAPPROVAL) { (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); } else if (action == ACTION_BENTO_DEPOSIT) { (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); } else if (action == ACTION_BENTO_WITHDRAW) { (value1, value2) = _bentoWithdraw(datas[i], value1, value2); } else if (action == ACTION_BENTO_TRANSFER) { (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); } else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) { (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); } else if (action == ACTION_CALL) { (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); } else if (returnValues == 2) { (value1, value2) = abi.decode(returnData, (uint256, uint256)); } } else if (action == ACTION_GET_REPAY_SHARE) { int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); } else if (action == ACTION_GET_REPAY_PART) { int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } /// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low. /// @param users An array of user addresses. /// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user. /// @param to Address of the receiver in open liquidations if `swapper` is zero. function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { // Oracle can fail but we still need to allow liquidations (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); // Keep totals allCollateralShare = allCollateralShare.add(collateralShare); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); // Apply a percentual fee share to sSpell holders { uint256 distributionAmount = (allBorrowAmount.mul(LIQUIDATION_MULTIPLIER) / LIQUIDATION_MULTIPLIER_PRECISION).sub(allBorrowAmount).mul(DISTRIBUTION_PART) / DISTRIBUTION_PRECISION; // Distribution Amount allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); // Swap using a swapper freely chosen by the caller // Open (flash) liquidation: get proceeds first and provide the borrow after bentoBox.transfer(collateral, address(this), to, allCollateralShare); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } /// @notice Withdraws the fees accumulated. function withdrawFees() public { accrue(); address _feeTo = masterContract.feeTo(); uint256 _feesEarned = accrueInfo.feesEarned; uint256 share = bentoBox.toShare(magicInternetMoney, _feesEarned, false); bentoBox.transfer(magicInternetMoney, address(this), _feeTo, share); accrueInfo.feesEarned = 0; emit LogWithdrawFees(_feeTo, _feesEarned); } /// @notice Sets the beneficiary of interest accrued. /// MasterContract Only Admin function. /// @param newFeeTo The address of the receiver. function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } /// @notice reduces the supply of MIM /// @param amount amount to reduce supply by function reduceSupply(uint256 amount) public { require(msg.sender == masterContract.owner(), "Caller is not the owner"); bentoBox.withdraw(magicInternetMoney, address(this), address(this), amount, 0); MagicInternetMoney(address(magicInternetMoney)).burn(amount); } }
Done this way to avoid stack too deep errors
amount = int256(_num(amount, value1, value2));
2,271,880
[ 1, 7387, 333, 4031, 358, 4543, 2110, 4885, 4608, 1334, 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, 3844, 273, 509, 5034, 24899, 2107, 12, 8949, 16, 460, 21, 16, 460, 22, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x078e77fC084f9267407848b1343E7F641c770918/sources/STBLBalancer_O.sol
Mainnet Factory Balancer
bPool = BFactory(0x8f7F78080219d4066A8036ccD30D588B416a40DB);
9,588,571
[ 1, 6376, 2758, 7822, 605, 5191, 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, 1377, 324, 2864, 273, 605, 1733, 12, 20, 92, 28, 74, 27, 42, 27, 3672, 31644, 3657, 72, 7132, 6028, 37, 3672, 5718, 952, 40, 5082, 40, 25, 5482, 38, 24, 2313, 69, 7132, 2290, 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 ]
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul // WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that // requires ABIEncoderV2. Exercise caution when calling that specific function. pragma experimental ABIEncoderV2; interface DharmaSmartWalletImplementationV1Interface { event CALLSUCCESS383( //inject NONSTANDARD NAMING bytes32 actionID, bool rolledBack, uint256 nonce, address to, bytes data, bytes returnData ); event CALLFAILURE442( //inject NONSTANDARD NAMING bytes32 actionID, uint256 nonce, address to, bytes data, string revertReason ); // ABIEncoderV2 uses an array of Calls for executing generic batch calls. struct Call { address to; bytes data; } // ABIEncoderV2 uses an array of CallReturns for handling generic batch calls. struct CallReturn { bool ok; bytes returnData; } function WITHDRAWETHER963( //inject NONSTANDARD NAMING uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function EXECUTEACTION770( //inject NONSTANDARD NAMING address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function RECOVER845(address newUserSigningKey) external; //inject NONSTANDARD NAMING function EXECUTEACTIONWITHATOMICBATCHCALLS418( //inject NONSTANDARD NAMING Call[] calldata calls, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool[] memory ok, bytes[] memory returnData); function GETNEXTGENERICACTIONID981( //inject NONSTANDARD NAMING address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function GETGENERICACTIONID781( //inject NONSTANDARD NAMING address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function GETNEXTGENERICATOMICBATCHACTIONID957( //inject NONSTANDARD NAMING Call[] calldata calls, uint256 minimumActionGas ) external view returns (bytes32 actionID); function GETGENERICATOMICBATCHACTIONID98( //inject NONSTANDARD NAMING Call[] calldata calls, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV3Interface { event CANCEL692(uint256 cancelledNonce); //inject NONSTANDARD NAMING event ETHWITHDRAWAL175(uint256 amount, address recipient); //inject NONSTANDARD NAMING } interface DharmaSmartWalletImplementationV4Interface { event ESCAPED27(); //inject NONSTANDARD NAMING function SETESCAPEHATCH554( //inject NONSTANDARD NAMING address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function REMOVEESCAPEHATCH653( //inject NONSTANDARD NAMING uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function PERMANENTLYDISABLEESCAPEHATCH796( //inject NONSTANDARD NAMING uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function ESCAPE232() external; //inject NONSTANDARD NAMING } interface DharmaSmartWalletImplementationV7Interface { // Fires when a new user signing key is set on the smart wallet. event NEWUSERSIGNINGKEY833(address userSigningKey); //inject NONSTANDARD NAMING // Fires when an error occurs as part of an attempted action. event EXTERNALERROR24(address indexed source, string revertReason); //inject NONSTANDARD NAMING // The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets. enum AssetType { DAI, USDC, ETH, SAI } // Actions, or protected methods (i.e. not deposits) each have an action type. enum ActionType { Cancel, SetUserSigningKey, Generic, GenericAtomicBatch, SAIWithdrawal, USDCWithdrawal, ETHWithdrawal, SetEscapeHatch, RemoveEscapeHatch, DisableEscapeHatch, DAIWithdrawal, SignatureVerification, TradeEthForDai, DAIBorrow, USDCBorrow } function INITIALIZE336(address userSigningKey) external; //inject NONSTANDARD NAMING function REPAYANDDEPOSIT967() external; //inject NONSTANDARD NAMING function WITHDRAWDAI449( //inject NONSTANDARD NAMING uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function WITHDRAWUSDC811( //inject NONSTANDARD NAMING uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function CANCEL991( //inject NONSTANDARD NAMING uint256 minimumActionGas, bytes calldata signature ) external; function SETUSERSIGNINGKEY240( //inject NONSTANDARD NAMING address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function MIGRATESAITODAI522() external; //inject NONSTANDARD NAMING function MIGRATECSAITODDAI208() external; //inject NONSTANDARD NAMING function MIGRATECDAITODDAI660() external; //inject NONSTANDARD NAMING function MIGRATECUSDCTODUSDC400() external; //inject NONSTANDARD NAMING function GETBALANCES53() external view returns ( //inject NONSTANDARD NAMING uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns zero ); function GETUSERSIGNINGKEY63() external view returns (address userSigningKey); //inject NONSTANDARD NAMING function GETNONCE95() external view returns (uint256 nonce); //inject NONSTANDARD NAMING function GETNEXTCUSTOMACTIONID792( //inject NONSTANDARD NAMING ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID); function GETCUSTOMACTIONID90( //inject NONSTANDARD NAMING ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function GETVERSION901() external pure returns (uint256 version); //inject NONSTANDARD NAMING } interface DharmaSmartWalletImplementationV8Interface { function TRADEETHFORDAIANDMINTDDAI339( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function GETNEXTETHFORDAIACTIONID361( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function GETETHFORDAIACTIONID368( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface ERC20Interface { function TRANSFER153(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function APPROVE270(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function BALANCEOF992(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE583( //inject NONSTANDARD NAMING address owner, address spender ) external view returns (uint256); } interface ERC1271Interface { function ISVALIDSIGNATURE229( //inject NONSTANDARD NAMING bytes calldata data, bytes calldata signature ) external view returns (bytes4 magicValue); } interface CTokenInterface { function REDEEM466(uint256 redeemAmount) external returns (uint256 err); //inject NONSTANDARD NAMING function TRANSFER153(address recipient, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE270(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function BALANCEOF992(address account) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE583(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING } interface DTokenInterface { // These external functions trigger accrual on the dToken and backing cToken. function MINT76(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING function REDEEM466(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING function REDEEMUNDERLYING215(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING // These external functions only trigger accrual on the dToken. function MINTVIACTOKEN796(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING // View and pure functions do not trigger accrual on the dToken or the cToken. function BALANCEOFUNDERLYING317(address account) external view returns (uint256 underlyingBalance); //inject NONSTANDARD NAMING } interface USDCV1Interface { function ISBLACKLISTED453(address _account) external view returns (bool); //inject NONSTANDARD NAMING function PAUSED117() external view returns (bool); //inject NONSTANDARD NAMING } interface DharmaKeyRegistryInterface { function GETKEY781() external view returns (address key); //inject NONSTANDARD NAMING } interface DharmaEscapeHatchRegistryInterface { function SETESCAPEHATCH554(address newEscapeHatch) external; //inject NONSTANDARD NAMING function REMOVEESCAPEHATCH653() external; //inject NONSTANDARD NAMING function PERMANENTLYDISABLEESCAPEHATCH796() external; //inject NONSTANDARD NAMING function GETESCAPEHATCH697() external view returns ( //inject NONSTANDARD NAMING bool exists, address escapeHatch ); } interface TradeHelperInterface { function TRADEETHFORDAI848( //inject NONSTANDARD NAMING uint256 daiExpected, address target, bytes calldata data ) external payable returns (uint256 daiReceived); } interface RevertReasonHelperInterface { function REASON113(uint256 code) external pure returns (string memory); //inject NONSTANDARD NAMING } interface EtherizedInterface { function TRIGGERETHERTRANSFER345( //inject NONSTANDARD NAMING address payable target, uint256 value ) external returns (bool success); } interface ConfigurationRegistryInterface { function GET761(bytes32 key) external view returns (bytes32 value); //inject NONSTANDARD NAMING } library Address { function ISCONTRACT235(address account) internal view returns (bool) { //inject NONSTANDARD NAMING uint256 size; assembly { size := extcodesize(account) } return size > 0; } } library ECDSA { function RECOVER845( //inject NONSTANDARD NAMING bytes32 hash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(hash, v, r, s); } function TOETHSIGNEDMESSAGEHASH603(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } contract Etherized is EtherizedInterface { address private constant _etherizer294 = address( //inject NONSTANDARD NAMING 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); function TRIGGERETHERTRANSFER345( //inject NONSTANDARD NAMING address payable target, uint256 amount ) external returns (bool success) { require(msg.sender == _etherizer294, "Etherized: only callable by Etherizer"); (success, ) = target.call.value(amount)(""); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } contract DharmaSmartWalletImplementationV11Staging is DharmaSmartWalletImplementationV1Interface, DharmaSmartWalletImplementationV3Interface, DharmaSmartWalletImplementationV4Interface, DharmaSmartWalletImplementationV7Interface, DharmaSmartWalletImplementationV8Interface, ERC1271Interface, Etherized { using Address for address; using ECDSA for bytes32; // WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS! // The user signing key associated with this account is in storage slot 0. // It is the core differentiator when it comes to the account in question. address private _userSigningKey; // The nonce associated with this account is in storage slot 1. Every time a // signature is submitted, it must have the appropriate nonce, and once it has // been accepted the nonce will be incremented. uint256 private _nonce; // The self-call context flag is in storage slot 2. Some protected functions // may only be called externally from calls originating from other methods on // this contract, which enables appropriate exception handling on reverts. // Any storage should only be set immediately preceding a self-call and should // be cleared upon entering the protected function being called. bytes4 internal _selfCallContext; // END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE! // The smart wallet version will be used when constructing valid signatures. uint256 internal constant _dharma_smart_wallet_version295 = 1011; //inject NONSTANDARD NAMING // DharmaKeyRegistryV2Staging holds a public key to verify meta-transactions. DharmaKeyRegistryInterface internal constant _dharma_key_registry438 = ( //inject NONSTANDARD NAMING DharmaKeyRegistryInterface(0x00000000006c7f32F0cD1eA4C1383558eb68802D) ); // Account recovery uses a hard-coded staging version of the recovery manager. address internal constant _account_recovery_manager816 = address( //inject NONSTANDARD NAMING 0x2a7E7718b755F9868E6B64DD18C6886707DD9c10 ); // Users can designate an "escape hatch" account with the ability to sweep all // funds from their smart wallet by using the Dharma Escape Hatch Registry. DharmaEscapeHatchRegistryInterface internal constant _escape_hatch_registry980 = ( //inject NONSTANDARD NAMING DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8) ); // Interface with dDai, dUSDC, Dai, USDC, Sai, cSai, cDai, cUSDC, & migrator. DTokenInterface internal constant _ddai406 = DTokenInterface( //inject NONSTANDARD NAMING 0x00000000001876eB1444c986fD502e618c587430 // mainnet ); DTokenInterface internal constant _dusdc174 = DTokenInterface( //inject NONSTANDARD NAMING 0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet ); ERC20Interface internal constant _dai860 = ERC20Interface( //inject NONSTANDARD NAMING 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _usdc146 = ERC20Interface( //inject NONSTANDARD NAMING 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); CTokenInterface internal constant _cdai443 = CTokenInterface( //inject NONSTANDARD NAMING 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 // mainnet ); CTokenInterface internal constant _cusdc481 = CTokenInterface( //inject NONSTANDARD NAMING 0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet ); // The "trade helper" facilitates Eth-to-Dai trades in an isolated context. TradeHelperInterface internal constant _trade_helper427 = TradeHelperInterface( //inject NONSTANDARD NAMING 0x421816CDFe2073945173c0c35799ec21261fB399 ); // The "revert reason helper" contains a collection of revert reason strings. RevertReasonHelperInterface internal constant _revert_reason_helper415 = ( //inject NONSTANDARD NAMING RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4) ); ConfigurationRegistryInterface internal constant _config_registry519 = ( //inject NONSTANDARD NAMING ConfigurationRegistryInterface(0xC5C0ead7Df3CeFC45c8F4592E3a0f1500949E75D) ); bytes32 internal constant _enable_usdc_minting_key536 = bytes32( //inject NONSTANDARD NAMING 0x596746115f08448433597980d42b4541c0197187d07ffad9c7f66a471c49dbba ); // keccak256("allowAvailableUSDCToBeUsedToMintCUSDC") // Compound returns a value of 0 to indicate success, or lack of an error. uint256 internal constant _compound_success452 = 0; //inject NONSTANDARD NAMING // ERC-1271 must return this magic value when `isValidSignature` is called. bytes4 internal constant _erc_1271_magic_value586 = bytes4(0x20c13b0b); //inject NONSTANDARD NAMING // Minimum supported deposit & non-maximum withdrawal size is .001 underlying. uint256 private constant _just_under_one_1000th_dai594 = 999999999999999; //inject NONSTANDARD NAMING uint256 private constant _just_under_one_1000th_usdc382 = 999; //inject NONSTANDARD NAMING // Specify the amount of gas to supply when making Ether transfers. uint256 private constant _eth_transfer_gas33 = 4999; //inject NONSTANDARD NAMING constructor() public { assert( _enable_usdc_minting_key536 == keccak256( bytes("allowAvailableUSDCToBeUsedToMintCUSDC") ) ); } function () external payable {} function INITIALIZE336(address userSigningKey) external { //inject NONSTANDARD NAMING // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set up the user's signing key and emit a corresponding event. _SETUSERSIGNINGKEY543(userSigningKey); // Approve the dDai contract to transfer Dai on behalf of this contract. if (_SETFULLAPPROVAL629(AssetType.DAI)) { // Get the current Dai balance on this contract. uint256 daiBalance = _dai860.BALANCEOF992(address(this)); // Try to deposit the full Dai balance to Dharma Dai. _DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance); } // Approve the dUSDC contract to transfer USDC on behalf of this contract. if (_SETFULLAPPROVAL629(AssetType.USDC)) { // Get the current USDC balance on this contract. uint256 usdcBalance = _usdc146.BALANCEOF992(address(this)); // Try to deposit the full Dai balance to Dharma USDC. _DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance); } } function REPAYANDDEPOSIT967() external { //inject NONSTANDARD NAMING // Get the current Dai balance on this contract. uint256 daiBalance = _dai860.BALANCEOF992(address(this)); // If there is any Dai balance, check for adequate approval for dDai. if (daiBalance > 0) { uint256 daiAllowance = _dai860.ALLOWANCE583(address(this), address(_ddai406)); // If allowance is insufficient, try to set it before depositing. if (daiAllowance < daiBalance) { if (_SETFULLAPPROVAL629(AssetType.DAI)) { // Deposit the full available Dai balance to Dharma Dai. _DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance); } // Otherwise, just go ahead and try the Dai deposit. } else { // Deposit the full available Dai balance to Dharma Dai. _DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance); } } // Get the current USDC balance on this contract. uint256 usdcBalance = _usdc146.BALANCEOF992(address(this)); // If there is any USDC balance, check for adequate approval for dUSDC. if (usdcBalance > 0) { uint256 usdcAllowance = _usdc146.ALLOWANCE583(address(this), address(_dusdc174)); // If allowance is insufficient, try to set it before depositing. if (usdcAllowance < usdcBalance) { if (_SETFULLAPPROVAL629(AssetType.USDC)) { // Deposit the full available USDC balance to Dharma USDC. _DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance); } // Otherwise, just go ahead and try the USDC deposit. } else { // Deposit the full available USDC balance to Dharma USDC. _DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance); } } } function WITHDRAWDAI449( //inject NONSTANDARD NAMING uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.DAIWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an amount of at least 0.001 Dai has been supplied. if (amount <= _just_under_one_1000th_dai594) { revert(_REVERTREASON31(0)); } // Ensure that a non-zero recipient has been supplied. if (recipient == address(0)) { revert(_REVERTREASON31(1)); } // Set the self-call context in order to call _withdrawDaiAtomic. _selfCallContext = this.WITHDRAWDAI449.selector; // Make the atomic self-call - if redeemUnderlying fails on dDai, it will // succeed but nothing will happen except firing an ExternalError event. If // the second part of the self-call (the Dai transfer) fails, it will revert // and roll back the first part of the call as well as fire an ExternalError // event after returning from the failed call. bytes memory returnData; (ok, returnData) = address(this).call(abi.encodeWithSelector( this._WITHDRAWDAIATOMIC5.selector, amount, recipient )); // If the atomic call failed, emit an event signifying a transfer failure. if (!ok) { emit EXTERNALERROR24(address(_dai860), _REVERTREASON31(2)); } else { // Set ok to false if the call succeeded but the withdrawal failed. ok = abi.decode(returnData, (bool)); } } function _WITHDRAWDAIATOMIC5( //inject NONSTANDARD NAMING uint256 amount, address recipient ) external returns (bool success) { // Ensure caller is this contract and self-call context is correctly set. _ENFORCESELFCALLFROM836(this.WITHDRAWDAI449.selector); // If amount = 0xfff...fff, withdraw the maximum amount possible. bool maxWithdraw = (amount == uint256(-1)); if (maxWithdraw) { // First attempt to redeem all dDai if there is a balance. _WITHDRAWMAXFROMDHARMATOKEN348(AssetType.DAI); // Then transfer all Dai to recipient if there is a balance. require(_TRANSFERMAX629(_dai860, recipient, false)); success = true; } else { // Attempt to withdraw specified Dai from Dharma Dai before proceeding. if (_WITHDRAWFROMDHARMATOKEN513(AssetType.DAI, amount)) { // At this point Dai transfer should never fail - wrap it just in case. require(_dai860.TRANSFER153(recipient, amount)); success = true; } } } function WITHDRAWUSDC811( //inject NONSTANDARD NAMING uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.USDCWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an amount of at least 0.001 USDC has been supplied. if (amount <= _just_under_one_1000th_usdc382) { revert(_REVERTREASON31(3)); } // Ensure that a non-zero recipient has been supplied. if (recipient == address(0)) { revert(_REVERTREASON31(1)); } // Set the self-call context in order to call _withdrawUSDCAtomic. _selfCallContext = this.WITHDRAWUSDC811.selector; // Make the atomic self-call - if redeemUnderlying fails on dUSDC, it will // succeed but nothing will happen except firing an ExternalError event. If // the second part of the self-call (USDC transfer) fails, it will revert // and roll back the first part of the call as well as fire an ExternalError // event after returning from the failed call. bytes memory returnData; (ok, returnData) = address(this).call(abi.encodeWithSelector( this._WITHDRAWUSDCATOMIC942.selector, amount, recipient )); if (!ok) { // Find out why USDC transfer reverted (doesn't give revert reasons). _DIAGNOSEANDEMITUSDCSPECIFICERROR976(_usdc146.TRANSFER153.selector); } else { // Set ok to false if the call succeeded but the withdrawal failed. ok = abi.decode(returnData, (bool)); } } function _WITHDRAWUSDCATOMIC942( //inject NONSTANDARD NAMING uint256 amount, address recipient ) external returns (bool success) { // Ensure caller is this contract and self-call context is correctly set. _ENFORCESELFCALLFROM836(this.WITHDRAWUSDC811.selector); // If amount = 0xfff...fff, withdraw the maximum amount possible. bool maxWithdraw = (amount == uint256(-1)); if (maxWithdraw) { // Attempt to redeem all dUSDC from Dharma USDC if there is a balance. _WITHDRAWMAXFROMDHARMATOKEN348(AssetType.USDC); // Then transfer all USDC to recipient if there is a balance. require(_TRANSFERMAX629(_usdc146, recipient, false)); success = true; } else { // Attempt to withdraw specified USDC from Dharma USDC before proceeding. if (_WITHDRAWFROMDHARMATOKEN513(AssetType.USDC, amount)) { // Ensure that the USDC transfer does not fail. require(_usdc146.TRANSFER153(recipient, amount)); success = true; } } } function WITHDRAWETHER963( //inject NONSTANDARD NAMING uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.ETHWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that a non-zero amount of Ether has been supplied. if (amount == 0) { revert(_REVERTREASON31(4)); } // Ensure that a non-zero recipient has been supplied. if (recipient == address(0)) { revert(_REVERTREASON31(1)); } // Attempt to transfer Ether to the recipient and emit an appropriate event. ok = _TRANSFERETH212(recipient, amount); } function CANCEL991( //inject NONSTANDARD NAMING uint256 minimumActionGas, bytes calldata signature ) external { // Get the current nonce. uint256 nonceToCancel = _nonce; // Ensure the caller or the supplied signature is valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.Cancel, abi.encode(), minimumActionGas, signature, signature ); // Emit an event to validate that the nonce is no longer valid. emit CANCEL692(nonceToCancel); } function EXECUTEACTION770( //inject NONSTANDARD NAMING address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { // Ensure that the `to` address is a contract and is not this contract. _ENSUREVALIDGENERICCALLTARGET978(to); // Ensure caller and/or supplied signatures are valid and increment nonce. (bytes32 actionID, uint256 nonce) = _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.Generic, abi.encode(to, data), minimumActionGas, userSignature, dharmaSignature ); // Note: from this point on, there are no reverts (apart from out-of-gas or // call-depth-exceeded) originating from this action. However, the call // itself may revert, in which case the function will return `false`, along // with the revert reason encoded as bytes, and fire an CallFailure event. // Perform the action via low-level call and set return values using result. (ok, returnData) = to.call(data); // Emit a CallSuccess or CallFailure event based on the outcome of the call. if (ok) { // Note: while the call succeeded, the action may still have "failed" // (for example, successful calls to Compound can still return an error). emit CALLSUCCESS383(actionID, false, nonce, to, data, returnData); } else { // Note: while the call failed, the nonce will still be incremented, which // will invalidate all supplied signatures. emit CALLFAILURE442(actionID, nonce, to, data, _DECODEREVERTREASON288(returnData)); } } function SETUSERSIGNINGKEY240( //inject NONSTANDARD NAMING address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.SetUserSigningKey, abi.encode(userSigningKey), minimumActionGas, userSignature, dharmaSignature ); // Set new user signing key on smart wallet and emit a corresponding event. _SETUSERSIGNINGKEY543(userSigningKey); } function SETESCAPEHATCH554( //inject NONSTANDARD NAMING address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.SetEscapeHatch, abi.encode(account), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an escape hatch account has been provided. if (account == address(0)) { revert(_REVERTREASON31(5)); } // Set a new escape hatch for the smart wallet unless it has been disabled. _escape_hatch_registry980.SETESCAPEHATCH554(account); } function REMOVEESCAPEHATCH653( //inject NONSTANDARD NAMING uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.RemoveEscapeHatch, abi.encode(), minimumActionGas, userSignature, dharmaSignature ); // Remove the escape hatch for the smart wallet if one is currently set. _escape_hatch_registry980.REMOVEESCAPEHATCH653(); } function PERMANENTLYDISABLEESCAPEHATCH796( //inject NONSTANDARD NAMING uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.DisableEscapeHatch, abi.encode(), minimumActionGas, userSignature, dharmaSignature ); // Permanently disable the escape hatch mechanism for this smart wallet. _escape_hatch_registry980.PERMANENTLYDISABLEESCAPEHATCH796(); } function TRADEETHFORDAIANDMINTDDAI339( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { // Ensure caller and/or supplied signatures are valid and increment nonce. _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.TradeEthForDai, abi.encode(ethToSupply, minimumDaiReceived, target, data), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an amount of at least 0.001 Dai will be received. if (minimumDaiReceived <= _just_under_one_1000th_dai594) { revert(_REVERTREASON31(31)); } // Set the self-call context in order to call _tradeEthForDaiAndMintDDaiAtomic. _selfCallContext = this.TRADEETHFORDAIANDMINTDDAI339.selector; // Make the atomic self-call - if the swap fails or the received dai is not // greater than or equal to the requirement, it will revert and roll back the // atomic call as well as fire an ExternalError. If dDai is not successfully // minted, the swap will succeed but an ExternalError for dDai will be fired. bytes memory returnData; (ok, returnData) = address(this).call(abi.encodeWithSelector( this._TRADEETHFORDAIANDMINTDDAIATOMIC657.selector, ethToSupply, minimumDaiReceived, target, data )); // If the atomic call failed, emit an event signifying a trade failure. if (!ok) { emit EXTERNALERROR24( address(_trade_helper427), _DECODEREVERTREASON288(returnData) ); } } function _TRADEETHFORDAIANDMINTDDAIATOMIC657( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data ) external returns (bool ok, bytes memory returnData) { // Ensure caller is this contract and self-call context is correctly set. _ENFORCESELFCALLFROM836(this.TRADEETHFORDAIANDMINTDDAI339.selector); // Do swap using supplied Ether amount, minimum Dai, target, and data. uint256 daiReceived = _trade_helper427.TRADEETHFORDAI848.value(ethToSupply)( minimumDaiReceived, target, data ); // Ensure that sufficient Dai was returned as a result of the swap. if (daiReceived < minimumDaiReceived) { revert(_REVERTREASON31(32)); } // Attempt to deposit the dai received and mint Dharma Dai. _DEPOSITDHARMATOKEN821(AssetType.DAI, daiReceived); } function ESCAPE232() external { //inject NONSTANDARD NAMING // Get the escape hatch account, if one exists, for this account. (bool exists, address escapeHatch) = _escape_hatch_registry980.GETESCAPEHATCH697(); // Ensure that an escape hatch is currently set for this smart wallet. if (!exists) { revert(_REVERTREASON31(6)); } // Ensure that the escape hatch account is the caller. if (msg.sender != escapeHatch) { revert(_REVERTREASON31(7)); } // Attempt to redeem all dDai for Dai on Dharma Dai. _WITHDRAWMAXFROMDHARMATOKEN348(AssetType.DAI); // Attempt to redeem all dUSDC for USDC on Dharma USDC. _WITHDRAWMAXFROMDHARMATOKEN348(AssetType.USDC); // Attempt to transfer the total Dai balance to the caller. _TRANSFERMAX629(_dai860, msg.sender, true); // Attempt to transfer the total USDC balance to the caller. _TRANSFERMAX629(_usdc146, msg.sender, true); // Attempt to transfer any residual cDai to the caller. _TRANSFERMAX629(ERC20Interface(address(_cdai443)), msg.sender, true); // Attempt to transfer any residual cUSDC to the caller. _TRANSFERMAX629(ERC20Interface(address(_cusdc481)), msg.sender, true); // Attempt to transfer any residual dDai to the caller. _TRANSFERMAX629(ERC20Interface(address(_ddai406)), msg.sender, true); // Attempt to transfer any residual dUSDC to the caller. _TRANSFERMAX629(ERC20Interface(address(_dusdc174)), msg.sender, true); // Determine if there is Ether at this address that should be transferred. uint256 balance = address(this).balance; if (balance > 0) { // Attempt to transfer any Ether to caller and emit an appropriate event. _TRANSFERETH212(msg.sender, balance); } // Emit an `Escaped` event. emit ESCAPED27(); } function RECOVER845(address newUserSigningKey) external { //inject NONSTANDARD NAMING // Only the Account Recovery Manager contract may call this function. if (msg.sender != _account_recovery_manager816) { revert(_REVERTREASON31(8)); } // Increment nonce to prevent signature reuse should original key be reset. _nonce++; // Set up the user's new dharma key and emit a corresponding event. _SETUSERSIGNINGKEY543(newUserSigningKey); } function MIGRATESAITODAI522() external { //inject NONSTANDARD NAMING revert(); } function MIGRATECSAITODDAI208() external { //inject NONSTANDARD NAMING revert(); } function MIGRATECDAITODDAI660() external { //inject NONSTANDARD NAMING _MIGRATECTOKENTODTOKEN6(AssetType.DAI); } function MIGRATECUSDCTODUSDC400() external { //inject NONSTANDARD NAMING _MIGRATECTOKENTODTOKEN6(AssetType.USDC); } function GETBALANCES53() external view returns ( //inject NONSTANDARD NAMING uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns 0 ) { daiBalance = _dai860.BALANCEOF992(address(this)); usdcBalance = _usdc146.BALANCEOF992(address(this)); etherBalance = address(this).balance; dDaiUnderlyingDaiBalance = _ddai406.BALANCEOFUNDERLYING317(address(this)); dUsdcUnderlyingUsdcBalance = _dusdc174.BALANCEOFUNDERLYING317(address(this)); } function GETUSERSIGNINGKEY63() external view returns (address userSigningKey) { //inject NONSTANDARD NAMING userSigningKey = _userSigningKey; } function GETNONCE95() external view returns (uint256 nonce) { //inject NONSTANDARD NAMING nonce = _nonce; } function GETNEXTCUSTOMACTIONID792( //inject NONSTANDARD NAMING ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( action, _VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503(action, amount, recipient), _nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function GETCUSTOMACTIONID90( //inject NONSTANDARD NAMING ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( action, _VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503(action, amount, recipient), nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function GETNEXTGENERICACTIONID981( //inject NONSTANDARD NAMING address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( ActionType.Generic, abi.encode(to, data), _nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function GETGENERICACTIONID781( //inject NONSTANDARD NAMING address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( ActionType.Generic, abi.encode(to, data), nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function GETNEXTETHFORDAIACTIONID361( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( ActionType.TradeEthForDai, abi.encode(ethToSupply, minimumDaiReceived, target, data), _nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function GETETHFORDAIACTIONID368( //inject NONSTANDARD NAMING uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( ActionType.TradeEthForDai, abi.encode(ethToSupply, minimumDaiReceived, target, data), nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function ISVALIDSIGNATURE229( //inject NONSTANDARD NAMING bytes calldata data, bytes calldata signatures ) external view returns (bytes4 magicValue) { // Get message hash digest and any additional context from data argument. bytes32 digest; bytes memory context; if (data.length == 32) { digest = abi.decode(data, (bytes32)); } else { if (data.length < 64) { revert(_REVERTREASON31(30)); } (digest, context) = abi.decode(data, (bytes32, bytes)); } // Get Dharma signature & user signature from combined signatures argument. if (signatures.length != 130) { revert(_REVERTREASON31(11)); } bytes memory signaturesInMemory = signatures; bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signaturesInMemory, 0x20)) s := mload(add(signaturesInMemory, 0x40)) v := byte(0, mload(add(signaturesInMemory, 0x60))) } bytes memory dharmaSignature = abi.encodePacked(r, s, v); assembly { r := mload(add(signaturesInMemory, 0x61)) s := mload(add(signaturesInMemory, 0x81)) v := byte(0, mload(add(signaturesInMemory, 0xa1))) } bytes memory userSignature = abi.encodePacked(r, s, v); // Validate user signature with `SignatureVerification` as the action type. if ( !_VALIDATEUSERSIGNATURE499( digest, ActionType.SignatureVerification, context, _userSigningKey, userSignature ) ) { revert(_REVERTREASON31(12)); } // Recover Dharma signature against key returned from Dharma Key Registry. if (_GETDHARMASIGNINGKEY429() != digest.RECOVER845(dharmaSignature)) { revert(_REVERTREASON31(13)); } // Return the ERC-1271 magic value to indicate success. magicValue = _erc_1271_magic_value586; } function GETIMPLEMENTATION136() external view returns (address implementation) { //inject NONSTANDARD NAMING (bool ok, bytes memory returnData) = address( 0x0000000000b45D6593312ac9fdE193F3D0633644 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } function GETVERSION901() external pure returns (uint256 version) { //inject NONSTANDARD NAMING version = _dharma_smart_wallet_version295; } function EXECUTEACTIONWITHATOMICBATCHCALLS418( //inject NONSTANDARD NAMING Call[] memory calls, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) public returns (bool[] memory ok, bytes[] memory returnData) { // Ensure that each `to` address is a contract and is not this contract. for (uint256 i = 0; i < calls.length; i++) { _ENSUREVALIDGENERICCALLTARGET978(calls[i].to); } // Ensure caller and/or supplied signatures are valid and increment nonce. (bytes32 actionID, uint256 nonce) = _VALIDATEACTIONANDINCREMENTNONCE883( ActionType.GenericAtomicBatch, abi.encode(calls), minimumActionGas, userSignature, dharmaSignature ); // Note: from this point on, there are no reverts (apart from out-of-gas or // call-depth-exceeded) originating from this contract. However, one of the // calls may revert, in which case the function will return `false`, along // with the revert reason encoded as bytes, and fire an CallFailure event. // Specify length of returned values in order to work with them in memory. ok = new bool[](calls.length); returnData = new bytes[](calls.length); // Set self-call context to call _executeActionWithAtomicBatchCallsAtomic. _selfCallContext = this.EXECUTEACTIONWITHATOMICBATCHCALLS418.selector; // Make the atomic self-call - if any call fails, calls that preceded it // will be rolled back and calls that follow it will not be made. (bool externalOk, bytes memory rawCallResults) = address(this).call( abi.encodeWithSelector( this._EXECUTEACTIONWITHATOMICBATCHCALLSATOMIC905.selector, calls ) ); // Parse data returned from self-call into each call result and store / log. CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[])); for (uint256 i = 0; i < callResults.length; i++) { Call memory currentCall = calls[i]; // Set the status and the return data / revert reason from the call. ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData; // Emit CallSuccess or CallFailure event based on the outcome of the call. if (callResults[i].ok) { // Note: while the call succeeded, the action may still have "failed". emit CALLSUCCESS383( actionID, !externalOk, // If another call failed this will have been rolled back nonce, currentCall.to, currentCall.data, callResults[i].returnData ); } else { // Note: while the call failed, the nonce will still be incremented, // which will invalidate all supplied signatures. emit CALLFAILURE442( actionID, nonce, currentCall.to, currentCall.data, _DECODEREVERTREASON288(callResults[i].returnData) ); // exit early - any calls after the first failed call will not execute. break; } } } function _EXECUTEACTIONWITHATOMICBATCHCALLSATOMIC905( //inject NONSTANDARD NAMING Call[] memory calls ) public returns (CallReturn[] memory callResults) { // Ensure caller is this contract and self-call context is correctly set. _ENFORCESELFCALLFROM836(this.EXECUTEACTIONWITHATOMICBATCHCALLS418.selector); bool rollBack = false; callResults = new CallReturn[](calls.length); for (uint256 i = 0; i < calls.length; i++) { // Perform low-level call and set return values using result. (bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data); callResults[i] = CallReturn({ok: ok, returnData: returnData}); if (!ok) { // Exit early - any calls after the first failed call will not execute. rollBack = true; break; } } if (rollBack) { // Wrap in length encoding and revert (provide data instead of a string). bytes memory callResultsBytes = abi.encode(callResults); assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) } } } function GETNEXTGENERICATOMICBATCHACTIONID957( //inject NONSTANDARD NAMING Call[] memory calls, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( ActionType.GenericAtomicBatch, abi.encode(calls), _nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function GETGENERICATOMICBATCHACTIONID98( //inject NONSTANDARD NAMING Call[] memory calls, uint256 nonce, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _GETACTIONID195( ActionType.GenericAtomicBatch, abi.encode(calls), nonce, minimumActionGas, _userSigningKey, _GETDHARMASIGNINGKEY429() ); } function _SETUSERSIGNINGKEY543(address userSigningKey) internal { //inject NONSTANDARD NAMING // Ensure that a user signing key is set on this smart wallet. if (userSigningKey == address(0)) { revert(_REVERTREASON31(14)); } _userSigningKey = userSigningKey; emit NEWUSERSIGNINGKEY833(userSigningKey); } function _SETFULLAPPROVAL629(AssetType asset) internal returns (bool ok) { //inject NONSTANDARD NAMING // Get asset's underlying token address and corresponding dToken address. address token; address dToken; if (asset == AssetType.DAI) { token = address(_dai860); dToken = address(_ddai406); } else { token = address(_usdc146); dToken = address(_dusdc174); } // Approve dToken contract to transfer underlying on behalf of this wallet. (ok, ) = address(token).call(abi.encodeWithSelector( // Note: since both Tokens have the same interface, just use DAI's. _dai860.APPROVE270.selector, dToken, uint256(-1) )); // Emit a corresponding event if the approval failed. if (!ok) { if (asset == AssetType.DAI) { emit EXTERNALERROR24(address(_dai860), _REVERTREASON31(17)); } else { // Find out why USDC transfer reverted (it doesn't give revert reasons). _DIAGNOSEANDEMITUSDCSPECIFICERROR976(_usdc146.APPROVE270.selector); } } } function _DEPOSITDHARMATOKEN821(AssetType asset, uint256 balance) internal { //inject NONSTANDARD NAMING // Only perform a deposit if the balance is at least .001 Dai or USDC. if ( asset == AssetType.DAI && balance > _just_under_one_1000th_dai594 || asset == AssetType.USDC && ( balance > _just_under_one_1000th_usdc382 && uint256(_config_registry519.GET761(_enable_usdc_minting_key536)) != 0 ) ) { // Get dToken address for the asset type. address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174); // Attempt to mint the balance on the dToken contract. (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( // Note: since both dTokens have the same interface, just use dDai's. _ddai406.MINT76.selector, balance )); // Log an external error if something went wrong with the attempt. _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( asset, _ddai406.MINT76.selector, ok, data ); } } function _WITHDRAWFROMDHARMATOKEN513( //inject NONSTANDARD NAMING AssetType asset, uint256 balance ) internal returns (bool success) { // Get dToken address for the asset type. (No custom ETH withdrawal action.) address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174); // Attempt to redeem the underlying balance from the dToken contract. (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( // Note: function selector is the same for each dToken so just use dDai's. _ddai406.REDEEMUNDERLYING215.selector, balance )); // Log an external error if something went wrong with the attempt. success = _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( asset, _ddai406.REDEEMUNDERLYING215.selector, ok, data ); } function _WITHDRAWMAXFROMDHARMATOKEN348(AssetType asset) internal { //inject NONSTANDARD NAMING // Get dToken address for the asset type. (No custom ETH withdrawal action.) address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174); // Try to retrieve the current dToken balance for this account. ERC20Interface dTokenBalance; (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( dTokenBalance.BALANCEOF992.selector, address(this) )); uint256 redeemAmount = 0; if (ok && data.length == 32) { redeemAmount = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check - log an ExternalError. _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( asset, dTokenBalance.BALANCEOF992.selector, ok, data ); } // Only perform the call to redeem if there is a non-zero balance. if (redeemAmount > 0) { // Attempt to redeem the underlying balance from the dToken contract. (ok, data) = dToken.call(abi.encodeWithSelector( // Function selector is the same for all dTokens, so just use dDai's. _ddai406.REDEEM466.selector, redeemAmount )); // Log an external error if something went wrong with the attempt. _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( asset, _ddai406.REDEEM466.selector, ok, data ); } } function _TRANSFERMAX629( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, bool suppressRevert ) internal returns (bool success) { // Get the current balance on the smart wallet for the supplied ERC20 token. uint256 balance = 0; bool balanceCheckWorked = true; if (!suppressRevert) { balance = token.BALANCEOF992(address(this)); } else { // Try to retrieve current token balance for this account with 1/2 gas. (bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.BALANCEOF992.selector, address(this)) ); if (ok && data.length == 32) { balance = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check. balanceCheckWorked = false; } } // Only perform the call to transfer if there is a non-zero balance. if (balance > 0) { if (!suppressRevert) { // Perform the transfer and pass along the returned boolean (or revert). success = token.TRANSFER153(recipient, balance); } else { // Attempt transfer with 1/2 gas, allow reverts, and return call status. (success, ) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.TRANSFER153.selector, recipient, balance) ); } } else { // Skip the transfer and return true as long as the balance check worked. success = balanceCheckWorked; } } function _TRANSFERETH212( //inject NONSTANDARD NAMING address payable recipient, uint256 amount ) internal returns (bool success) { // Attempt to transfer any Ether to caller and emit an event if it fails. (success, ) = recipient.call.gas(_eth_transfer_gas33).value(amount)(""); if (!success) { emit EXTERNALERROR24(recipient, _REVERTREASON31(18)); } else { emit ETHWITHDRAWAL175(amount, recipient); } } function _VALIDATEACTIONANDINCREMENTNONCE883( //inject NONSTANDARD NAMING ActionType action, bytes memory arguments, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) internal returns (bytes32 actionID, uint256 actionNonce) { // Ensure that the current gas exceeds the minimum required action gas. // This prevents griefing attacks where an attacker can invalidate a // signature without providing enough gas for the action to succeed. Also // note that some gas will be spent before this check is reached - supplying // ~30,000 additional gas should suffice when submitting transactions. To // skip this requirement, supply zero for the minimumActionGas argument. if (minimumActionGas != 0) { if (gasleft() < minimumActionGas) { revert(_REVERTREASON31(19)); } } // Get the current nonce for the action to be performed. actionNonce = _nonce; // Get the user signing key that will be used to verify their signature. address userSigningKey = _userSigningKey; // Get the Dharma signing key that will be used to verify their signature. address dharmaSigningKey = _GETDHARMASIGNINGKEY429(); // Determine the actionID - this serves as the signature hash. actionID = _GETACTIONID195( action, arguments, actionNonce, minimumActionGas, userSigningKey, dharmaSigningKey ); // Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID. bytes32 messageHash = actionID.TOETHSIGNEDMESSAGEHASH603(); // Actions other than Cancel require both signatures; Cancel only needs one. if (action != ActionType.Cancel) { // Validate user signing key signature unless it is `msg.sender`. if (msg.sender != userSigningKey) { if ( !_VALIDATEUSERSIGNATURE499( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_REVERTREASON31(20)); } } // Validate Dharma signing key signature unless it is `msg.sender`. if (msg.sender != dharmaSigningKey) { if (dharmaSigningKey != messageHash.RECOVER845(dharmaSignature)) { revert(_REVERTREASON31(21)); } } } else { // Validate signing key signature unless user or Dharma is `msg.sender`. if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) { if ( dharmaSigningKey != messageHash.RECOVER845(dharmaSignature) && !_VALIDATEUSERSIGNATURE499( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_REVERTREASON31(22)); } } } // Increment nonce in order to prevent reuse of signatures after the call. _nonce++; } function _MIGRATECTOKENTODTOKEN6(AssetType token) internal { //inject NONSTANDARD NAMING CTokenInterface cToken; DTokenInterface dToken; if (token == AssetType.DAI) { cToken = _cdai443; dToken = _ddai406; } else { cToken = _cusdc481; dToken = _dusdc174; } // Get the current cToken balance for this account. uint256 balance = cToken.BALANCEOF992(address(this)); // Only perform the conversion if there is a non-zero balance. if (balance > 0) { // If the allowance is insufficient, set it before depositing. if (cToken.ALLOWANCE583(address(this), address(dToken)) < balance) { if (!cToken.APPROVE270(address(dToken), uint256(-1))) { revert(_REVERTREASON31(23)); } } // Deposit the new balance on the Dharma Token. if (dToken.MINTVIACTOKEN796(balance) == 0) { revert(_REVERTREASON31(24)); } } } function _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( //inject NONSTANDARD NAMING AssetType asset, bytes4 functionSelector, bool ok, bytes memory data ) internal returns (bool success) { // Log an external error if something went wrong with the attempt. if (ok) { if (data.length == 32) { uint256 amount = abi.decode(data, (uint256)); if (amount > 0) { success = true; } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _GETDHARMATOKENDETAILS978(asset, functionSelector) ); emit EXTERNALERROR24( account, string( abi.encodePacked( name, " gave no tokens calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _GETDHARMATOKENDETAILS978(asset, functionSelector) ); emit EXTERNALERROR24( account, string( abi.encodePacked( name, " gave bad data calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _GETDHARMATOKENDETAILS978(asset, functionSelector) ); // Decode the revert reason in the event one was returned. string memory revertReason = _DECODEREVERTREASON288(data); emit EXTERNALERROR24( account, string( abi.encodePacked( name, " reverted calling ", functionName, ": ", revertReason ) ) ); } } function _DIAGNOSEANDEMITUSDCSPECIFICERROR976(bytes4 functionSelector) internal { //inject NONSTANDARD NAMING // Determine the name of the function that was called on USDC. string memory functionName; if (functionSelector == _usdc146.TRANSFER153.selector) { functionName = "transfer"; } else { functionName = "approve"; } USDCV1Interface usdcNaughty = USDCV1Interface(address(_usdc146)); // Find out why USDC transfer reverted (it doesn't give revert reasons). if (usdcNaughty.ISBLACKLISTED453(address(this))) { emit EXTERNALERROR24( address(_usdc146), string( abi.encodePacked( functionName, " failed - USDC has blacklisted this user." ) ) ); } else { // Note: `else if` breaks coverage. if (usdcNaughty.PAUSED117()) { emit EXTERNALERROR24( address(_usdc146), string( abi.encodePacked( functionName, " failed - USDC contract is currently paused." ) ) ); } else { emit EXTERNALERROR24( address(_usdc146), string( abi.encodePacked( "USDC contract reverted on ", functionName, "." ) ) ); } } } function _ENFORCESELFCALLFROM836(bytes4 selfCallContext) internal { //inject NONSTANDARD NAMING // Ensure caller is this contract and self-call context is correctly set. if (msg.sender != address(this) || _selfCallContext != selfCallContext) { revert(_REVERTREASON31(25)); } // Clear the self-call context. delete _selfCallContext; } function _VALIDATEUSERSIGNATURE499( //inject NONSTANDARD NAMING bytes32 messageHash, ActionType action, bytes memory arguments, address userSigningKey, bytes memory userSignature ) internal view returns (bool valid) { if (!userSigningKey.ISCONTRACT235()) { valid = userSigningKey == messageHash.RECOVER845(userSignature); } else { bytes memory data = abi.encode(messageHash, action, arguments); valid = ( ERC1271Interface(userSigningKey).ISVALIDSIGNATURE229( data, userSignature ) == _erc_1271_magic_value586 ); } } function _GETDHARMASIGNINGKEY429() internal view returns ( //inject NONSTANDARD NAMING address dharmaSigningKey ) { dharmaSigningKey = _dharma_key_registry438.GETKEY781(); } function _GETACTIONID195( //inject NONSTANDARD NAMING ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey ) internal view returns (bytes32 actionID) { // actionID is constructed according to EIP-191-0x45 to prevent replays. actionID = keccak256( abi.encodePacked( address(this), _dharma_smart_wallet_version295, userSigningKey, dharmaSigningKey, nonce, minimumActionGas, action, arguments ) ); } function _GETDHARMATOKENDETAILS978( //inject NONSTANDARD NAMING AssetType asset, bytes4 functionSelector ) internal pure returns ( address account, string memory name, string memory functionName ) { if (asset == AssetType.DAI) { account = address(_ddai406); name = "Dharma Dai"; } else { account = address(_dusdc174); name = "Dharma USD Coin"; } // Note: since both dTokens have the same interface, just use dDai's. if (functionSelector == _ddai406.MINT76.selector) { functionName = "mint"; } else { if (functionSelector == ERC20Interface(account).BALANCEOF992.selector) { functionName = "balanceOf"; } else { functionName = string(abi.encodePacked( "redeem", functionSelector == _ddai406.REDEEM466.selector ? "" : "Underlying" )); } } } function _ENSUREVALIDGENERICCALLTARGET978(address to) internal view { //inject NONSTANDARD NAMING if (!to.ISCONTRACT235()) { revert(_REVERTREASON31(26)); } if (to == address(this)) { revert(_REVERTREASON31(27)); } if (to == address(_escape_hatch_registry980)) { revert(_REVERTREASON31(28)); } } function _VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503( //inject NONSTANDARD NAMING ActionType action, uint256 amount, address recipient ) internal pure returns (bytes memory arguments) { // Ensure that the action type is a valid custom action type. bool validActionType = ( action == ActionType.Cancel || action == ActionType.SetUserSigningKey || action == ActionType.DAIWithdrawal || action == ActionType.USDCWithdrawal || action == ActionType.ETHWithdrawal || action == ActionType.SetEscapeHatch || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ); if (!validActionType) { revert(_REVERTREASON31(29)); } // Use action type to determine parameters to include in returned arguments. if ( action == ActionType.Cancel || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ) { // Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch. arguments = abi.encode(); } else if ( action == ActionType.SetUserSigningKey || action == ActionType.SetEscapeHatch ) { // Ignore `amount` parameter for other, non-withdrawal actions. arguments = abi.encode(recipient); } else { // Use both `amount` and `recipient` parameters for withdrawals. arguments = abi.encode(amount, recipient); } } function _DECODEREVERTREASON288( //inject NONSTANDARD NAMING bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08) && revertData[1] == byte(0xc3) && revertData[2] == byte(0x79) && revertData[3] == byte(0xa0) ) { // Get the revert reason without the prefix from the revert data. bytes memory revertReasonBytes = new bytes(revertData.length - 4); for (uint256 i = 4; i < revertData.length; i++) { revertReasonBytes[i - 4] = revertData[i]; } // Decode the resultant revert reason as a string. revertReason = abi.decode(revertReasonBytes, (string)); } else { // Simply return the default, with no revert reason. revertReason = _REVERTREASON31(uint256(-1)); } } function _REVERTREASON31( //inject NONSTANDARD NAMING uint256 code ) internal pure returns (string memory reason) { reason = _revert_reason_helper415.REASON113(code); } }
Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
5,492,051
[ 1, 12512, 716, 333, 445, 353, 1338, 4140, 4982, 6835, 16171, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 19931, 288, 309, 1110, 7000, 554, 12, 2867, 13, 288, 15226, 12, 20, 16, 374, 13, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x32Ce7Fd95F27528942d13b20C24965ACbfACF8AC/sources/MKCToken.sol
* @title MKC Token is Standard ERC20 token/
contract MKCToken is StandardToken { string public name = "MKC Token"; string public symbol = "MKC"; address owner; uint public decimals = 18; uint public INITIAL_SUPPLY = 100000000*10**18; constructor(address _owner) public { owner = _owner; totalSupply = INITIAL_SUPPLY; balances[_owner] = INITIAL_SUPPLY; } function changeName(string _name) public { if (msg.sender == owner) name = _name; } function changeSymbol(string _symbol) public { if (msg.sender == owner) symbol = _symbol; } function changeNameAndSymbol(string _name,string _symbol) public { if (msg.sender == owner) { name = _name; symbol = _symbol; } } function changeNameAndSymbol(string _name,string _symbol) public { if (msg.sender == owner) { name = _name; symbol = _symbol; } } }
11,024,063
[ 1, 49, 47, 39, 3155, 353, 8263, 4232, 39, 3462, 1147, 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, 16351, 490, 47, 1268, 969, 353, 8263, 1345, 288, 203, 203, 565, 533, 1071, 508, 273, 315, 49, 47, 39, 3155, 14432, 203, 565, 533, 1071, 3273, 273, 315, 49, 47, 39, 14432, 203, 565, 1758, 3410, 31, 203, 565, 2254, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 1071, 28226, 67, 13272, 23893, 273, 2130, 9449, 14, 2163, 636, 2643, 31, 203, 203, 565, 3885, 12, 2867, 389, 8443, 13, 1071, 288, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 2078, 3088, 1283, 273, 28226, 67, 13272, 23893, 31, 203, 3639, 324, 26488, 63, 67, 8443, 65, 273, 28226, 67, 13272, 23893, 31, 203, 565, 289, 203, 203, 565, 445, 2549, 461, 12, 1080, 389, 529, 13, 1071, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 3410, 13, 203, 5411, 508, 273, 389, 529, 31, 203, 565, 289, 7010, 203, 565, 445, 2549, 5335, 12, 1080, 389, 7175, 13, 1071, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 3410, 13, 203, 5411, 3273, 273, 389, 7175, 31, 203, 565, 289, 7010, 7010, 565, 445, 2549, 31925, 5335, 12, 1080, 389, 529, 16, 1080, 389, 7175, 13, 1071, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 3410, 13, 288, 7010, 5411, 508, 273, 389, 529, 31, 203, 5411, 3273, 273, 389, 7175, 31, 203, 3639, 289, 203, 565, 289, 7010, 565, 445, 2549, 31925, 5335, 12, 1080, 389, 529, 16, 1080, 389, 7175, 13, 1071, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 3410, 13, 288, 7010, 5411, 508, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../interfaces/INFTComplexGemPool.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../interfaces/IERC3156FlashLender.sol"; import "../libs/AddressSet.sol"; import "./NFTComplexGemPoolData.sol"; contract NFTComplexGemPool is NFTComplexGemPoolData, INFTComplexGemPool, IERC3156FlashLender, ERC1155Holder { using AddressSet for AddressSet.Set; using ComplexPoolLib for ComplexPoolLib.ComplexPoolData; /** * @dev Add an address allowed to control this contract */ function addController(address _controllerAddress) external { require( poolData.controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); poolData.controllers[_controllerAddress] = true; } /** * @dev Check if this address is a controller */ function isController(address _controllerAddress) external view returns (bool) { return poolData.controllers[_controllerAddress]; } /** * @dev Remove the sender's address from the list of controllers */ function relinquishControl() external { require( poolData.controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); delete poolData.controllers[msg.sender]; } constructor() { poolData.controllers[msg.sender] = true; } /** * @dev initializer called when contract is deployed */ function initialize( string memory _symbol, string memory _name, uint256 _ethPrice, uint256 _minTime, uint256 _maxTime, uint256 _diffstep, uint256 _maxClaims, address _allowedToken ) external override onlyController { poolData.pool = address(this); poolData.symbol = _symbol; poolData.name = _name; poolData.ethPrice = _ethPrice; poolData.minTime = _minTime; poolData.maxTime = _maxTime; poolData.diffstep = _diffstep; poolData.maxClaims = _maxClaims; poolData.visible = true; poolData.enabled = true; if (_allowedToken != address(0)) { poolData.allowedTokens.insert(_allowedToken); } } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setGovernor(address _governorAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.governor = _governorAddress; } /** * @dev set the fee tracker. pool uses the fee tracker to issue fee tracker token issuance requests */ function setFeeTracker(address _feeTrackerAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.feeTracker = _feeTrackerAddress; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setMultiToken(address _multiTokenAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.multitoken = _multiTokenAddress; } /** * @dev set the AMM swap helper that gets token prices */ function setSwapHelper(address _swapHelperAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.swapHelper = _swapHelperAddress; } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems(address _creatorAddress, address _funderAddress) external override { // security checks for this method are in the library - this // method may only be called one time per new pool creation poolData.mintGenesisGems(_creatorAddress, _funderAddress); } /** * @dev create a single claim with given timeframe */ function createClaim(uint256 _timeframe) external payable override { poolData.createClaims(_timeframe, 1); } /** * @dev create multiple claims with given timeframe */ function createClaims(uint256 _timeframe, uint256 _count) external payable override { poolData.createClaims(_timeframe, _count); } /** * @dev purchase gems */ function purchaseGems(uint256 _count) external payable override { poolData.purchaseGems(msg.sender, msg.value, _count); } /** * @dev create a claim using a erc20 token */ function createERC20Claim(address _erc20TokenAddress, uint256 _tokenAmount) external override { poolData.createERC20Claims(_erc20TokenAddress, _tokenAmount, 1); } /** * @dev create a claim using a erc20 token */ function createERC20Claims( address _erc20TokenAddress, uint256 _tokenAmount, uint256 _count ) external override { poolData.createERC20Claims(_erc20TokenAddress, _tokenAmount, _count); } /** * @dev collect an open claim (take custody of the funds the claim is redeemable for and maybe a gem too) */ function collectClaim(uint256 _claimHash, bool _requireMature) external override { poolData.collectClaim(_claimHash, _requireMature); } /** * @dev The maximum flash loan amount - 90% of available funds */ function maxFlashLoan(address tokenAddress) external view override returns (uint256) { // if the token address is zero then get the FTM balance // other wise get the token balance of the given token address return tokenAddress == address(0) ? address(this).balance : IERC20(tokenAddress).balanceOf(address(this)); } /** * @dev The flash loan fee - 0.1% of borrowed funds */ function flashFee(address token, uint256 amount) public view override returns (uint256) { // get hash of flash fee key using token address uint256 flashFeeHash = uint256( keccak256(abi.encodePacked("flash_loan", address(token))) ); // get the flash fee from the storage uint256 feeDiv = INFTGemFeeManager(poolData.feeTracker).fee( flashFeeHash ); // if the flash fee is not set, get the default fee if (feeDiv == 0) { flashFeeHash = uint256(keccak256(abi.encodePacked("flash_loan"))); feeDiv = INFTGemFeeManager(poolData.feeTracker).fee(flashFeeHash); } // if no default fee, set the fee to 10000 (0.01%) if (feeDiv == 0) { feeDiv = 10000; } return amount / feeDiv; } /** * @dev Perform a flash loan (borrow tokens from the controller and return them after a certain time) */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external override returns (bool) { // get the fee of the flash loan uint256 fee = flashFee(token, amount); // get the receiver's address address receiverAddress = address(receiver); // no token address means we are sending FTM if (token == address(0)) { payable(receiverAddress).transfer(amount); } else { // else we are sending erc20 tokens IERC20(token).transfer(receiverAddress, amount); } // get the balance of the lender - base token if address is 0 // or erc20 token if address is not 0 uint256 initialBalance = token == address(0) ? address(this).balance : IERC20(token).balanceOf(address(this)); // create success callback hash bytes32 callbackSuccess = keccak256("ERC3156FlashBorrower.onFlashLoan"); // call the flash loan callback require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == callbackSuccess, "FlashMinter: Callback failed" ); // check if the flash loan is finished // first we get the balance of the lender uint256 _allowance = address(this).balance; if (token != address(0)) { // if the token is erc20 we need // to get the allowance of the token _allowance = IERC20(token).allowance( address(receiver), address(this) ); } else { // if the token is FTM we check if the // initia balance is greater than the // allowance. If it is we set _allowance // to zero to dissallow the loan. Other if (initialBalance > _allowance) _allowance = 0; else _allowance = _allowance - initialBalance; } // if the allowance is greater than the loan amount plus // the fee then we can finish the flash loan require( _allowance >= (amount + fee), "FlashMinter: Repay not approved" ); return true; } }
* @dev The maximum flash loan amount - 90% of available funds/ if the token address is zero then get the FTM balance other wise get the token balance of the given token address
function maxFlashLoan(address tokenAddress) external view override returns (uint256) { return tokenAddress == address(0) ? address(this).balance : IERC20(tokenAddress).balanceOf(address(this)); }
888,468
[ 1, 1986, 4207, 9563, 28183, 3844, 300, 8566, 9, 434, 2319, 284, 19156, 19, 309, 326, 1147, 1758, 353, 3634, 1508, 336, 326, 478, 22903, 11013, 1308, 24754, 336, 326, 1147, 11013, 434, 326, 864, 1147, 1758, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 943, 11353, 1504, 304, 12, 2867, 1147, 1887, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 1147, 1887, 422, 1758, 12, 20, 13, 203, 7734, 692, 1758, 12, 2211, 2934, 12296, 203, 7734, 294, 467, 654, 39, 3462, 12, 2316, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 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 ]
// SPDX-License-Identifier: MIT // 2nd part of the transition applier due to contract size restrictions pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /* Internal Imports */ import {DataTypes as dt} from "./libraries/DataTypes.sol"; import {Transitions as tn} from "./libraries/Transitions.sol"; import "./libraries/ErrMsg.sol"; contract TransitionApplier2 { uint256 public constant STAKING_SCALE_FACTOR = 1e12; /********************** * External Functions * **********************/ /** * @notice Apply an AggregateOrdersTransition. * * @param _transition The disputed transition. * @param _strategyInfo The involved strategy from the previous transition. * @return new strategy info after applying the disputed transition */ function applyAggregateOrdersTransition( dt.AggregateOrdersTransition memory _transition, dt.StrategyInfo memory _strategyInfo ) public pure returns (dt.StrategyInfo memory) { uint256 npend = _strategyInfo.pending.length; require(npend > 0, ErrMsg.REQ_NO_PEND); dt.PendingStrategyInfo memory psi = _strategyInfo.pending[npend - 1]; require(_transition.buyAmount == psi.buyAmount, ErrMsg.REQ_BAD_AMOUNT); require(_transition.sellShares == psi.sellShares, ErrMsg.REQ_BAD_SHARES); uint256 minSharesFromBuy = (_transition.buyAmount * 1e18) / psi.maxSharePriceForBuy; uint256 minAmountFromSell = (_transition.sellShares * psi.minSharePriceForSell) / 1e18; require(_transition.minSharesFromBuy == minSharesFromBuy, ErrMsg.REQ_BAD_SHARES); require(_transition.minAmountFromSell == minAmountFromSell, ErrMsg.REQ_BAD_AMOUNT); _strategyInfo.nextAggregateId++; return _strategyInfo; } /** * @notice Apply a ExecutionResultTransition. * * @param _transition The disputed transition. * @param _strategyInfo The involved strategy from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new strategy info after applying the disputed transition */ function applyExecutionResultTransition( dt.ExecutionResultTransition memory _transition, dt.StrategyInfo memory _strategyInfo, dt.GlobalInfo memory _globalInfo ) public pure returns (dt.StrategyInfo memory, dt.GlobalInfo memory) { uint256 idx; bool found = false; for (uint256 i = 0; i < _strategyInfo.pending.length; i++) { if (_strategyInfo.pending[i].aggregateId == _transition.aggregateId) { idx = i; found = true; break; } } require(found, ErrMsg.REQ_BAD_AGGR); if (_transition.success) { _strategyInfo.pending[idx].sharesFromBuy = _transition.sharesFromBuy; _strategyInfo.pending[idx].amountFromSell = _transition.amountFromSell; } _strategyInfo.pending[idx].executionSucceed = _transition.success; _strategyInfo.pending[idx].unsettledBuyAmount = _strategyInfo.pending[idx].buyAmount; _strategyInfo.pending[idx].unsettledSellShares = _strategyInfo.pending[idx].sellShares; _strategyInfo.lastExecAggregateId = _transition.aggregateId; return (_strategyInfo, _globalInfo); } /** * @notice Apply a WithdrawProtocolFeeTransition. * * @param _transition The disputed transition. * @param _globalInfo The involved global info from the previous transition. * @return new global info after applying the disputed transition */ function applyWithdrawProtocolFeeTransition( dt.WithdrawProtocolFeeTransition memory _transition, dt.GlobalInfo memory _globalInfo ) public pure returns (dt.GlobalInfo memory) { _globalInfo.protoFees[_transition.assetId] -= _transition.amount; return _globalInfo; } /** * @notice Apply a TransferOperatorFeeTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new account info and global info after applying the disputed transition */ function applyTransferOperatorFeeTransition( dt.TransferOperatorFeeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.AccountInfo memory, dt.GlobalInfo memory) { require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.account != address(0), ErrMsg.REQ_BAD_ACCT); uint32 assetFeeLen = uint32(_globalInfo.opFees.assets.length); if (assetFeeLen > 1) { tn.adjustAccountIdleAssetEntries(_accountInfo, assetFeeLen - 1); for (uint256 i = 1; i < assetFeeLen; i++) { _accountInfo.idleAssets[i] += _globalInfo.opFees.assets[i]; _globalInfo.opFees.assets[i] = 0; } } uint32 shareFeeLen = uint32(_globalInfo.opFees.shares.length); if (shareFeeLen > 1) { tn.adjustAccountShareEntries(_accountInfo, shareFeeLen - 1); for (uint256 i = 1; i < shareFeeLen; i++) { _accountInfo.shares[i] += _globalInfo.opFees.shares[i]; _globalInfo.opFees.shares[i] = 0; } } return (_accountInfo, _globalInfo); } /** * @notice Apply a UpdateEpochTransition. * * @param _transition The disputed transition. * @param _globalInfo The involved global info from the previous transition. * @return new global info after applying the disputed transition */ function applyUpdateEpochTransition(dt.UpdateEpochTransition memory _transition, dt.GlobalInfo memory _globalInfo) public pure returns (dt.GlobalInfo memory) { if (_transition.epoch >= _globalInfo.currEpoch) { _globalInfo.currEpoch = _transition.epoch; } return _globalInfo; } /** * @notice Apply a StakeTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new account, staking pool and global info after applying the disputed transition */ function applyStakeTransition( dt.StakeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns ( dt.AccountInfo memory, dt.StakingPoolInfo memory, dt.GlobalInfo memory ) { require( ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( _transition.transitionType, _transition.poolId, _transition.shares, _transition.fee, _transition.timestamp ) ) ), _transition.v, _transition.r, _transition.s ) == _accountInfo.account, ErrMsg.REQ_BAD_SIG ); require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.timestamp < _transition.timestamp, ErrMsg.REQ_BAD_TS); require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP); _accountInfo.timestamp = _transition.timestamp; uint32 poolId = _transition.poolId; uint256 feeInShares; (bool isCelr, uint256 fee) = tn.getFeeInfo(_transition.fee); if (isCelr) { _accountInfo.idleAssets[1] -= fee; tn.updateOpFee(_globalInfo, true, 1, fee); } else { feeInShares = fee; tn.updateOpFee(_globalInfo, false, _stakingPoolInfo.strategyId, fee); } uint256 addedShares = _transition.shares - feeInShares; _updatePoolStates(_stakingPoolInfo, _globalInfo); _adjustAccountStakedShareAndStakeEntries(_accountInfo, poolId); _adjustAccountRewardDebtEntries(_accountInfo, poolId, uint32(_stakingPoolInfo.rewardPerEpoch.length - 1)); if (addedShares > 0) { uint256 addedStake = _getAdjustedStake( _accountInfo.stakedShares[poolId] + addedShares, _stakingPoolInfo.stakeAdjustmentFactor ) - _accountInfo.stakes[poolId]; _accountInfo.stakedShares[poolId] += addedShares; _accountInfo.stakes[poolId] += addedStake; _stakingPoolInfo.totalShares += addedShares; _stakingPoolInfo.totalStakes += addedStake; for (uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++) { _accountInfo.rewardDebts[poolId][rewardTokenId] += (addedStake * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) / STAKING_SCALE_FACTOR; } } tn.adjustAccountShareEntries(_accountInfo, _stakingPoolInfo.strategyId); _accountInfo.shares[_stakingPoolInfo.strategyId] -= _transition.shares; return (_accountInfo, _stakingPoolInfo, _globalInfo); } /** * @notice Apply an UnstakeTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new account, staking pool and global info after applying the disputed transition */ function applyUnstakeTransition( dt.UnstakeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns ( dt.AccountInfo memory, dt.StakingPoolInfo memory, dt.GlobalInfo memory ) { require( ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( _transition.transitionType, _transition.poolId, _transition.shares, _transition.fee, _transition.timestamp ) ) ), _transition.v, _transition.r, _transition.s ) == _accountInfo.account, ErrMsg.REQ_BAD_SIG ); require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.timestamp < _transition.timestamp, ErrMsg.REQ_BAD_TS); require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP); _accountInfo.timestamp = _transition.timestamp; uint32 poolId = _transition.poolId; uint256 feeInShares; (bool isCelr, uint256 fee) = tn.getFeeInfo(_transition.fee); if (isCelr) { _accountInfo.idleAssets[1] -= fee; tn.updateOpFee(_globalInfo, true, 1, fee); } else { feeInShares = fee; tn.updateOpFee(_globalInfo, false, _stakingPoolInfo.strategyId, fee); } uint256 removedShares = _transition.shares; _updatePoolStates(_stakingPoolInfo, _globalInfo); require(_accountInfo.stakes.length > poolId, ErrMsg.REQ_BAD_AMOUNT); _adjustAccountRewardDebtEntries(_accountInfo, poolId, uint32(_stakingPoolInfo.rewardPerEpoch.length - 1)); uint256 originalStake = _accountInfo.stakes[poolId]; if (removedShares > 0) { uint256 removedStake = _accountInfo.stakes[poolId] - _getAdjustedStake( _accountInfo.stakedShares[poolId] - removedShares, _stakingPoolInfo.stakeAdjustmentFactor ); _accountInfo.stakedShares[poolId] -= removedShares; _accountInfo.stakes[poolId] -= removedStake; _stakingPoolInfo.totalShares -= removedShares; _stakingPoolInfo.totalStakes -= removedStake; } // Harvest for (uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++) { // NOTE: Calculate pending reward using original stake to avoid rounding down twice uint256 pendingReward = (originalStake * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) / STAKING_SCALE_FACTOR - _accountInfo.rewardDebts[poolId][rewardTokenId]; _accountInfo.rewardDebts[poolId][rewardTokenId] = (_accountInfo.stakes[poolId] * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) / STAKING_SCALE_FACTOR; uint32 assetId = _stakingPoolInfo.rewardAssetIds[rewardTokenId]; _globalInfo.rewards = tn.adjustUint256Array(_globalInfo.rewards, assetId); // Cap to available reward if (pendingReward > _globalInfo.rewards[assetId]) { pendingReward = _globalInfo.rewards[assetId]; } _accountInfo.idleAssets[assetId] += pendingReward; _globalInfo.rewards[assetId] -= pendingReward; } tn.adjustAccountShareEntries(_accountInfo, _stakingPoolInfo.strategyId); _accountInfo.shares[_stakingPoolInfo.strategyId] += _transition.shares - feeInShares; return (_accountInfo, _stakingPoolInfo, _globalInfo); } /** * @notice Apply an AddPoolTransition. * * @param _transition The disputed transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new staking pool info after applying the disputed transition */ function applyAddPoolTransition( dt.AddPoolTransition memory _transition, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.StakingPoolInfo memory) { require(_transition.rewardAssetIds.length > 0, ErrMsg.REQ_BAD_LEN); require(_transition.rewardAssetIds.length == _transition.rewardPerEpoch.length, ErrMsg.REQ_BAD_LEN); require(_stakingPoolInfo.strategyId == 0, ErrMsg.REQ_BAD_SP); require(_transition.startEpoch >= _globalInfo.currEpoch, ErrMsg.REQ_BAD_EPOCH); _stakingPoolInfo.lastRewardEpoch = _transition.startEpoch; _stakingPoolInfo.stakeAdjustmentFactor = _transition.stakeAdjustmentFactor; _stakingPoolInfo.strategyId = _transition.strategyId; _stakingPoolInfo.rewardAssetIds = new uint32[](_transition.rewardAssetIds.length); for (uint256 i = 0; i < _transition.rewardAssetIds.length; i++) { _stakingPoolInfo.rewardAssetIds[i] = _transition.rewardAssetIds[i]; } _stakingPoolInfo.accumulatedRewardPerUnit = tn.adjustUint256Array( _stakingPoolInfo.accumulatedRewardPerUnit, uint32(_transition.rewardAssetIds.length - 1) ); _stakingPoolInfo.rewardPerEpoch = new uint256[](_transition.rewardPerEpoch.length); for (uint256 i = 0; i < _transition.rewardPerEpoch.length; i++) { _stakingPoolInfo.rewardPerEpoch[i] = _transition.rewardPerEpoch[i]; } return _stakingPoolInfo; } /** * @notice Apply an UpdatePoolTransition. * * @param _transition The disputed transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new staking pool info after applying the disputed transition */ function applyUpdatePoolTransition( dt.UpdatePoolTransition memory _transition, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.StakingPoolInfo memory) { require(_transition.rewardPerEpoch.length == _stakingPoolInfo.rewardPerEpoch.length, ErrMsg.REQ_BAD_LEN); require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP); _updatePoolStates(_stakingPoolInfo, _globalInfo); _stakingPoolInfo.rewardPerEpoch = new uint256[](_transition.rewardPerEpoch.length); for (uint256 i = 0; i < _transition.rewardPerEpoch.length; i++) { _stakingPoolInfo.rewardPerEpoch[i] = _transition.rewardPerEpoch[i]; } return _stakingPoolInfo; } /** * @notice Apply a DepositRewardTransition. * * @param _transition The disputed transition. * @param _globalInfo The involved global info from the previous transition. * @return new global info after applying the disputed transition */ function applyDepositRewardTransition( dt.DepositRewardTransition memory _transition, dt.GlobalInfo memory _globalInfo ) public pure returns (dt.GlobalInfo memory) { _globalInfo.rewards = tn.adjustUint256Array(_globalInfo.rewards, _transition.assetId); _globalInfo.rewards[_transition.assetId] += _transition.amount; return _globalInfo; } /********************* * Private Functions * *********************/ function _updatePoolStates(dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo) private pure { if (_globalInfo.currEpoch > _stakingPoolInfo.lastRewardEpoch) { uint256 totalStakes = _stakingPoolInfo.totalStakes; if (totalStakes > 0) { uint64 numEpochs = _globalInfo.currEpoch - _stakingPoolInfo.lastRewardEpoch; for ( uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++ ) { uint256 pendingReward = numEpochs * _stakingPoolInfo.rewardPerEpoch[rewardTokenId]; _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId] += ((pendingReward * STAKING_SCALE_FACTOR) / totalStakes); } } _stakingPoolInfo.lastRewardEpoch = _globalInfo.currEpoch; } } /** * Helper to expand the account array of staked shares and stakes if needed. */ function _adjustAccountStakedShareAndStakeEntries(dt.AccountInfo memory _accountInfo, uint32 poolId) private pure { uint32 n = uint32(_accountInfo.stakedShares.length); if (n <= poolId) { uint256[] memory arr = new uint256[](poolId + 1); for (uint32 i = 0; i < n; i++) { arr[i] = _accountInfo.stakedShares[i]; } for (uint32 i = n; i <= poolId; i++) { arr[i] = 0; } _accountInfo.stakedShares = arr; } n = uint32(_accountInfo.stakes.length); if (n <= poolId) { uint256[] memory arr = new uint256[](poolId + 1); for (uint32 i = 0; i < n; i++) { arr[i] = _accountInfo.stakes[i]; } for (uint32 i = n; i <= poolId; i++) { arr[i] = 0; } _accountInfo.stakes = arr; } } /** * Helper to expand the 2D array of account reward debt entries per pool and reward token IDs. */ function _adjustAccountRewardDebtEntries( dt.AccountInfo memory _accountInfo, uint32 poolId, uint32 rewardTokenId ) private pure { uint32 n = uint32(_accountInfo.rewardDebts.length); if (n <= poolId) { uint256[][] memory rewardDebts = new uint256[][](poolId + 1); for (uint32 i = 0; i < n; i++) { rewardDebts[i] = _accountInfo.rewardDebts[i]; } for (uint32 i = n; i < poolId; i++) { rewardDebts[i] = new uint256[](0); } rewardDebts[poolId] = new uint256[](rewardTokenId + 1); _accountInfo.rewardDebts = rewardDebts; } uint32 nRewardTokens = uint32(_accountInfo.rewardDebts[poolId].length); if (nRewardTokens <= rewardTokenId) { uint256[] memory debts = new uint256[](rewardTokenId + 1); for (uint32 i = 0; i < nRewardTokens; i++) { debts[i] = _accountInfo.rewardDebts[poolId][i]; } for (uint32 i = nRewardTokens; i <= rewardTokenId; i++) { debts[i] = 0; } _accountInfo.rewardDebts[poolId] = debts; } } /** * @notice Calculates the adjusted stake from staked shares. * @param _stakedShares The staked shares * @param _adjustmentFactor The adjustment factor, a value from (0, 1) * STAKING_SCALE_FACTOR */ function _getAdjustedStake(uint256 _stakedShares, uint256 _adjustmentFactor) private pure returns (uint256) { return ((STAKING_SCALE_FACTOR - _adjustmentFactor) * _stakedShares + _sqrt(STAKING_SCALE_FACTOR * _adjustmentFactor * _stakedShares)) / STAKING_SCALE_FACTOR; } /** * @notice Implements square root with Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method). * @param _y The input */ function _sqrt(uint256 _y) private pure returns (uint256) { uint256 z; if (_y > 3) { z = _y; uint256 x = _y / 2 + 1; while (x < z) { z = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z = 1; } return z; } }
* @notice Apply a UpdateEpochTransition. @param _transition The disputed transition. @param _globalInfo The involved global info from the previous transition. @return new global info after applying the disputed transition/
function applyUpdateEpochTransition(dt.UpdateEpochTransition memory _transition, dt.GlobalInfo memory _globalInfo) public pure returns (dt.GlobalInfo memory) { if (_transition.epoch >= _globalInfo.currEpoch) { _globalInfo.currEpoch = _transition.epoch; } return _globalInfo; }
12,924,564
[ 1, 7001, 279, 2315, 14638, 8850, 18, 225, 389, 14936, 1021, 1015, 458, 329, 6007, 18, 225, 389, 6347, 966, 1021, 24589, 2552, 1123, 628, 326, 2416, 6007, 18, 327, 394, 2552, 1123, 1839, 13650, 326, 1015, 458, 329, 6007, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2230, 1891, 14638, 8850, 12, 7510, 18, 1891, 14638, 8850, 3778, 389, 14936, 16, 3681, 18, 5160, 966, 3778, 389, 6347, 966, 13, 203, 3639, 1071, 203, 3639, 16618, 203, 3639, 1135, 261, 7510, 18, 5160, 966, 3778, 13, 203, 565, 288, 203, 3639, 309, 261, 67, 14936, 18, 12015, 1545, 389, 6347, 966, 18, 17016, 14638, 13, 288, 203, 5411, 389, 6347, 966, 18, 17016, 14638, 273, 389, 14936, 18, 12015, 31, 203, 3639, 289, 203, 3639, 327, 389, 6347, 966, 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 ]
./partial_match/97/0xc6B519a3fcfCac7e4adCA8427d42b8aF7d80CF30/sources/InsuranceFund.sol
* @notice claim token to caller @param _amount the amount of quoteToken caller want to claim/
function claim(Decimal.decimal calldata _amount) external onlyOwner { IERC20Upgradeable quoteToken = exchange.quoteAsset(); _transfer(quoteToken, _msgSender(), _amount); }
11,482,714
[ 1, 14784, 1147, 358, 4894, 225, 389, 8949, 326, 3844, 434, 3862, 1345, 4894, 2545, 358, 7516, 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, 445, 7516, 12, 5749, 18, 12586, 745, 892, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 3639, 467, 654, 39, 3462, 10784, 429, 3862, 1345, 273, 7829, 18, 6889, 6672, 5621, 203, 3639, 389, 13866, 12, 6889, 1345, 16, 389, 3576, 12021, 9334, 389, 8949, 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 ]
pragma solidity ^0.4.24; contract Token { mapping (address => uint256) public balanceOf; function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); } contract Future1Exchange { address public archon; mapping (address => mapping(address => uint256)) public _token; constructor() public { archon = msg.sender; } function safeAdd(uint crtbal, uint depbal) public pure returns (uint) { uint totalbal = crtbal + depbal; return totalbal; } function safeSub(uint crtbal, uint depbal) public pure returns (uint) { uint totalbal = crtbal - depbal; return totalbal; } /// @notice View balance /// @param token Token contract /// @param user owner address function balanceOf(address token,address user) public view returns(uint256) { return Token(token).balanceOf(user); } /// @notice Token transfer /// @param token Token contract /// @param tokens value function tokenTransfer(address token, uint256 tokens)public payable { _token[msg.sender][token] = safeAdd(_token[msg.sender][token], tokens); Token(token).transferFrom(msg.sender,address(this), tokens); } /// @notice Token withdraw /// @param token Token contract /// @param to Receiver address /// @param tokens value function tokenWithdraw(address token, address to, uint256 tokens)public payable { if(archon==msg.sender) { if(Token(token).balanceOf(address(this))>=tokens) { _token[msg.sender][token] = safeSub(_token[msg.sender][token] , tokens) ; Token(token).transfer(to, tokens); } } } ///@notice Token balance ///@param token Token contract function contract_bal(address token) public view returns(uint256) { return Token(token).balanceOf(address(this)); } ///@notice Deposit ETH function depositETH() payable external { } ///@notice Withdraw ETH ///@param to Receiver address ///@param value ethervalue function withdrawETH(address to, uint256 value) public payable returns (bool) { if(archon==msg.sender) { to.transfer(value); return true; } } }
@notice Withdraw ETH@param to Receiver address@param value ethervalue
function withdrawETH(address to, uint256 value) public payable returns (bool) { if(archon==msg.sender) { to.transfer(value); return true; } }
1,835,880
[ 1, 1190, 9446, 512, 2455, 225, 358, 31020, 1758, 225, 460, 225, 2437, 1132, 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, 598, 9446, 1584, 44, 12, 2867, 225, 358, 16, 2254, 5034, 460, 13, 1071, 8843, 429, 1135, 261, 6430, 13, 540, 203, 565, 288, 203, 540, 203, 3639, 309, 12, 991, 265, 631, 3576, 18, 15330, 13, 203, 3639, 288, 28524, 18701, 203, 1171, 358, 18, 13866, 12, 1132, 1769, 203, 1171, 327, 638, 31, 203, 377, 203, 540, 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, -100, -100, -100, -100, -100 ]
./full_match/1/0xE702BA65dEdc278535De1D6aE288AB495347a140/sources/src/uniswapv3lpETHLinkOnly.sol
@notice Represents the deposit of an NFT
contract UniswapV3LP is IERC721Receiver, Ownable { using SafeMath for uint256; using SafeMath for uint128; using PositionValue for INonfungiblePositionManager; address public WETH = 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6; address public distributor; INonfungiblePositionManager public immutable _posMgr; IUniswapV3Factory public immutable _univ3Factory; struct Deposit { address owner; uint128 liquidity; address token0; address token1; } mapping(address => uint256) public balances; uint256 public totalLPSupply; uint256 public totalLPSupplyFromOwner; mapping(uint256 => Deposit) public deposits; constructor(address posMgr, address univ3Factory) { _posMgr = INonfungiblePositionManager(posMgr); _univ3Factory = IUniswapV3Factory(univ3Factory); } function onERC721Received(address operator, address, uint256 tokenId, bytes calldata) external override returns (bytes4) { require(msg.sender == address(_posMgr), "not a univ3 nft"); _createDeposit(operator, tokenId); return this.onERC721Received.selector; } function _createDeposit(address owner, uint256 tokenId) internal { (,, address token0, address token1,,,, uint128 liquidity,,,,) = _posMgr.positions(tokenId); } deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1}); function slippagify(uint256 amount, uint256 slippage) internal pure returns (uint256) { require(slippage >= 0 && slippage <= 1e5, "not in range"); return amount.mul(1e5 - slippage).div(1e5); } function mintNewPosition(INonfungiblePositionManager.MintParams memory params, uint256 slippage) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) { if(params.token0 == WETH) { TransferHelper.safeTransferFrom(params.token1, msg.sender, address(this), params.amount1Desired); } else if(params.token1 == WETH) { TransferHelper.safeTransferFrom(params.token0, msg.sender, address(this), params.amount0Desired); } TransferHelper.safeApprove(params.token1, address(_posMgr), params.amount1Desired); TransferHelper.safeApprove(params.token0, address(_posMgr), params.amount0Desired); params.amount1Min = slippagify(params.amount1Desired, slippage); (tokenId, liquidity, amount0, amount1) = _posMgr.mint(params); if (amount0 < params.amount0Desired) { TransferHelper.safeApprove(params.token0, address(_posMgr), 0); uint256 refund0 = params.amount0Desired - amount0; TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } if (amount1 < params.amount1Desired) { TransferHelper.safeApprove(params.token1, address(_posMgr), 0); uint256 refund1 = params.amount1Desired - amount1; TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = liquidity; if(msg.sender == owner()) { totalLPSupplyFromOwner = liquidity; } } function mintNewPosition(INonfungiblePositionManager.MintParams memory params, uint256 slippage) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) { if(params.token0 == WETH) { TransferHelper.safeTransferFrom(params.token1, msg.sender, address(this), params.amount1Desired); } else if(params.token1 == WETH) { TransferHelper.safeTransferFrom(params.token0, msg.sender, address(this), params.amount0Desired); } TransferHelper.safeApprove(params.token1, address(_posMgr), params.amount1Desired); TransferHelper.safeApprove(params.token0, address(_posMgr), params.amount0Desired); params.amount1Min = slippagify(params.amount1Desired, slippage); (tokenId, liquidity, amount0, amount1) = _posMgr.mint(params); if (amount0 < params.amount0Desired) { TransferHelper.safeApprove(params.token0, address(_posMgr), 0); uint256 refund0 = params.amount0Desired - amount0; TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } if (amount1 < params.amount1Desired) { TransferHelper.safeApprove(params.token1, address(_posMgr), 0); uint256 refund1 = params.amount1Desired - amount1; TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = liquidity; if(msg.sender == owner()) { totalLPSupplyFromOwner = liquidity; } } function mintNewPosition(INonfungiblePositionManager.MintParams memory params, uint256 slippage) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) { if(params.token0 == WETH) { TransferHelper.safeTransferFrom(params.token1, msg.sender, address(this), params.amount1Desired); } else if(params.token1 == WETH) { TransferHelper.safeTransferFrom(params.token0, msg.sender, address(this), params.amount0Desired); } TransferHelper.safeApprove(params.token1, address(_posMgr), params.amount1Desired); TransferHelper.safeApprove(params.token0, address(_posMgr), params.amount0Desired); params.amount1Min = slippagify(params.amount1Desired, slippage); (tokenId, liquidity, amount0, amount1) = _posMgr.mint(params); if (amount0 < params.amount0Desired) { TransferHelper.safeApprove(params.token0, address(_posMgr), 0); uint256 refund0 = params.amount0Desired - amount0; TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } if (amount1 < params.amount1Desired) { TransferHelper.safeApprove(params.token1, address(_posMgr), 0); uint256 refund1 = params.amount1Desired - amount1; TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = liquidity; if(msg.sender == owner()) { totalLPSupplyFromOwner = liquidity; } } IWETH(WETH).deposit{value: msg.value}(); params.amount0Min = slippagify(params.amount0Desired, slippage); _createDeposit(msg.sender, tokenId); function mintNewPosition(INonfungiblePositionManager.MintParams memory params, uint256 slippage) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) { if(params.token0 == WETH) { TransferHelper.safeTransferFrom(params.token1, msg.sender, address(this), params.amount1Desired); } else if(params.token1 == WETH) { TransferHelper.safeTransferFrom(params.token0, msg.sender, address(this), params.amount0Desired); } TransferHelper.safeApprove(params.token1, address(_posMgr), params.amount1Desired); TransferHelper.safeApprove(params.token0, address(_posMgr), params.amount0Desired); params.amount1Min = slippagify(params.amount1Desired, slippage); (tokenId, liquidity, amount0, amount1) = _posMgr.mint(params); if (amount0 < params.amount0Desired) { TransferHelper.safeApprove(params.token0, address(_posMgr), 0); uint256 refund0 = params.amount0Desired - amount0; TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } if (amount1 < params.amount1Desired) { TransferHelper.safeApprove(params.token1, address(_posMgr), 0); uint256 refund1 = params.amount1Desired - amount1; TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = liquidity; if(msg.sender == owner()) { totalLPSupplyFromOwner = liquidity; } } function mintNewPosition(INonfungiblePositionManager.MintParams memory params, uint256 slippage) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) { if(params.token0 == WETH) { TransferHelper.safeTransferFrom(params.token1, msg.sender, address(this), params.amount1Desired); } else if(params.token1 == WETH) { TransferHelper.safeTransferFrom(params.token0, msg.sender, address(this), params.amount0Desired); } TransferHelper.safeApprove(params.token1, address(_posMgr), params.amount1Desired); TransferHelper.safeApprove(params.token0, address(_posMgr), params.amount0Desired); params.amount1Min = slippagify(params.amount1Desired, slippage); (tokenId, liquidity, amount0, amount1) = _posMgr.mint(params); if (amount0 < params.amount0Desired) { TransferHelper.safeApprove(params.token0, address(_posMgr), 0); uint256 refund0 = params.amount0Desired - amount0; TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } if (amount1 < params.amount1Desired) { TransferHelper.safeApprove(params.token1, address(_posMgr), 0); uint256 refund1 = params.amount1Desired - amount1; TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = liquidity; if(msg.sender == owner()) { totalLPSupplyFromOwner = liquidity; } } function mintNewPosition(INonfungiblePositionManager.MintParams memory params, uint256 slippage) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) { if(params.token0 == WETH) { TransferHelper.safeTransferFrom(params.token1, msg.sender, address(this), params.amount1Desired); } else if(params.token1 == WETH) { TransferHelper.safeTransferFrom(params.token0, msg.sender, address(this), params.amount0Desired); } TransferHelper.safeApprove(params.token1, address(_posMgr), params.amount1Desired); TransferHelper.safeApprove(params.token0, address(_posMgr), params.amount0Desired); params.amount1Min = slippagify(params.amount1Desired, slippage); (tokenId, liquidity, amount0, amount1) = _posMgr.mint(params); if (amount0 < params.amount0Desired) { TransferHelper.safeApprove(params.token0, address(_posMgr), 0); uint256 refund0 = params.amount0Desired - amount0; TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } if (amount1 < params.amount1Desired) { TransferHelper.safeApprove(params.token1, address(_posMgr), 0); uint256 refund1 = params.amount1Desired - amount1; TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = liquidity; if(msg.sender == owner()) { totalLPSupplyFromOwner = liquidity; } } function rescuseNFT(uint256 tokenId, address to) external onlyOwner { _posMgr.safeTransferFrom(address(this), to, tokenId); } function collectFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.collect(params); } function collectFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.collect(params); } _sendToOwner(tokenId,amount0,amount1); function updateDistributor(address _newDistributor) external onlyOwner { distributor = _newDistributor; } function balanceOf(address _user) external view returns (uint256) { return balances[_user]; } function totalSupply() external view returns (uint256) { return totalLPSupply - totalLPSupplyFromOwner; } function decreaseLiquidity(uint256 tokenId, uint128 liquidity, uint256 slippage) external returns (uint256 amount0, uint256 amount1) { require(balances[msg.sender] >= liquidity, "balance too low"); (uint256 amount0Min, uint256 amount1Min) = calcExpectedMin(tokenId, liquidity, slippage); INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: amount0Min, amount1Min: amount1Min, deadline: block.timestamp }); INonfungiblePositionManager.CollectParams memory params2 = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.decreaseLiquidity(params); _posMgr.collect(params2); { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; } else { } balances[msg.sender] = balances[msg.sender].sub(liquidity); totalLPSupply = totalLPSupply - liquidity; } function decreaseLiquidity(uint256 tokenId, uint128 liquidity, uint256 slippage) external returns (uint256 amount0, uint256 amount1) { require(balances[msg.sender] >= liquidity, "balance too low"); (uint256 amount0Min, uint256 amount1Min) = calcExpectedMin(tokenId, liquidity, slippage); INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: amount0Min, amount1Min: amount1Min, deadline: block.timestamp }); INonfungiblePositionManager.CollectParams memory params2 = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.decreaseLiquidity(params); _posMgr.collect(params2); { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; } else { } balances[msg.sender] = balances[msg.sender].sub(liquidity); totalLPSupply = totalLPSupply - liquidity; } function decreaseLiquidity(uint256 tokenId, uint128 liquidity, uint256 slippage) external returns (uint256 amount0, uint256 amount1) { require(balances[msg.sender] >= liquidity, "balance too low"); (uint256 amount0Min, uint256 amount1Min) = calcExpectedMin(tokenId, liquidity, slippage); INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: amount0Min, amount1Min: amount1Min, deadline: block.timestamp }); INonfungiblePositionManager.CollectParams memory params2 = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.decreaseLiquidity(params); _posMgr.collect(params2); { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; } else { } balances[msg.sender] = balances[msg.sender].sub(liquidity); totalLPSupply = totalLPSupply - liquidity; } _sendToOwner(tokenId, amount0, amount1); if(msg.sender == owner()) function decreaseLiquidity(uint256 tokenId, uint128 liquidity, uint256 slippage) external returns (uint256 amount0, uint256 amount1) { require(balances[msg.sender] >= liquidity, "balance too low"); (uint256 amount0Min, uint256 amount1Min) = calcExpectedMin(tokenId, liquidity, slippage); INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: amount0Min, amount1Min: amount1Min, deadline: block.timestamp }); INonfungiblePositionManager.CollectParams memory params2 = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.decreaseLiquidity(params); _posMgr.collect(params2); { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; } else { } balances[msg.sender] = balances[msg.sender].sub(liquidity); totalLPSupply = totalLPSupply - liquidity; } function decreaseLiquidity(uint256 tokenId, uint128 liquidity, uint256 slippage) external returns (uint256 amount0, uint256 amount1) { require(balances[msg.sender] >= liquidity, "balance too low"); (uint256 amount0Min, uint256 amount1Min) = calcExpectedMin(tokenId, liquidity, slippage); INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: amount0Min, amount1Min: amount1Min, deadline: block.timestamp }); INonfungiblePositionManager.CollectParams memory params2 = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = _posMgr.decreaseLiquidity(params); _posMgr.collect(params2); { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; } else { } balances[msg.sender] = balances[msg.sender].sub(liquidity); totalLPSupply = totalLPSupply - liquidity; } function calcExpectedMin(uint256 tokenId, uint128 liquidity, uint256 slippage) internal view returns (uint256 amount0, uint256 amount1) { (,, address token0, address token1, uint24 fee,,,,,,,) = _posMgr.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool( PoolAddress.computeAddress( ) ); (uint160 sqrtRatioX96,,,,,,) = pool.slot0(); uint256 totalSupply = totalLPSupply; amount0 = slippagify(posValue0.mul(liquidity).div(totalSupply), slippage); amount1 = slippagify(posValue1.mul(liquidity).div(totalSupply), slippage); } _posMgr.factory(), PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee}) function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } IWETH(WETH).deposit{value: msg.value}(); function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); } else if(token1 == WETH) { TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); } TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } if(msg.sender == owner() || msg.sender == distributor) { totalLPSupplyFromOwner = totalLPSupplyFromOwner + liquidity; } else { } balances[msg.sender] = balances[msg.sender].add(liquidity); totalLPSupply = totalLPSupply + liquidity; } function _sendToOwner(uint256 tokenId, uint256 amount0, uint256 amount1) private { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { IWETH(WETH).withdraw(amount0); require(success, "Who"); if(amount1 > 0) TransferHelper.safeTransfer(token1, distributor, amount1); } else if (token1 == WETH){ IWETH(WETH).withdraw(amount1); require(success, "Who"); if(amount0 > 0) TransferHelper.safeTransfer(token0, distributor, amount0); } } function _sendToOwner(uint256 tokenId, uint256 amount0, uint256 amount1) private { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { IWETH(WETH).withdraw(amount0); require(success, "Who"); if(amount1 > 0) TransferHelper.safeTransfer(token1, distributor, amount1); } else if (token1 == WETH){ IWETH(WETH).withdraw(amount1); require(success, "Who"); if(amount0 > 0) TransferHelper.safeTransfer(token0, distributor, amount0); } } (bool success, ) = distributor.call{value: amount0}(""); function _sendToOwner(uint256 tokenId, uint256 amount0, uint256 amount1) private { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; if(token0 == WETH) { IWETH(WETH).withdraw(amount0); require(success, "Who"); if(amount1 > 0) TransferHelper.safeTransfer(token1, distributor, amount1); } else if (token1 == WETH){ IWETH(WETH).withdraw(amount1); require(success, "Who"); if(amount0 > 0) TransferHelper.safeTransfer(token0, distributor, amount0); } } (bool success, ) = distributor.call{value: amount1}(""); function recoverEth() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } function recoverTokens(address tokenAddress) external onlyOwner { IERC20 token = IERC20(tokenAddress); token.transfer(msg.sender, token.balanceOf(address(this))); } receive() payable external { } }
9,804,455
[ 1, 23869, 87, 326, 443, 1724, 434, 392, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1351, 291, 91, 438, 58, 23, 14461, 353, 467, 654, 39, 27, 5340, 12952, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 10392, 31, 203, 565, 1450, 11010, 620, 364, 2120, 265, 12125, 75, 1523, 2555, 1318, 31, 203, 565, 1758, 1071, 678, 1584, 44, 273, 374, 20029, 24, 42, 15259, 5324, 2499, 8942, 42, 24, 22201, 74, 27, 38, 12416, 37, 25, 785, 23, 2643, 6260, 73, 9452, 70, 22, 26825, 72, 26, 31, 203, 565, 1758, 1071, 1015, 19293, 31, 203, 565, 2120, 265, 12125, 75, 1523, 2555, 1318, 1071, 11732, 389, 917, 9455, 31, 203, 565, 467, 984, 291, 91, 438, 58, 23, 1733, 1071, 11732, 389, 318, 427, 23, 1733, 31, 203, 203, 565, 1958, 4019, 538, 305, 288, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 10392, 4501, 372, 24237, 31, 203, 3639, 1758, 1147, 20, 31, 203, 3639, 1758, 1147, 21, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 324, 26488, 31, 203, 565, 2254, 5034, 1071, 2078, 14461, 3088, 1283, 31, 203, 565, 2254, 5034, 1071, 2078, 14461, 3088, 1283, 1265, 5541, 31, 203, 565, 2874, 12, 11890, 5034, 516, 4019, 538, 305, 13, 1071, 443, 917, 1282, 31, 203, 565, 3885, 12, 2867, 949, 9455, 16, 1758, 28772, 23, 1733, 13, 288, 203, 3639, 389, 917, 9455, 273, 2120, 265, 12125, 75, 1523, 2555, 1318, 12, 917, 9455, 1769, 203, 3639, 389, 318, 427, 23, 1733, 2 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title AccessDeposit * @dev Adds grant/revoke functions to the contract. */ contract AccessDeposit is Claimable { // Access for adding deposit. mapping(address => bool) private depositAccess; // Modifier for accessibility to add deposit. modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; } // @dev Grant acess to deposit heroes. function grantAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = true; } // @dev Revoke acess to deposit heroes. function revokeAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = false; } } /** * @title AccessDeploy * @dev Adds grant/revoke functions to the contract. */ contract AccessDeploy is Claimable { // Access for deploying heroes. mapping(address => bool) private deployAccess; // Modifier for accessibility to deploy a hero on a location. modifier onlyAccessDeploy { require(msg.sender == owner || deployAccess[msg.sender] == true); _; } // @dev Grant acess to deploy heroes. function grantAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = true; } // @dev Revoke acess to deploy heroes. function revokeAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = false; } } /** * @title AccessMint * @dev Adds grant/revoke functions to the contract. */ contract AccessMint is Claimable { // Access for minting new tokens. mapping(address => bool) private mintAccess; // Modifier for accessibility to define new hero types. modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; } // @dev Grant acess to mint heroes. function grantAccessMint(address _address) onlyOwner public { mintAccess[_address] = true; } // @dev Revoke acess to mint heroes. function revokeAccessMint(address _address) onlyOwner public { mintAccess[_address] = false; } } /** * @title Gold * @dev ERC20 Token that can be minted. */ contract Gold is StandardToken, Claimable, AccessMint { string public constant name = "Gold"; string public constant symbol = "G"; uint8 public constant decimals = 18; // Event that is fired when minted. event Mint( address indexed _to, uint256 indexed _tokenId ); // @dev Mint tokens with _amount to the address. function mint(address _to, uint256 _amount) onlyAccessMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * @title CryptoSaga Card * @dev ERC721 Token that repesents CryptoSaga's cards. * Buy consuming a card, players of CryptoSaga can get a heroe. */ contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) { require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId; } } /** * @title The interface contract for Card-For-Hero swap functionality. * @dev With this contract, a card holder can swap his/her CryptoSagaCard for reward. * This contract is intended to be inherited by CryptoSagaCardSwap implementation contracts. */ contract CryptoSagaCardSwap is Ownable { // Card contract. address internal cardAddess; // Modifier for accessibility to define new hero types. modifier onlyCard { require(msg.sender == cardAddess); _; } // @dev Set the address of the contract that represents ERC721 Card. function setCardContract(address _contractAddress) public onlyOwner { cardAddess = _contractAddress; } // @dev Convert card into reward. // This should be implemented by CryptoSagaCore later. function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } /** * @title CryptoSagaHero * @dev The token contract for the hero. * Also a superset of the ERC721 standard that allows for the minting * of the non-fungible tokens. */ contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit { string public constant name = "CryptoSaga Hero"; string public constant symbol = "HERO"; struct HeroClass { // ex) Soldier, Knight, Fighter... string className; // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. uint8 classRank; // 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. uint8 classRace; // How old is this hero class? uint32 classAge; // 0: Fighter, 1: Rogue, 2: Mage. uint8 classType; // Possible max level of this class. uint32 maxLevel; // 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. uint8 aura; // Base stats of this hero type. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] baseStats; // Minimum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] minIVForStats; // Maximum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] maxIVForStats; // Number of currently instanced heroes. uint32 currentNumberOfInstancedHeroes; } struct HeroInstance { // What is this hero's type? ex) John, Sally, Mark... uint32 heroClassId; // Individual hero's name. string heroName; // Current level of this hero. uint32 currentLevel; // Current exp of this hero. uint32 currentExp; // Where has this hero been deployed? (0: Never depolyed ever.) ex) Dungeon Floor #1, Arena #5... uint32 lastLocationId; // When a hero is deployed, it takes time for the hero to return to the base. This is in Unix epoch. uint256 availableAt; // Current stats of this hero. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] currentStats; // The individual value for this hero's stats. // This will affect the current stats of heroes. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] ivForStats; } // Required exp for level up will increase when heroes level up. // This defines how the value will increase. uint32 public requiredExpIncreaseFactor = 100; // Required Gold for level up will increase when heroes level up. // This defines how the value will increase. uint256 public requiredGoldIncreaseFactor = 1000000000000000000; // Existing hero classes. mapping(uint32 => HeroClass) public heroClasses; // The number of hero classes ever defined. uint32 public numberOfHeroClasses; // Existing hero instances. // The key is _tokenId. mapping(uint256 => HeroInstance) public tokenIdToHeroInstance; // The number of tokens ever minted. This works as the serial number. uint256 public numberOfTokenIds; // Gold contract. Gold public goldContract; // Deposit of players (in Gold). mapping(address => uint256) public addressToGoldDeposit; // Random seed. uint32 private seed = 0; // Event that is fired when a hero type defined. event DefineType( address indexed _by, uint32 indexed _typeId, string _className ); // Event that is fired when a hero is upgraded. event LevelUp( address indexed _by, uint256 indexed _tokenId, uint32 _newLevel ); // Event that is fired when a hero is deployed. event Deploy( address indexed _by, uint256 indexed _tokenId, uint32 _locationId, uint256 _duration ); // @dev Get the class's entire infomation. function getClassInfo(uint32 _classId) external view returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) { var _cl = heroClasses[_classId]; return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats); } // @dev Get the class's name. function getClassName(uint32 _classId) external view returns (string) { return heroClasses[_classId].className; } // @dev Get the class's rank. function getClassRank(uint32 _classId) external view returns (uint8) { return heroClasses[_classId].classRank; } // @dev Get the heroes ever minted for the class. function getClassMintCount(uint32 _classId) external view returns (uint32) { return heroClasses[_classId].currentNumberOfInstancedHeroes; } // @dev Get the hero's entire infomation. function getHeroInfo(uint256 _tokenId) external view returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { HeroInstance memory _h = tokenIdToHeroInstance[_tokenId]; var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4]; return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp); } // @dev Get the hero's class id. function getHeroClassId(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].heroClassId; } // @dev Get the hero's name. function getHeroName(uint256 _tokenId) external view returns (string) { return tokenIdToHeroInstance[_tokenId].heroName; } // @dev Get the hero's level. function getHeroLevel(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].currentLevel; } // @dev Get the hero's location. function getHeroLocation(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].lastLocationId; } // @dev Get the time when the hero become available. function getHeroAvailableAt(uint256 _tokenId) external view returns (uint256) { return tokenIdToHeroInstance[_tokenId].availableAt; } // @dev Get the hero's BP. function getHeroBP(uint256 _tokenId) public view returns (uint32) { var _tmp = tokenIdToHeroInstance[_tokenId].currentStats; return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]); } // @dev Get the hero's required gold for level up. function getHeroRequiredGoldForLevelUp(uint256 _tokenId) public view returns (uint256) { return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor; } // @dev Get the hero's required exp for level up. function getHeroRequiredExpForLevelUp(uint256 _tokenId) public view returns (uint32) { return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor); } // @dev Get the deposit of gold of the player. function getGoldDepositOfAddress(address _address) external view returns (uint256) { return addressToGoldDeposit[_address]; } // @dev Get the token id of the player's #th token. function getTokenIdOfAddressAndIndex(address _address, uint256 _index) external view returns (uint256) { return tokensOf(_address)[_index]; } // @dev Get the total BP of the player. function getTotalBPOfAddress(address _address) external view returns (uint32) { var _tokens = tokensOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { _totalBP += getHeroBP(_tokens[i]); } return _totalBP; } // @dev Set the hero's name. function setHeroName(uint256 _tokenId, string _name) onlyOwnerOf(_tokenId) public { tokenIdToHeroInstance[_tokenId].heroName = _name; } // @dev Set the address of the contract that represents ERC20 Gold. function setGoldContract(address _contractAddress) onlyOwner public { goldContract = Gold(_contractAddress); } // @dev Set the required golds to level up a hero. function setRequiredExpIncreaseFactor(uint32 _value) onlyOwner public { requiredExpIncreaseFactor = _value; } // @dev Set the required golds to level up a hero. function setRequiredGoldIncreaseFactor(uint256 _value) onlyOwner public { requiredGoldIncreaseFactor = _value; } // @dev Contructor. function CryptoSagaHero(address _goldAddress) public { require(_goldAddress != address(0)); // Assign Gold contract. setGoldContract(_goldAddress); // Initial heroes. // Name, Rank, Race, Age, Type, Max Level, Aura, Stats. defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]); defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]); defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]); defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]); defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]); } // @dev Define a new hero type (class). function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats) onlyOwner public { require(_classRank < 5); require(_classType < 3); require(_aura < 5); require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]); HeroClass memory _heroType = HeroClass({ className: _className, classRank: _classRank, classRace: _classRace, classAge: _classAge, classType: _classType, maxLevel: _maxLevel, aura: _aura, baseStats: _baseStats, minIVForStats: _minIVForStats, maxIVForStats: _maxIVForStats, currentNumberOfInstancedHeroes: 0 }); // Save the hero class. heroClasses[numberOfHeroClasses] = _heroType; // Fire event. DefineType(msg.sender, numberOfHeroClasses, _heroType.className); // Increment number of hero classes. numberOfHeroClasses ++; } // @dev Mint a new hero, with _heroClassId. function mint(address _owner, uint32 _heroClassId) onlyAccessMint public returns (uint256) { require(_owner != address(0)); require(_heroClassId < numberOfHeroClasses); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroClassId]; // Mint ERC721 token. _mint(_owner, numberOfTokenIds); // Build random IVs for this hero instance. uint32[5] memory _ivForStats; uint32[5] memory _initialStats; for (uint8 i = 0; i < 5; i++) { _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i])); _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i]; } // Temporary hero instance. HeroInstance memory _heroInstance = HeroInstance({ heroClassId: _heroClassId, heroName: "", currentLevel: 1, currentExp: 0, lastLocationId: 0, availableAt: now, currentStats: _initialStats, ivForStats: _ivForStats }); // Save the hero instance. tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance; // Increment number of token ids. // This will only increment when new token is minted, and will never be decemented when the token is burned. numberOfTokenIds ++; // Increment instanced number of heroes. _heroClassInfo.currentNumberOfInstancedHeroes ++; return numberOfTokenIds - 1; } // @dev Set where the heroes are deployed, and when they will return. // This is intended to be called by Dungeon, Arena, Guild contracts. function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. require(_heroInstance.availableAt <= now); _heroInstance.lastLocationId = _locationId; _heroInstance.availableAt = now + _duration; // As the hero has been deployed to another place, fire event. Deploy(msg.sender, _tokenId, _locationId, _duration); } // @dev Add exp. // This is intended to be called by Dungeon, Arena, Guild contracts. function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; var _newExp = _heroInstance.currentExp + _exp; // Sanity check to ensure we don't overflow. require(_newExp == uint256(uint128(_newExp))); _heroInstance.currentExp += _newExp; } // @dev Add deposit. // This is intended to be called by Dungeon, Arena, Guild contracts. function addDeposit(address _to, uint256 _amount) onlyAccessDeposit public { // Increment deposit. addressToGoldDeposit[_to] += _amount; } // @dev Level up the hero with _tokenId. // This function is called by the owner of the hero. function levelUp(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public { // Hero instance. var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.) require(_heroInstance.availableAt <= now); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroInstance.heroClassId]; // Hero shouldn't level up exceed its max level. require(_heroInstance.currentLevel < _heroClassInfo.maxLevel); // Required Exp. var requiredExp = getHeroRequiredExpForLevelUp(_tokenId); // Need to have enough exp. require(_heroInstance.currentExp >= requiredExp); // Required Gold. var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId); // Owner of token. var _ownerOfToken = ownerOf(_tokenId); // Need to have enough Gold balance. require(addressToGoldDeposit[_ownerOfToken] >= requiredGold); // Increase Level. _heroInstance.currentLevel += 1; // Increase Stats. for (uint8 i = 0; i < 5; i++) { _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i]; } // Deduct exp. _heroInstance.currentExp -= requiredExp; // Deduct gold. addressToGoldDeposit[_ownerOfToken] -= requiredGold; // Fire event. LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel); } // @dev Transfer deposit (with the allowance pattern.) function transferDeposit(uint256 _amount) whenNotPaused public { require(goldContract.allowance(msg.sender, this) >= _amount); // Send msg.sender's Gold to this contract. if (goldContract.transferFrom(msg.sender, this, _amount)) { // Increment deposit. addressToGoldDeposit[msg.sender] += _amount; } } // @dev Withdraw deposit. function withdrawDeposit(uint256 _amount) public { require(addressToGoldDeposit[msg.sender] >= _amount); // Send deposit of Golds to msg.sender. (Rather minting...) if (goldContract.transfer(msg.sender, _amount)) { // Decrement deposit. addressToGoldDeposit[msg.sender] -= _amount; } } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } } /** * @title CryptoSagaCardSwapMerculet * @dev This directly summons hero. */ contract CryptoSagaCardSwapMerculet is Pausable{ // 50% of Merculet will be sent to this wallet. address public wallet1; // 50% of Merculet will be sent to this wallet. address public wallet2; // Merculet token instance. ERC20 public merculetContract; // The hero contract. CryptoSagaHero public heroContract; // Merculet token price. uint256 public merculetPrice = 1000000000000000000000; // 1000 Merculets. // Blacklisted heroes. // This is needed in order to protect players, in case there exists any hero with critical issues. // We promise we will use this function carefully, and this won't be used for balancing the OP heroes. mapping(uint32 => bool) public blackList; // Random seed. uint32 private seed = 0; // @dev Set the price of summoning a hero with Merculet token. function setMerculetPrice(uint256 _value) onlyOwner public { merculetPrice = _value; } // @dev Set blacklist. function setBlacklist(uint32 _classId, bool _value) onlyOwner public { blackList[_classId] = _value; } // @dev Contructor. function CryptoSagaCardSwapMerculet(address _heroAddress, address _tokenAddress, address _walletAddress1, address _walletAddress2) public { require(_heroAddress != address(0)); require(_walletAddress1 != address(0)); require(_walletAddress2 != address(0)); wallet1 = _walletAddress1; wallet2 = _walletAddress1; heroContract = CryptoSagaHero(_heroAddress); merculetContract = ERC20(_tokenAddress); } // @dev Pay with Merculet. function payWithMerculet(uint256 _amount) whenNotPaused public { require(msg.sender != address(0)); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = merculetPrice * _amount; require(merculetContract.allowance(msg.sender, this) >= _priceOfBundle); if (merculetContract.transferFrom(msg.sender, this, _priceOfBundle)) { // Send Merculet tokens to the wallets. merculetContract.transfer(wallet1, _priceOfBundle / 2); merculetContract.transfer(wallet2, _priceOfBundle / 2); for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5000) { _heroRankToMint = 1; } else if (_randomValue < 9550) { _heroRankToMint = 2; } else if (_randomValue < 9950) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } } } // @dev Summon a hero. // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary function summonHero(address _to, uint8 _heroRankToMint) private returns (uint256) { // Get the list of hero classes. uint32 _numberOfClasses = heroContract.numberOfHeroClasses(); uint32[] memory _candidates = new uint32[](_numberOfClasses); uint32 _count = 0; for (uint32 i = 0; i < _numberOfClasses; i ++) { if (heroContract.getClassRank(i) == _heroRankToMint && blackList[i] != true) { _candidates[_count] = i; _count++; } } require(_count != 0); return heroContract.mint(_to, _candidates[random(_count, 0)]); } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } }
Required Gold for level up will increase when heroes level up. This defines how the value will increase.
uint256 public requiredGoldIncreaseFactor = 1000000000000000000;
50,118
[ 1, 3705, 611, 1673, 364, 1801, 731, 903, 10929, 1347, 366, 2439, 281, 1801, 731, 18, 1220, 11164, 3661, 326, 460, 903, 10929, 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, 225, 2254, 5034, 1071, 1931, 43, 1673, 382, 11908, 6837, 273, 2130, 12648, 12648, 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 ]
/** *Submitted for verification at Etherscan.io on 2017-09-02 */ pragma solidity ^ 0.4.8; contract ERC20 { uint public totalSupply; function totalSupply() constant returns(uint totalSupply); function balanceOf(address who) constant returns(uint256); function allowance(address owner, address spender) constant returns(uint); function transferFrom(address from, address to, uint value) returns(bool ok); function approve(address spender, uint value) returns(bool ok); function transfer(address to, uint value) returns(bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract SoarCoin is ERC20 { // Name of the token string public constant name = "Soarcoin"; // Symbol of token string public constant symbol = "Soar"; uint public decimals = 6; uint public totalSupply = 5000000000000000 ; //5 billion includes 6 zero for decimal address central_account; address owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // Functions with this modifier can only be executed by the owner modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlycentralAccount { require(msg.sender == central_account); _; } function SoarCoin() { owner = msg.sender; balances[owner] = totalSupply; } // erc20 function to return total supply function totalSupply() constant returns(uint) { return totalSupply; } // erc20 function to return balance of give address function balanceOf(address sender) constant returns(uint256 balance) { return balances[sender]; } // Transfer the balance from one account to another account function transfer(address _to, uint256 _amount) returns(bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function set_centralAccount(address central_Acccount) onlyOwner { central_account = central_Acccount; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns(bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns(bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowed[_owner][_spender]; } // Failsafe drain only owner can call this function function drain() onlyOwner { if (!owner.send(this.balance)) revert(); } // function called by owner only function zero_fee_transaction( address _from, address _to, uint256 _amount ) onlycentralAccount returns(bool success) { if (balances[_from] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } }
Name of the token Symbol of token Functions with this modifier can only be executed by the owner
{ string public constant name = "Soarcoin"; string public constant symbol = "Soar"; uint public decimals = 6; address central_account; address owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlycentralAccount { require(msg.sender == central_account); _; } function SoarCoin() { owner = msg.sender; balances[owner] = totalSupply; } function totalSupply() constant returns(uint) { return totalSupply; } function balanceOf(address sender) constant returns(uint256 balance) { return balances[sender]; } function transfer(address _to, uint256 _amount) returns(bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; return false; } } function transfer(address _to, uint256 _amount) returns(bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; return false; } } } else { function set_centralAccount(address central_Acccount) onlyOwner { central_account = central_Acccount; } function transferFrom( address _from, address _to, uint256 _amount ) returns(bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns(bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; return false; } } } else { function approve(address _spender, uint256 _amount) returns(bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowed[_owner][_spender]; } function drain() onlyOwner { if (!owner.send(this.balance)) revert(); } function zero_fee_transaction( address _from, address _to, uint256 _amount ) onlycentralAccount returns(bool success) { if (balances[_from] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; return false; } } function zero_fee_transaction( address _from, address _to, uint256 _amount ) onlycentralAccount returns(bool success) { if (balances[_from] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; return false; } } } else { }
916,047
[ 1, 461, 434, 326, 1147, 8565, 434, 1147, 15486, 598, 333, 9606, 848, 1338, 506, 7120, 635, 326, 3410, 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, 288, 203, 4202, 203, 565, 533, 1071, 5381, 508, 273, 315, 10225, 11828, 885, 14432, 203, 203, 565, 533, 1071, 5381, 3273, 273, 315, 10225, 297, 14432, 203, 203, 565, 2254, 1071, 15105, 273, 1666, 31, 203, 565, 1758, 18291, 67, 4631, 31, 203, 565, 1758, 3410, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 1338, 71, 12839, 3032, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 18291, 67, 4631, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 445, 6155, 297, 27055, 1435, 203, 565, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 8443, 65, 273, 2078, 3088, 1283, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 2078, 3088, 1283, 1435, 5381, 1135, 12, 11890, 13, 288, 203, 4202, 327, 2078, 3088, 1283, 31, 203, 565, 289, 203, 377, 203, 565, 445, 11013, 951, 12, 2867, 5793, 13, 5381, 1135, 12, 11890, 5034, 11013, 13, 288, 2 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.6.7 https://hardhat.org // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Misc_AMOs/ManualTokenTrackerAMO.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= ManualTokenTrackerAMO ====================== // ==================================================================== // Balances manually set by a bot. Calculations done off chain to lower gas. // Calculating collatDollarBalance on-chain can be extremely gassy. // Sum of misc token balances in various addresses; // Has dollarBalances(), so it can be added to an AMOMinter // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian contract ManualTokenTrackerAMO is Owned { // Core address public timelock_address; address public bot_address; // Balances uint256 public fraxDollarBalanceStored; uint256 public collatDollarBalanceStored; // Safeguards uint256 public change_tolerance = 25000; // E6 // Price constants uint256 public constant PRICE_PRECISION = 1e6; // Misc uint256 public last_timestamp; uint256 public min_cooldown_secs = 14400; // 4 hours /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier onlyByOwnGovBot() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == bot_address, "Not owner, tlck, or bot"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _creator_address, address _timelock_address, address _bot_address ) Owned(_creator_address) { timelock_address = _timelock_address; bot_address = _bot_address; } /* ========== VIEWS ========== */ function collatDollarBalance() external view returns (uint256) { (, uint256 collat_val_e18) = dollarBalances(); return collat_val_e18; } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = fraxDollarBalanceStored; collat_val_e18 = collatDollarBalanceStored; } /* ========== RESTRICTED FUNCTIONS, BUT BOT CAN SET ========== */ // Set the dollar balances for tracked tokens. // These balances are calculated off-chain due to extensive gas. // The very first set should be done manually function setDollarBalances( uint256 _new_frax_dollar_balance, uint256 _new_collat_dollar_balance, bool bypass_checks ) public onlyByOwnGovBot { // The bot cannot bypass the checks or update too fast if (msg.sender == bot_address) { require(!bypass_checks, "Only owner or governance can bypass checks"); require(block.timestamp >= (block.timestamp + min_cooldown_secs), "Too soon"); } // Calculate the max change in either direction uint256 frax_db_change = (fraxDollarBalanceStored * change_tolerance) / PRICE_PRECISION; uint256 collat_db_change = (collatDollarBalanceStored * change_tolerance) / PRICE_PRECISION; // Do the checks if (!bypass_checks){ // FRAX Dollar Balance if (_new_frax_dollar_balance >= fraxDollarBalanceStored) { require( _new_frax_dollar_balance <= (fraxDollarBalanceStored + frax_db_change), "_new_frax_dollar_balance too high" ); } else { // Prevent underflow uint256 lower_frax_db_bound = 0; if (frax_db_change < fraxDollarBalanceStored){ lower_frax_db_bound = fraxDollarBalanceStored - frax_db_change; } require( _new_frax_dollar_balance >= lower_frax_db_bound, "_new_frax_dollar_balance too low" ); } // Collat Dollar Balance if (_new_collat_dollar_balance >= collatDollarBalanceStored) { require( _new_collat_dollar_balance <= (collatDollarBalanceStored + collat_db_change), "_new_collat_dollar_balance too high" ); } else { // Prevent underflow uint256 lower_collat_db_bound = 0; if (collat_db_change < collatDollarBalanceStored){ lower_collat_db_bound = collatDollarBalanceStored - collat_db_change; } require( _new_collat_dollar_balance >= lower_collat_db_bound, "_new_collat_dollar_balance too low" ); } } // Set the values fraxDollarBalanceStored = _new_frax_dollar_balance; collatDollarBalanceStored = _new_collat_dollar_balance; last_timestamp = block.timestamp; } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address _new_timelock_address) external onlyByOwnGov { timelock_address = _new_timelock_address; } function setBot(address _new_bot_address) external onlyByOwnGov { bot_address = _new_bot_address; } // Used to block fat-finger balance changes, or balanceOf/pricing errors // In E6. 50000 = +/- 5% tolerance function setChangeTolerance(uint256 _change_tolerance) external onlyByOwnGov { change_tolerance = _change_tolerance; } // Used as a further safety feature function setMinCooldownSecs(uint256 _min_cooldown_secs) external onlyByOwnGov { min_cooldown_secs = _min_cooldown_secs; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); }
Set the dollar balances for tracked tokens. These balances are calculated off-chain due to extensive gas. The very first set should be done manually The bot cannot bypass the checks or update too fast Do the checks FRAX Dollar Balance Prevent underflow Collat Dollar Balance Prevent underflow
function setDollarBalances( uint256 _new_frax_dollar_balance, uint256 _new_collat_dollar_balance, bool bypass_checks ) public onlyByOwnGovBot { if (msg.sender == bot_address) { require(!bypass_checks, "Only owner or governance can bypass checks"); require(block.timestamp >= (block.timestamp + min_cooldown_secs), "Too soon"); } uint256 collat_db_change = (collatDollarBalanceStored * change_tolerance) / PRICE_PRECISION; if (!bypass_checks){ if (_new_frax_dollar_balance >= fraxDollarBalanceStored) { require( _new_frax_dollar_balance <= (fraxDollarBalanceStored + frax_db_change), "_new_frax_dollar_balance too high" ); } else { uint256 lower_frax_db_bound = 0; if (frax_db_change < fraxDollarBalanceStored){ lower_frax_db_bound = fraxDollarBalanceStored - frax_db_change; } require( _new_frax_dollar_balance >= lower_frax_db_bound, "_new_frax_dollar_balance too low" ); } if (_new_collat_dollar_balance >= collatDollarBalanceStored) { require( _new_collat_dollar_balance <= (collatDollarBalanceStored + collat_db_change), "_new_collat_dollar_balance too high" ); } else { uint256 lower_collat_db_bound = 0; if (collat_db_change < collatDollarBalanceStored){ lower_collat_db_bound = collatDollarBalanceStored - collat_db_change; } require( _new_collat_dollar_balance >= lower_collat_db_bound, "_new_collat_dollar_balance too low" ); } } collatDollarBalanceStored = _new_collat_dollar_balance; last_timestamp = block.timestamp; }
400,628
[ 1, 694, 326, 302, 25442, 324, 26488, 364, 15200, 2430, 18, 8646, 324, 26488, 854, 8894, 3397, 17, 5639, 6541, 358, 1110, 14315, 16189, 18, 1021, 8572, 1122, 444, 1410, 506, 2731, 10036, 1021, 2512, 2780, 17587, 326, 4271, 578, 1089, 4885, 4797, 2256, 326, 4271, 14583, 2501, 463, 25442, 30918, 19412, 3613, 2426, 1558, 4801, 463, 25442, 30918, 19412, 3613, 2426, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 40, 25442, 38, 26488, 12, 203, 3639, 2254, 5034, 389, 2704, 67, 74, 354, 92, 67, 72, 25442, 67, 12296, 16, 7010, 3639, 2254, 5034, 389, 2704, 67, 1293, 4801, 67, 72, 25442, 67, 12296, 16, 7010, 3639, 1426, 17587, 67, 12366, 203, 565, 262, 1071, 1338, 858, 5460, 43, 1527, 6522, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 2512, 67, 2867, 13, 288, 203, 5411, 2583, 12, 5, 29604, 67, 12366, 16, 315, 3386, 3410, 578, 314, 1643, 82, 1359, 848, 17587, 4271, 8863, 203, 5411, 2583, 12, 2629, 18, 5508, 1545, 261, 2629, 18, 5508, 397, 1131, 67, 71, 1371, 2378, 67, 21317, 3631, 315, 10703, 17136, 8863, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 4508, 270, 67, 1966, 67, 3427, 273, 261, 1293, 4801, 40, 25442, 13937, 18005, 380, 2549, 67, 25456, 13, 342, 10365, 1441, 67, 3670, 26913, 31, 203, 203, 3639, 309, 16051, 29604, 67, 12366, 15329, 203, 5411, 309, 261, 67, 2704, 67, 74, 354, 92, 67, 72, 25442, 67, 12296, 1545, 284, 354, 17593, 25442, 13937, 18005, 13, 288, 203, 7734, 2583, 12, 203, 10792, 389, 2704, 67, 74, 354, 92, 67, 72, 25442, 67, 12296, 1648, 261, 74, 354, 17593, 25442, 13937, 18005, 397, 284, 354, 92, 67, 1966, 67, 3427, 3631, 7010, 10792, 4192, 2704, 67, 74, 354, 92, 67, 72, 25442, 67, 12296, 4885, 3551, 6, 203, 7734, 11272, 203, 5411, 289, 203, 5411, 469, 288, 203, 7734, 2254, 5034, 2612, 67, 74, 354, 92, 67, 1966, 67, 2 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IERC20 { function TOTALSUPPLY57() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF949(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER654(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE664(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE585(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM949(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER751(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL265(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER315() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA742() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address payable private _owner; event OWNERSHIPTRANSFERRED883(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER315(); emit OWNERSHIPTRANSFERRED883(address(0), _owner); } function OWNER860() public view returns (address payable) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER684() { //inject NONSTANDARD NAMING require(ISOWNER606(), "Ownable: caller is not the owner"); _; } function ISOWNER606() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER315() == _owner; } function RENOUNCEOWNERSHIP25() public ONLYOWNER684 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED883(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP520(address payable newOwner) public ONLYOWNER684 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP409(newOwner); } function _TRANSFEROWNERSHIP409(address payable newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED883(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 _totalSupply; function TOTALSUPPLY57() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF949(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER654(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER957(_MSGSENDER315(), recipient, amount); return true; } function ALLOWANCE664(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE585(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE29(_MSGSENDER315(), spender, amount); return true; } function TRANSFERFROM949(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER957(sender, recipient, amount); _APPROVE29(sender, _MSGSENDER315(), _allowances[sender][_MSGSENDER315()].SUB32(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE599(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].ADD719(addedValue)); return true; } function DECREASEALLOWANCE607(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].SUB32(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER957(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].SUB32(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD719(amount); emit TRANSFER751(sender, recipient, amount); } function _MINT290(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD719(amount); _balances[account] = _balances[account].ADD719(amount); emit TRANSFER751(address(0), account, amount); } function _BURN535(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB32(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB32(amount); emit TRANSFER751(account, address(0), amount); } function _APPROVE29(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 APPROVAL265(owner, spender, amount); } function _BURNFROM245(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN535(account, amount); _APPROVE29(account, _MSGSENDER315(), _allowances[account][_MSGSENDER315()].SUB32(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME844() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL911() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS364() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD719(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB32(a, b, "SafeMath: subtraction overflow"); } function SUB32(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL297(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV972(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV972(a, b, "SafeMath: division by zero"); } function DIV972(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD124(a, b, "SafeMath: modulo by zero"); } function MOD124(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract yeldTUSD is ERC20, ERC20Detailed, Ownable { using SafeMath for uint256; address public yTUSDAddress; uint256 public initialPrice = 10000; uint256 public fromYeldTTUSDoYeld = initialPrice * (10 ** 18); // Must be divided by 1e18 to get the real value uint256 public fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld / initialPrice; // Must be divided by 1e18 to get the real value uint256 public yeldReward = 1; uint256 public yeldTUSDDecimals = 18; // The price has 18 decimals meaning you'll have to divide by 1e18 to get the real value uint256 public lastPriceUpdate = now; uint256 public priceUpdatePeriod = 1 days; modifier ONLYYTUSD369 { //inject NONSTANDARD NAMING require(msg.sender == yTUSDAddress); _; } constructor() public payable ERC20Detailed("yeld TUSD", "yeldTUSD", 18) {} function SETYTUSD712(address _yTUSDAddress) public ONLYOWNER684 { //inject NONSTANDARD NAMING yTUSDAddress = _yTUSDAddress; } function MINT359(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING _MINT290(_to, _amount); } function BURN815(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING _BURN535(_to, _amount); } function CHANGEPRICERATIO481(uint256 _price) public ONLYOWNER684 { //inject NONSTANDARD NAMING initialPrice = _price; } function CHECKIFPRICENEEDSUPDATING725() public view returns(bool) { //inject NONSTANDARD NAMING return now >= lastPriceUpdate + priceUpdatePeriod; } function UPDATEPRICE820() public { //inject NONSTANDARD NAMING require(CHECKIFPRICENEEDSUPDATING725(), "The price can't be updated yet"); // Update the price uint256 daysPassed = (now - lastPriceUpdate) / 1 days; yeldReward = daysPassed; lastPriceUpdate = now; fromYeldTTUSDoYeld = initialPrice.MUL297(10 ** yeldTUSDDecimals).DIV972(yeldReward); fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld.DIV972(initialPrice); } function EXTRACTTOKENSIFSTUCK927(address _token, uint256 _amount) public ONLYOWNER684 { //inject NONSTANDARD NAMING IERC20(_token).TRANSFER654(msg.sender, _amount); } function EXTRACTETHIFSTUCK461() public ONLYOWNER684 { //inject NONSTANDARD NAMING OWNER860().transfer(address(this).balance); } }
inject NONSTANDARD NAMING
function SUB32(uint256 a, uint256 b) internal pure returns (uint256) {
12,740,437
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10025, 1578, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract dapBetting { /* Types */ enum eventStatus{ open, finished, closed } struct bid{ uint id; bytes32 name; address[] whoBet; uint amountReceived; } struct betEvent{ uint id; bytes32 name; address creator; address arbitrator; bytes32 winner; uint arbitratorFee; uint256 endBlock; uint256 minBid; uint256 maxBid; bid[] bids; bet[] bets; eventStatus status; } struct bet{ address person; bytes32 bidName; uint amount; } /* Storage */ mapping (address => betEvent[]) public betEvents; mapping (address => uint) public pendingWithdrawals; /* Events */ event eventCreated(uint id, address creator); event betMade(uint value, uint id); event eventStatusChanged(uint status); event withdrawalDone(uint amount); /* Modifiers */ modifier onlyFinished(address creator, uint eventId){ if (betEvents[creator][eventId].status == eventStatus.finished || betEvents[creator][eventId].endBlock < block.number){ _; } } modifier onlyArbitrator(address creator, uint eventId){ if (betEvents[creator][eventId].arbitrator == msg.sender){ _; } } /* Methods */ function createEvent(bytes32 name, bytes32[] names, address arbitrator, uint fee, uint256 endBlock, uint256 minBid, uint256 maxBid) external{ require(fee < 100); /* check whether event with such name already exist */ bool found; for (uint8 x = 0;x<betEvents[msg.sender].length;x++){ if(betEvents[msg.sender][x].name == name){ found = true; } } require(!found); /* check names for duplicates */ for (uint8 y=0;i<names.length;i++){ require(names[y] != names[y+1]); } uint newId = betEvents[msg.sender].length++; betEvents[msg.sender][newId].id = newId; betEvents[msg.sender][newId].name = name; betEvents[msg.sender][newId].arbitrator = arbitrator; betEvents[msg.sender][newId].status = eventStatus.open; betEvents[msg.sender][newId].creator = msg.sender; betEvents[msg.sender][newId].endBlock = endBlock; betEvents[msg.sender][newId].minBid = minBid; betEvents[msg.sender][newId].maxBid = maxBid; betEvents[msg.sender][newId].arbitratorFee = fee; for (uint8 i = 0;i < names.length; i++){ uint newBidId = betEvents[msg.sender][newId].bids.length++; betEvents[msg.sender][newId].bids[newBidId].name = names[i]; betEvents[msg.sender][newId].bids[newBidId].id = newBidId; } emit eventCreated(newId, msg.sender); } function makeBet(address creator, uint eventId, bytes32 bidName) payable external{ require(betEvents[creator][eventId].status == eventStatus.open); if (betEvents[creator][eventId].endBlock > 0){ require(block.number > betEvents[creator][eventId].endBlock); } /* check whether bid with given name actually exists */ bool found; for (uint8 i=0;i<betEvents[creator][eventId].bids.length;i++){ if (betEvents[creator][eventId].bids[i].name == bidName){ bid storage foundBid = betEvents[creator][eventId].bids[i]; found = true; } } require(found); //check for block if (betEvents[creator][eventId].endBlock > 0){ require(betEvents[creator][eventId].endBlock < block.number); } //check for minimal amount if (betEvents[creator][eventId].minBid > 0){ require(msg.value > betEvents[creator][eventId].minBid); } //check for maximal amount if (betEvents[creator][eventId].maxBid > 0){ require(msg.value < betEvents[creator][eventId].maxBid); } foundBid.whoBet.push(msg.sender); foundBid.amountReceived += msg.value; uint newBetId = betEvents[creator][eventId].bets.length++; betEvents[creator][eventId].bets[newBetId].person = msg.sender; betEvents[creator][eventId].bets[newBetId].amount = msg.value; betEvents[creator][eventId].bets[newBetId].bidName = bidName; emit betMade(msg.value, newBetId); } function finishEvent(address creator, uint eventId) external{ require(betEvents[creator][eventId].status == eventStatus.open && betEvents[creator][eventId].endBlock == 0); require(msg.sender == betEvents[creator][eventId].arbitrator); betEvents[creator][eventId].status = eventStatus.finished; emit eventStatusChanged(1); } function determineWinner(address creator, uint eventId, bytes32 bidName) external onlyFinished(creator, eventId) onlyArbitrator(creator, eventId){ require (findBid(creator, eventId, bidName)); betEvent storage cEvent = betEvents[creator][eventId]; cEvent.winner = bidName; uint amountLost; uint amountWon; uint lostBetsLen; /*Calculating amount of all lost bets */ for (uint x=0;x<betEvents[creator][eventId].bids.length;x++){ if (cEvent.bids[x].name != cEvent.winner){ amountLost += cEvent.bids[x].amountReceived; } } /* Calculating amount of all won bets */ for (x=0;x<cEvent.bets.length;x++){ if(cEvent.bets[x].bidName == cEvent.winner){ uint wonBetAmount = cEvent.bets[x].amount; amountWon += wonBetAmount; pendingWithdrawals[cEvent.bets[x].person] += wonBetAmount; } else { lostBetsLen++; } } /* If we do have win bets */ if (amountWon > 0){ pendingWithdrawals[cEvent.arbitrator] += amountLost/100*cEvent.arbitratorFee; amountLost = amountLost - (amountLost/100*cEvent.arbitratorFee); for (x=0;x<cEvent.bets.length;x++){ if(cEvent.bets[x].bidName == cEvent.winner){ //uint wonBetPercentage = cEvent.bets[x].amount*100/amountWon; uint wonBetPercentage = percent(cEvent.bets[x].amount, amountWon, 2); pendingWithdrawals[cEvent.bets[x].person] += (amountLost/100)*wonBetPercentage; } } } else { /* If we dont have any bets won, we pay all the funds back except arbitrator fee */ for(x=0;x<cEvent.bets.length;x++){ pendingWithdrawals[cEvent.bets[x].person] += cEvent.bets[x].amount-((cEvent.bets[x].amount/100) * cEvent.arbitratorFee); pendingWithdrawals[cEvent.arbitrator] += (cEvent.bets[x].amount/100) * cEvent.arbitratorFee; } } cEvent.status = eventStatus.closed; emit eventStatusChanged(2); } function withdraw(address person) private{ uint amount = pendingWithdrawals[person]; pendingWithdrawals[person] = 0; person.transfer(amount); emit withdrawalDone(amount); } function requestWithdraw() external { //require(pendingWithdrawals[msg.sender] != 0); withdraw(msg.sender); } function findBid(address creator, uint eventId, bytes32 bidName) private view returns(bool){ for (uint8 i=0;i<betEvents[creator][eventId].bids.length;i++){ if(betEvents[creator][eventId].bids[i].name == bidName){ return true; } } } function calc(uint one, uint two) private pure returns(uint){ return one/two; } function percent(uint numerator, uint denominator, uint precision) public pure returns(uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision+1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } /* Getters */ function getBidsNum(address creator, uint eventId) external view returns (uint){ return betEvents[creator][eventId].bids.length; } function getBid(address creator, uint eventId, uint bidId) external view returns (uint, bytes32, uint){ bid storage foundBid = betEvents[creator][eventId].bids[bidId]; return(foundBid.id, foundBid.name, foundBid.amountReceived); } function getBetsNums(address creator, uint eventId) external view returns (uint){ return betEvents[creator][eventId].bets.length; } function getWhoBet(address creator, uint eventId, uint bidId) external view returns (address[]){ return betEvents[creator][eventId].bids[bidId].whoBet; } function getBet(address creator, uint eventId, uint betId) external view returns(address, bytes32, uint){ bet storage foundBet = betEvents[creator][eventId].bets[betId]; return (foundBet.person, foundBet.bidName, foundBet.amount); } function getEventId(address creator, bytes32 eventName) external view returns (uint, bool){ for (uint i=0;i<betEvents[creator].length;i++){ if(betEvents[creator][i].name == eventName){ return (betEvents[creator][i].id, true); } } } }
check whether bid with given name actually exists */
bool found;
2,449,828
[ 1, 1893, 2856, 9949, 598, 864, 508, 6013, 1704, 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 ]
[ 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, 1426, 1392, 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, -100, -100, -100 ]
./partial_match/5/0x4f9BcBB7Cf46559E2169ece84eD6f8BddB260861/sources/DeporDEAORecorder.sol
withdrawpush to array
function recordPledgeDisable(address owner, uint256 amount) external whenNotPaused onlyWhitelistAdmin { PledgeRecord memory record = PledgeRecord(owner, amount, 3, block.number, block.timestamp); userPledgeRecords[owner].push(record); }
16,856,308
[ 1, 1918, 9446, 6206, 358, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1409, 52, 19998, 11879, 12, 2867, 3410, 16, 2254, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 1347, 1248, 28590, 203, 3639, 1338, 18927, 4446, 203, 565, 288, 203, 203, 3639, 453, 19998, 2115, 3778, 1409, 273, 203, 5411, 453, 19998, 2115, 12, 8443, 16, 3844, 16, 890, 16, 1203, 18, 2696, 16, 1203, 18, 5508, 1769, 203, 3639, 729, 52, 19998, 6499, 63, 8443, 8009, 6206, 12, 3366, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-pool-utils/contracts/BaseGeneralPool.sol"; import "@balancer-labs/v2-pool-utils/contracts/BaseMinimalSwapInfoPool.sol"; import "./StableMath.sol"; import "./StablePoolUserDataHelpers.sol"; contract StablePool is BaseGeneralPool, BaseMinimalSwapInfoPool, StableMath { using FixedPoint for uint256; using StablePoolUserDataHelpers for bytes; using WordCodec for bytes32; // This contract uses timestamps to slowly update its Amplification parameter over time. These changes must occur // over a minimum time period much larger than the blocktime, making timestamp manipulation a non-issue. // solhint-disable not-rely-on-time // Amplification factor changes must happen over a minimum period of one day, and can at most divide or multiple the // current value by 2 every day. // WARNING: this only limits *a single* amplification change to have a maximum rate of change of twice the original // value daily. It is possible to perform multiple amplification changes in sequence to increase this value more // rapidly: for example, by doubling the value every day it can increase by a factor of 8 over three days (2^3). uint256 private constant _MIN_UPDATE_TIME = 1 days; uint256 private constant _MAX_AMP_UPDATE_DAILY_RATE = 2; bytes32 private _packedAmplificationData; event AmpUpdateStarted(uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime); event AmpUpdateStopped(uint256 currentValue); // To track how many tokens are owed to the Vault as protocol fees, we measure and store the value of the invariant // after every join and exit. All invariant growth that happens between join and exit events is due to swap fees. uint256 private _lastInvariant; // Because the invariant depends on the amplification parameter, and this value may change over time, we should only // compare invariants that were computed using the same value. We therefore store it whenever we store // _lastInvariant. uint256 private _lastInvariantAmp; enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256 amplificationParameter, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, // Because we're inheriting from both BaseGeneralPool and BaseMinimalSwapInfoPool we can choose any // specialization setting. Since this Pool never registers or deregisters any tokens after construction, // picking Two Token when the Pool only has two tokens is free gas savings. tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.GENERAL, name, symbol, tokens, new address[](tokens.length), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { _require(tokens.length <= _MAX_STABLE_TOKENS, Errors.MAX_STABLE_TOKENS); _require(amplificationParameter >= _MIN_AMP, Errors.MIN_AMP); _require(amplificationParameter <= _MAX_AMP, Errors.MAX_AMP); uint256 initialAmp = Math.mul(amplificationParameter, _AMP_PRECISION); _setAmplificationData(initialAmp); } // Base Pool handlers // Swap - General Pool specialization (from BaseGeneralPool) function _onSwapGivenIn( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal view virtual override whenNotPaused returns (uint256) { (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 amountOut = StableMath._calcOutGivenIn(currentAmp, balances, indexIn, indexOut, swapRequest.amount); return amountOut; } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal view virtual override whenNotPaused returns (uint256) { (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 amountIn = StableMath._calcInGivenOut(currentAmp, balances, indexIn, indexOut, swapRequest.amount); return amountIn; } // Swap - Two Token Pool specialization (from BaseMinimalSwapInfoPool) function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual override returns (uint256) { _require(_getTotalTokens() == 2, Errors.NOT_TWO_TOKENS); (uint256[] memory balances, uint256 indexIn, uint256 indexOut) = _getSwapBalanceArrays( swapRequest, balanceTokenIn, balanceTokenOut ); return _onSwapGivenIn(swapRequest, balances, indexIn, indexOut); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual override returns (uint256) { _require(_getTotalTokens() == 2, Errors.NOT_TWO_TOKENS); (uint256[] memory balances, uint256 indexIn, uint256 indexOut) = _getSwapBalanceArrays( swapRequest, balanceTokenIn, balanceTokenOut ); return _onSwapGivenOut(swapRequest, balances, indexIn, indexOut); } function _getSwapBalanceArrays( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) private view returns ( uint256[] memory balances, uint256 indexIn, uint256 indexOut ) { balances = new uint256[](2); if (_token0 == swapRequest.tokenIn) { indexIn = 0; indexOut = 1; balances[0] = balanceTokenIn; balances[1] = balanceTokenOut; } else { // _token0 == swapRequest.tokenOut indexOut = 0; indexIn = 1; balances[0] = balanceTokenOut; balances[1] = balanceTokenIn; } } // Initialize function _onInitializePool( bytes32, address, address, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. StablePool.JoinKind kind = userData.joinKind(); _require(kind == StablePool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, _getTotalTokens()); _upscaleArray(amountsIn, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 invariantAfterJoin = StableMath._calculateInvariant(currentAmp, amountsIn, true); // Set the initial BPT to the value of the invariant. uint256 bptAmountOut = invariantAfterJoin; _updateLastInvariant(invariantAfterJoin, currentAmp); return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas to // calculate the fee amounts during each individual swap. uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(balances, protocolSwapFeePercentage); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, scalingFactors, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _updateInvariantAfterJoin(balances, amountsIn); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, scalingFactors, userData); } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 bptAmountOut = StableMath._calcBptOutGivenExactTokensIn( currentAmp, balances, amountsIn, totalSupply(), _swapFeePercentage ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); (uint256 currentAmp, ) = _getAmplificationParameter(); amountsIn[tokenIndex] = StableMath._calcTokenInGivenExactBptOut( currentAmp, balances, tokenIndex, bptAmountOut, totalSupply(), _swapFeePercentage ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating fee amounts during each individual swap dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(balances, protocolSwapFeePercentage); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, scalingFactors, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fee amounts due in future joins and exits. _updateInvariantAfterExit(balances, amountsOut); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, userData); } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, scalingFactors, userData); } } function _exitExactBPTInForTokenOut(uint256[] memory balances, bytes memory userData) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); // We exit in a single token, so initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token (uint256 currentAmp, ) = _getAmplificationParameter(); amountsOut[tokenIndex] = StableMath._calcTokenOutGivenExactBptIn( currentAmp, balances, tokenIndex, bptAmountIn, totalSupply(), _swapFeePercentage ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = StableMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 bptAmountIn = StableMath._calcBptInGivenExactTokensOut( currentAmp, balances, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Helpers /** * @dev Stores the last measured invariant, and the amplification parameter used to compute it. */ function _updateLastInvariant(uint256 invariant, uint256 amplificationParameter) private { _lastInvariant = invariant; _lastInvariantAmp = amplificationParameter; } /** * @dev Returns the amount of protocol fees to pay, given the value of the last stored invariant and the current * balances. */ function _getDueProtocolFeeAmounts(uint256[] memory balances, uint256 protocolSwapFeePercentage) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // Instead of paying the protocol swap fee in all tokens proportionally, we will pay it in a single one. This // will reduce gas costs for single asset joins and exits, as at most only two Pool balances will change (the // token joined/exited, and the token in which fees will be paid). // The protocol fee is charged using the token with the highest balance in the pool. uint256 chosenTokenIndex = 0; uint256 maxBalance = balances[0]; for (uint256 i = 1; i < _getTotalTokens(); ++i) { uint256 currentBalance = balances[i]; if (currentBalance > maxBalance) { chosenTokenIndex = i; maxBalance = currentBalance; } } // Set the fee amount to pay in the selected token dueProtocolFeeAmounts[chosenTokenIndex] = StableMath._calcDueTokenProtocolSwapFeeAmount( _lastInvariantAmp, balances, _lastInvariant, chosenTokenIndex, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Computes and stores the value of the invariant after a join, which is required to compute due protocol fees * in the future. */ function _updateInvariantAfterJoin(uint256[] memory balances, uint256[] memory amountsIn) private { _mutateAmounts(balances, amountsIn, FixedPoint.add); (uint256 currentAmp, ) = _getAmplificationParameter(); // This invariant is used only to compute the final balance when calculating the protocol fees. These are // rounded down, so we round the invariant up. _updateLastInvariant(StableMath._calculateInvariant(currentAmp, balances, true), currentAmp); } /** * @dev Computes and stores the value of the invariant after an exit, which is required to compute due protocol fees * in the future. */ function _updateInvariantAfterExit(uint256[] memory balances, uint256[] memory amountsOut) private { _mutateAmounts(balances, amountsOut, FixedPoint.sub); (uint256 currentAmp, ) = _getAmplificationParameter(); // This invariant is used only to compute the final balance when calculating the protocol fees. These are // rounded down, so we round the invariant up. _updateLastInvariant(StableMath._calculateInvariant(currentAmp, balances, true), currentAmp); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // When calculating the current BPT rate, we may not have paid the protocol fees, therefore // the invariant should be smaller than its current value. Then, we round down overall. (uint256 currentAmp, ) = _getAmplificationParameter(); _upscaleArray(balances, _scalingFactors()); uint256 invariant = StableMath._calculateInvariant(currentAmp, balances, false); return invariant.divDown(totalSupply()); } // Amplification /** * @dev Begins changing the amplification parameter to `rawEndValue` over time. The value will change linearly until * `endTime` is reached, when it will be `rawEndValue`. * * NOTE: Internally, the amplification parameter is represented using higher precision. The values returned by * `getAmplificationParameter` have to be corrected to account for this when comparing to `rawEndValue`. */ function startAmplificationParameterUpdate(uint256 rawEndValue, uint256 endTime) external authenticate { _require(rawEndValue >= _MIN_AMP, Errors.MIN_AMP); _require(rawEndValue <= _MAX_AMP, Errors.MAX_AMP); uint256 duration = Math.sub(endTime, block.timestamp); _require(duration >= _MIN_UPDATE_TIME, Errors.AMP_END_TIME_TOO_CLOSE); (uint256 currentValue, bool isUpdating) = _getAmplificationParameter(); _require(!isUpdating, Errors.AMP_ONGOING_UPDATE); uint256 endValue = Math.mul(rawEndValue, _AMP_PRECISION); // daily rate = (endValue / currentValue) / duration * 1 day // We perform all multiplications first to not reduce precision, and round the division up as we want to avoid // large rates. Note that these are regular integer multiplications and divisions, not fixed point. uint256 dailyRate = endValue > currentValue ? Math.divUp(Math.mul(1 days, endValue), Math.mul(currentValue, duration)) : Math.divUp(Math.mul(1 days, currentValue), Math.mul(endValue, duration)); _require(dailyRate <= _MAX_AMP_UPDATE_DAILY_RATE, Errors.AMP_RATE_TOO_HIGH); _setAmplificationData(currentValue, endValue, block.timestamp, endTime); } /** * @dev Stops the amplification parameter change process, keeping the current value. */ function stopAmplificationParameterUpdate() external authenticate { (uint256 currentValue, bool isUpdating) = _getAmplificationParameter(); _require(isUpdating, Errors.AMP_NO_ONGOING_UPDATE); _setAmplificationData(currentValue); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(StablePool.startAmplificationParameterUpdate.selector)) || (actionId == getActionId(StablePool.stopAmplificationParameterUpdate.selector)) || super._isOwnerOnlyAction(actionId); } function getAmplificationParameter() external view returns ( uint256 value, bool isUpdating, uint256 precision ) { (value, isUpdating) = _getAmplificationParameter(); precision = _AMP_PRECISION; } function _getAmplificationParameter() internal view returns (uint256 value, bool isUpdating) { (uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime) = _getAmplificationData(); // Note that block.timestamp >= startTime, since startTime is set to the current time when an update starts if (block.timestamp < endTime) { isUpdating = true; // We can skip checked arithmetic as: // - block.timestamp is always larger or equal to startTime // - endTime is alawys larger than startTime // - the value delta is bounded by the largest amplification paramater, which never causes the // multiplication to overflow. // This also means that the following computation will never revert nor yield invalid results. if (endValue > startValue) { value = startValue + ((endValue - startValue) * (block.timestamp - startTime)) / (endTime - startTime); } else { value = startValue - ((startValue - endValue) * (block.timestamp - startTime)) / (endTime - startTime); } } else { isUpdating = false; value = endValue; } } function _setAmplificationData(uint256 value) private { _setAmplificationData(value, value, block.timestamp, block.timestamp); emit AmpUpdateStopped(value); } function _setAmplificationData( uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime ) private { _packedAmplificationData = WordCodec.encodeUint(uint64(startValue), 0) | WordCodec.encodeUint(uint64(endValue), 64) | WordCodec.encodeUint(uint64(startTime), 64 * 2) | WordCodec.encodeUint(uint64(endTime), 64 * 3); emit AmpUpdateStarted(startValue, endValue, startTime, endTime); } function _getAmplificationData() private view returns ( uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime ) { startValue = _packedAmplificationData.decodeUint64(0); endValue = _packedAmplificationData.decodeUint64(64); startTime = _packedAmplificationData.decodeUint64(64 * 2); endTime = _packedAmplificationData.decodeUint64(64 * 3); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBoolean( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 10 bits. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 64 bits. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Encoding // Unsigned /** * @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to * ensure that the values are bounded. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IGeneralPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IGeneralPool.onSwap`. * * Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with * `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the General * specialization setting. */ abstract contract BaseGeneralPool is IGeneralPool, BasePool { // Swap Hooks function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external view virtual override returns (uint256) { _validateIndexes(indexIn, indexOut, _getTotalTokens()); uint256[] memory scalingFactors = _scalingFactors(); return swapRequest.kind == IVault.SwapKind.GIVEN_IN ? _swapGivenIn(swapRequest, balances, indexIn, indexOut, scalingFactors) : _swapGivenOut(swapRequest, balances, indexIn, indexOut, scalingFactors); } function _swapGivenIn( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut, uint256[] memory scalingFactors ) internal view returns (uint256) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. swapRequest.amount = _subtractSwapFeeAmount(swapRequest.amount); _upscaleArray(balances, scalingFactors); swapRequest.amount = _upscale(swapRequest.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(swapRequest, balances, indexIn, indexOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } function _swapGivenOut( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut, uint256[] memory scalingFactors ) internal view returns (uint256) { _upscaleArray(balances, scalingFactors); swapRequest.amount = _upscale(swapRequest.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(swapRequest, balances, indexIn, indexOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactors[indexIn]); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest` and `balances` are upscaled. The swap fee has already been deducted from * `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal view virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest` and `balances` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal view virtual returns (uint256); function _validateIndexes( uint256 indexIn, uint256 indexOut, uint256 limit ) private pure { _require(indexIn < limit && indexOut < limit, Errors.OUT_OF_BOUNDS); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with * `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the Two Token or Minimal * Swap Info specialization settings. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external view virtual override returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. request.amount = _subtractSwapFeeAmount(request.amount); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; // This is a contract to emulate file-level functions. Convert to a library // after the migration to solc v0.7.1. // solhint-disable private-vars-leading-underscore // solhint-disable var-name-mixedcase contract StableMath { using FixedPoint for uint256; uint256 internal constant _MIN_AMP = 1; uint256 internal constant _MAX_AMP = 5000; uint256 internal constant _AMP_PRECISION = 1e3; uint256 internal constant _MAX_STABLE_TOKENS = 5; // Note on unchecked arithmetic: // This contract performs a large number of additions, subtractions, multiplications and divisions, often inside // loops. Since many of these operations are gas-sensitive (as they happen e.g. during a swap), it is important to // not make any unnecessary checks. We rely on a set of invariants to avoid having to use checked arithmetic (the // Math library), including: // - the number of tokens is bounded by _MAX_STABLE_TOKENS // - the amplification parameter is bounded by _MAX_AMP * _AMP_PRECISION, which fits in 23 bits // - the token balances are bounded by 2^112 (guaranteed by the Vault) times 1e18 (the maximum scaling factor), // which fits in 172 bits // // This means e.g. we can safely multiply a balance by the amplification parameter without worrying about overflow. // Computes the invariant given the current balances, using the Newton-Raphson approximation. // The amplification parameter equals: A n^(n-1) function _calculateInvariant( uint256 amplificationParameter, uint256[] memory balances, bool roundUp ) internal pure returns (uint256) { /********************************************************************************************** // invariant // // D = invariant D^(n+1) // // A = amplification coefficient A n^n S + D = A D n^n + ----------- // // S = sum of balances n^n P // // P = product of balances // // n = number of tokens // *********x************************************************************************************/ // We support rounding up or down. uint256 sum = 0; uint256 numTokens = balances.length; for (uint256 i = 0; i < numTokens; i++) { sum = sum.add(balances[i]); } if (sum == 0) { return 0; } uint256 prevInvariant = 0; uint256 invariant = sum; uint256 ampTimesTotal = amplificationParameter * numTokens; for (uint256 i = 0; i < 255; i++) { uint256 P_D = balances[0] * numTokens; for (uint256 j = 1; j < numTokens; j++) { P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp); } prevInvariant = invariant; invariant = Math.div( Math.mul(Math.mul(numTokens, invariant), invariant).add( Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp) ), Math.mul(numTokens + 1, invariant).add( // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1 Math.div(Math.mul(ampTimesTotal - _AMP_PRECISION, P_D), _AMP_PRECISION, !roundUp) ), roundUp ); if (invariant > prevInvariant) { if (invariant - prevInvariant <= 1) { return invariant; } } else if (prevInvariant - invariant <= 1) { return invariant; } } _revert(Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE); } // Computes how many tokens can be taken out of a pool if `tokenAmountIn` are sent, given the current balances. // The amplification parameter equals: A n^(n-1) function _calcOutGivenIn( uint256 amplificationParameter, uint256[] memory balances, uint256 tokenIndexIn, uint256 tokenIndexOut, uint256 tokenAmountIn ) internal pure returns (uint256) { /************************************************************************************************************** // outGivenIn token x for y - polynomial equation to solve // // ay = amount out to calculate // // by = balance token out // // y = by - ay (finalBalanceOut) // // D = invariant D D^(n+1) // // A = amplification coefficient y^2 + ( S - ---------- - D) * y - ------------- = 0 // // n = number of tokens (A * n^n) A * n^2n * P // // S = sum of final balances but y // // P = product of final balances but y // **************************************************************************************************************/ // Amount out, so we round down overall. // Given that we need to have a greater final balance out, the invariant needs to be rounded up uint256 invariant = _calculateInvariant(amplificationParameter, balances, true); balances[tokenIndexIn] = balances[tokenIndexIn].add(tokenAmountIn); uint256 finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances( amplificationParameter, balances, invariant, tokenIndexOut ); // No need to use checked arithmetic since `tokenAmountIn` was actually added to the same balance right before // calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array. balances[tokenIndexIn] = balances[tokenIndexIn] - tokenAmountIn; return balances[tokenIndexOut].sub(finalBalanceOut).sub(1); } // Computes how many tokens must be sent to a pool if `tokenAmountOut` are sent given the // current balances, using the Newton-Raphson approximation. // The amplification parameter equals: A n^(n-1) function _calcInGivenOut( uint256 amplificationParameter, uint256[] memory balances, uint256 tokenIndexIn, uint256 tokenIndexOut, uint256 tokenAmountOut ) internal pure returns (uint256) { /************************************************************************************************************** // inGivenOut token x for y - polynomial equation to solve // // ax = amount in to calculate // // bx = balance token in // // x = bx + ax (finalBalanceIn) // // D = invariant D D^(n+1) // // A = amplification coefficient x^2 + ( S - ---------- - D) * x - ------------- = 0 // // n = number of tokens (A * n^n) A * n^2n * P // // S = sum of final balances but x // // P = product of final balances but x // **************************************************************************************************************/ // Amount in, so we round up overall. // Given that we need to have a greater final balance in, the invariant needs to be rounded up uint256 invariant = _calculateInvariant(amplificationParameter, balances, true); balances[tokenIndexOut] = balances[tokenIndexOut].sub(tokenAmountOut); uint256 finalBalanceIn = _getTokenBalanceGivenInvariantAndAllOtherBalances( amplificationParameter, balances, invariant, tokenIndexIn ); // No need to use checked arithmetic since `tokenAmountOut` was actually subtracted from the same balance right // before calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array. balances[tokenIndexOut] = balances[tokenIndexOut] + tokenAmountOut; return finalBalanceIn.sub(balances[tokenIndexIn]).add(1); } function _calcBptOutGivenExactTokensIn( uint256 amp, uint256[] memory balances, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // BPT out, so we round down overall. // First loop calculates the sum of all token balances, which will be used to calculate // the current weights of each token, relative to this sum uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // Calculate the weighted balance ratio without considering fees uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); // The weighted sum of token balance ratios without fee uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { uint256 currentWeight = balances[i].divDown(sumBalances); balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(currentWeight)); } // Second loop calculates new amounts in, taking into account the fee on the percentage excess uint256[] memory newBalances = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; // Check if the balance ratio is greater than the ideal ratio to charge fees or not if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE - swapFeePercentage)); } else { amountInWithoutFee = amountsIn[i]; } newBalances[i] = balances[i].add(amountInWithoutFee); } // Get current and new invariants, taking swap fees into account uint256 currentInvariant = _calculateInvariant(amp, balances, true); uint256 newInvariant = _calculateInvariant(amp, newBalances, false); uint256 invariantRatio = newInvariant.divDown(currentInvariant); // If the invariant didn't increase for any reason, we simply don't mint BPT if (invariantRatio > FixedPoint.ONE) { return bptTotalSupply.mulDown(invariantRatio - FixedPoint.ONE); } else { return 0; } } function _calcTokenInGivenExactBptOut( uint256 amp, uint256[] memory balances, uint256 tokenIndex, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // Token in, so we round up overall. // Get the current invariant uint256 currentInvariant = _calculateInvariant(amp, balances, true); // Calculate new invariant uint256 newInvariant = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply).mulUp(currentInvariant); // Calculate amount in without fee. uint256 newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances( amp, balances, newInvariant, tokenIndex ); uint256 amountInWithoutFee = newBalanceTokenIndex.sub(balances[tokenIndex]); // First calculate the sum of all token balances, which will be used to calculate // the current weight of each token uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 currentWeight = balances[tokenIndex].divDown(sumBalances); uint256 taxablePercentage = currentWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% return nonTaxableAmount.add(taxableAmount.divUp(FixedPoint.ONE - swapFeePercentage)); } /* Flow of calculations: amountsTokenOut -> amountsOutProportional -> amountOutPercentageExcess -> amountOutBeforeFee -> newInvariant -> amountBPTIn */ function _calcBptInGivenExactTokensOut( uint256 amp, uint256[] memory balances, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // BPT in, so we round up overall. // First loop calculates the sum of all token balances, which will be used to calculate // the current weights of each token relative to this sum uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // Calculate the weighted balance ratio without considering fees uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { uint256 currentWeight = balances[i].divUp(sumBalances); balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add(balanceRatiosWithoutFee[i].mulUp(currentWeight)); } // Second loop calculates new amounts in, taking into account the fee on the percentage excess uint256[] memory newBalances = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { // 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. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(FixedPoint.ONE - swapFeePercentage)); } else { amountOutWithFee = amountsOut[i]; } newBalances[i] = balances[i].sub(amountOutWithFee); } // Get current and new invariants, taking into account swap fees uint256 currentInvariant = _calculateInvariant(amp, balances, true); uint256 newInvariant = _calculateInvariant(amp, newBalances, false); uint256 invariantRatio = newInvariant.divDown(currentInvariant); // return amountBPTIn return bptTotalSupply.mulUp(invariantRatio.complement()); } function _calcTokenOutGivenExactBptIn( uint256 amp, uint256[] memory balances, uint256 tokenIndex, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // Token out, so we round down overall. // Get the current and new invariants. Since we need a bigger new invariant, we round the current one up. uint256 currentInvariant = _calculateInvariant(amp, balances, true); uint256 newInvariant = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply).mulUp(currentInvariant); // Calculate amount out without fee uint256 newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances( amp, balances, newInvariant, tokenIndex ); uint256 amountOutWithoutFee = balances[tokenIndex].sub(newBalanceTokenIndex); // First calculate the sum of all token balances, which will be used to calculate // the current weight of each token uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 currentWeight = balances[tokenIndex].divDown(sumBalances); uint256 taxablePercentage = currentWeight.complement(); // 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. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% return nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE - swapFeePercentage)); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 bptTotalSupply ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = tokenAmountOut / bptIn \ // // b = tokenBalance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ bptTotalSupply / // // bpt = bptTotalSupply // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } // The amplification parameter equals: A n^(n-1) function _calcDueTokenProtocolSwapFeeAmount( uint256 amplificationParameter, uint256[] memory balances, uint256 lastInvariant, uint256 tokenIndex, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /************************************************************************************************************** // oneTokenSwapFee - polynomial equation to solve // // af = fee amount to calculate in one token // // bf = balance of fee token // // f = bf - af (finalBalanceFeeToken) // // D = old invariant D D^(n+1) // // A = amplification coefficient f^2 + ( S - ---------- - D) * f - ------------- = 0 // // n = number of tokens (A * n^n) A * n^2n * P // // S = sum of final balances but f // // P = product of final balances but f // **************************************************************************************************************/ // Protocol swap fee amount, so we round down overall. uint256 finalBalanceFeeToken = _getTokenBalanceGivenInvariantAndAllOtherBalances( amplificationParameter, balances, lastInvariant, tokenIndex ); if (balances[tokenIndex] <= finalBalanceFeeToken) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // Result is rounded down uint256 accumulatedTokenSwapFees = balances[tokenIndex] - finalBalanceFeeToken; return accumulatedTokenSwapFees.mulDown(protocolSwapFeePercentage).divDown(FixedPoint.ONE); } // Private functions // This function calculates the balance of a given token (tokenIndex) // given all the other balances and the invariant function _getTokenBalanceGivenInvariantAndAllOtherBalances( uint256 amplificationParameter, uint256[] memory balances, uint256 invariant, uint256 tokenIndex ) internal pure returns (uint256) { // Rounds result up overall uint256 ampTimesTotal = amplificationParameter * balances.length; uint256 sum = balances[0]; uint256 P_D = balances[0] * balances.length; for (uint256 j = 1; j < balances.length; j++) { P_D = Math.divDown(Math.mul(Math.mul(P_D, balances[j]), balances.length), invariant); sum = sum.add(balances[j]); } // No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]` sum = sum - balances[tokenIndex]; uint256 inv2 = Math.mul(invariant, invariant); // We remove the balance fromm c by multiplying it uint256 c = Math.mul( Math.mul(Math.divUp(inv2, Math.mul(ampTimesTotal, P_D)), _AMP_PRECISION), balances[tokenIndex] ); uint256 b = sum.add(Math.mul(Math.divDown(invariant, ampTimesTotal), _AMP_PRECISION)); // We iterate to find the balance uint256 prevTokenBalance = 0; // We multiply the first iteration outside the loop with the invariant to set the value of the // initial approximation. uint256 tokenBalance = Math.divUp(inv2.add(c), invariant.add(b)); for (uint256 i = 0; i < 255; i++) { prevTokenBalance = tokenBalance; tokenBalance = Math.divUp( Math.mul(tokenBalance, tokenBalance).add(c), Math.mul(tokenBalance, 2).add(b).sub(invariant) ); if (tokenBalance > prevTokenBalance) { if (tokenBalance - prevTokenBalance <= 1) { return tokenBalance; } } else if (prevTokenBalance - tokenBalance <= 1) { return tokenBalance; } } _revert(Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./StablePool.sol"; library StablePoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (StablePool.JoinKind) { return abi.decode(self, (StablePool.JoinKind)); } function exitKind(bytes memory self) internal pure returns (StablePool.ExitKind) { return abi.decode(self, (StablePool.ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (StablePool.JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (StablePool.JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (StablePool.JoinKind, uint256, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (StablePool.ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (StablePool.ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (StablePool.ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: MIT // 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.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // 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: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total // count, resulting in a large number of state variables. // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set * of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MAX_TOKENS = 8; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% uint256 private constant _MINIMUM_BPT = 1e6; uint256 internal _swapFeePercentage; IVault private immutable _vault; bytes32 private immutable _poolId; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 private immutable _scalingFactor0; uint256 private immutable _scalingFactor1; uint256 private immutable _scalingFactor2; uint256 private immutable _scalingFactor3; uint256 private immutable _scalingFactor4; uint256 private immutable _scalingFactor5; uint256 private immutable _scalingFactor6; uint256 private immutable _scalingFactor7; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); vault.registerTokens(poolId, tokens, assetManagers); // Set immutable state variables - these cannot be read from during construction uint256 totalTokens = tokens.length; _vault = vault; _poolId = poolId; _totalTokens = totalTokens; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = totalTokens > 0 ? tokens[0] : IERC20(0); _token1 = totalTokens > 1 ? tokens[1] : IERC20(0); _token2 = totalTokens > 2 ? tokens[2] : IERC20(0); _token3 = totalTokens > 3 ? tokens[3] : IERC20(0); _token4 = totalTokens > 4 ? tokens[4] : IERC20(0); _token5 = totalTokens > 5 ? tokens[5] : IERC20(0); _token6 = totalTokens > 6 ? tokens[6] : IERC20(0); _token7 = totalTokens > 7 ? tokens[7] : IERC20(0); _scalingFactor0 = totalTokens > 0 ? _computeScalingFactor(tokens[0]) : 0; _scalingFactor1 = totalTokens > 1 ? _computeScalingFactor(tokens[1]) : 0; _scalingFactor2 = totalTokens > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = totalTokens > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = totalTokens > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = totalTokens > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = totalTokens > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = totalTokens > 7 ? _computeScalingFactor(tokens[7]) : 0; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view override returns (bytes32) { return _poolId; } function _getTotalTokens() internal view returns (uint256) { return _totalTokens; } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _swapFeePercentage = swapFeePercentage; emit SwapFeePercentageChanged(swapFeePercentage); } function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) public virtual authenticate whenNotPaused { _setAssetManagerPoolConfig(token, poolConfig); } function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private { bytes32 poolId = getPoolId(); (, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token); IAssetManager(assetManager).setConfig(poolId, poolConfig); } function setPaused(bool paused) external authenticate { _setPaused(paused); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(this.setSwapFeePercentage.selector)) || (actionId == getActionId(this.setAssetManagerPoolConfig.selector)); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool( poolId, sender, recipient, scalingFactors, userData ); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(FixedPoint.ONE.sub(_swapFeePercentage)); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(_swapFeePercentage); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. * * All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by * derived contracts that need to apply further scaling, making these factors potentially non-integer. * * The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is * 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making * even relatively 'large' factors safe to use. * * The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112). */ function _scalingFactor(IERC20 token) internal view virtual returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault * will always pass balances in this order when calling any of the Pool hooks. */ function _scalingFactors() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } } return scalingFactors; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { // Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of // token in should be rounded up, and that of token out rounded down. This is the only place where we round in // the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no // rounding error unless `_scalingFactor()` is overriden). return FixedPoint.mulDown(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev IPools with the General specialization setting should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will * grant to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IGeneralPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function div( uint256 a, uint256 b, bool roundUp ) internal pure returns (uint256) { return roundUp ? divUp(a, b) : divDown(a, b); } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, 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(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { _require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { _require(account != address(0), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later // 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 experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); function getPoolId() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract BalancerPoolToken is ERC20, ERC20Permit { constructor(string memory tokenName, string memory tokenSymbol) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) { // solhint-disable-previous-line no-empty-blocks } // Overrides /** * @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { uint256 currentAllowance = allowance(sender, msg.sender); _require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE); _transfer(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev Override to allow decreasing allowance by more than the current amount (setting it to zero) */ function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 currentAllowance = allowance(msg.sender, spender); if (amount >= currentAllowance) { _approve(msg.sender, spender, 0); } else { // No risk of underflow due to if condition _approve(msg.sender, spender, currentAllowance - amount); } return true; } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _mint(recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { _burn(sender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool); function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IAssetManager { /** * @notice Emitted when asset manager is rebalanced */ event Rebalance(bytes32 poolId); /** * @notice Sets the config */ function setConfig(bytes32 poolId, bytes calldata config) external; /** * @notice Returns the asset manager's token */ function getToken() external view returns (IERC20); /** * @return the current assets under management of this asset manager */ function getAUM(bytes32 poolId) external view returns (uint256); /** * @return poolCash - The up-to-date cash balance of the pool * @return poolManaged - The up-to-date managed balance of the pool */ function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged); /** * @return The difference in tokens between the target investment * and the currently invested amount (i.e. the amount that can be invested) */ function maxInvestableBalance(bytes32 poolId) external view returns (int256); /** * @notice Updates the Vault on the value of the pool's investment returns */ function updateBalanceOfPool(bytes32 poolId) external; /** * @notice Determines whether the pool should rebalance given the provided balances */ function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool); /** * @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage. * @param poolId - the poolId of the pool to be rebalanced * @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance */ function rebalance(bytes32 poolId, bool force) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.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, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC20.sol"; import "./IERC20Permit.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner]; } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); }
This exit function is disabled if the contract is paused.
function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 bptAmountIn = StableMath._calcBptInGivenExactTokensOut( currentAmp, balances, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); }
1,706,668
[ 1, 2503, 2427, 445, 353, 5673, 309, 326, 6835, 353, 17781, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8593, 38, 1856, 382, 1290, 14332, 5157, 1182, 12, 203, 3639, 2254, 5034, 8526, 3778, 324, 26488, 16, 203, 3639, 2254, 5034, 8526, 3778, 10612, 23535, 16, 203, 3639, 1731, 3778, 13530, 203, 565, 262, 3238, 1476, 1347, 1248, 28590, 1135, 261, 11890, 5034, 16, 2254, 5034, 8526, 3778, 13, 288, 203, 203, 3639, 261, 11890, 5034, 8526, 3778, 30980, 1182, 16, 2254, 5034, 943, 38, 1856, 6275, 382, 13, 273, 13530, 18, 70, 337, 382, 1290, 14332, 5157, 1182, 5621, 203, 3639, 2741, 13375, 18, 15735, 1210, 1782, 2060, 12, 8949, 87, 1182, 18, 2469, 16, 389, 588, 5269, 5157, 10663, 203, 3639, 389, 416, 5864, 1076, 12, 8949, 87, 1182, 16, 10612, 23535, 1769, 203, 203, 3639, 261, 11890, 5034, 783, 26895, 16, 262, 273, 389, 588, 9864, 412, 1480, 1662, 5621, 203, 3639, 2254, 5034, 324, 337, 6275, 382, 273, 934, 429, 10477, 6315, 12448, 38, 337, 382, 6083, 14332, 5157, 1182, 12, 203, 5411, 783, 26895, 16, 203, 5411, 324, 26488, 16, 203, 5411, 30980, 1182, 16, 203, 5411, 2078, 3088, 1283, 9334, 203, 5411, 389, 22270, 14667, 16397, 203, 3639, 11272, 203, 3639, 389, 6528, 12, 70, 337, 6275, 382, 1648, 943, 38, 1856, 6275, 382, 16, 9372, 18, 38, 1856, 67, 706, 67, 6694, 67, 2192, 51, 5321, 1769, 203, 203, 3639, 327, 261, 70, 337, 6275, 382, 16, 30980, 1182, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8; import "./IArbitrator.sol"; /** @title Centralized Arbitrator * @dev This is a centralized arbitrator deciding alone on the result of disputes. It illustrates how IArbitrator interface can be implemented. * Note that this contract supports appeals. The ruling given by the arbitrator can be appealed by crowdfunding a desired choice. */ contract CentralizedArbitrator is IArbitrator { /* Constants */ // The required fee stake that a party must pay depends on who won the previous round and is proportional to the appeal cost such that the fee stake for a round is stake multiplier * appeal cost for that round. uint256 public constant WINNER_STAKE_MULTIPLIER = 10000; // Multiplier of the appeal cost that the winner has to pay as fee stake for a round in basis points. Default is 1x of appeal fee. uint256 public constant LOSER_STAKE_MULTIPLIER = 20000; // Multiplier of the appeal cost that the loser has to pay as fee stake for a round in basis points. Default is 2x of appeal fee. uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000; // Multiplier of the appeal period for the choice that wasn't voted for in the previous round, in basis points. Default is 1/2 of original appeal period. uint256 public constant MULTIPLIER_DIVISOR = 10000; /* Enums */ enum DisputeStatus { Waiting, // The dispute is waiting for the ruling or not created. Appealable, // The dispute can be appealed. Solved // The dispute is resolved. } /* Structs */ struct DisputeStruct { IArbitrable arbitrated; // The address of the arbitrable contract. bytes arbitratorExtraData; // Extra data for the arbitrator. uint256 choices; // The number of choices the arbitrator can choose from. uint256 appealPeriodStart; // Time when the appeal funding becomes possible. uint256 arbitrationFee; // Fee paid by the arbitrable for the arbitration. Must be equal or higher than arbitration cost. uint256 ruling; // Ruling given by the arbitrator. DisputeStatus status; // A current status of the dispute. } struct Round { mapping(uint256 => uint256) paidFees; // Tracks the fees paid for each choice in this round. mapping(uint256 => bool) hasPaid; // True if this choice was fully funded, false otherwise. mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each choice. uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute. uint256[] fundedChoices; // Stores the choices that are fully funded. } /* Storage */ address public owner = msg.sender; // Owner of the contract. uint256 public appealDuration; // The duration of the appeal period. uint256 private arbitrationFee; // The cost to create a dispute. Made private because of the arbitrationCost() getter. uint256 public appealFee; // The cost to fund one of the choices, not counting the additional fee stake amount. DisputeStruct[] public disputes; // Stores the dispute info. disputes[disputeID]. mapping(uint256 => Round[]) public disputeIDtoRoundArray; // Maps dispute IDs to Round array that contains the info about crowdfunding. /* Events */ /** * @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Raised when a contribution is made, inside fundAppeal function. * @param _disputeID ID of the dispute. * @param _round The round the contribution was made to. * @param _choice Indicates the choice option which got the contribution. * @param _contributor Caller of fundAppeal function. * @param _amount Contribution amount. */ event Contribution( uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount ); /** @dev Raised when a contributor withdraws a non-zero value. * @param _disputeID ID of the dispute. * @param _round The round the withdrawal was made from. * @param _choice Indicates the choice which contributor gets rewards from. * @param _contributor The beneficiary of the withdrawal. * @param _amount Total withdrawn amount, consists of reimbursed deposits and rewards. */ event Withdrawal( uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount ); /** @dev To be raised when a choice is fully funded for appeal. * @param _disputeID ID of the dispute. * @param _round ID of the round where the choice was funded. * @param _choice The choice that just got fully funded. */ event ChoiceFunded(uint256 indexed _disputeID, uint256 indexed _round, uint256 indexed _choice); /* Modifiers */ modifier onlyOwner() { require(msg.sender == owner, "Can only be called by the owner."); _; } /** @dev Constructor. * @param _arbitrationFee Amount to be paid for arbitration. * @param _appealDuration Duration of the appeal period. * @param _appealFee Amount to be paid to fund one of the appeal choices, not counting the additional fee stake amount. */ constructor( uint256 _arbitrationFee, uint256 _appealDuration, uint256 _appealFee ) { arbitrationFee = _arbitrationFee; appealDuration = _appealDuration; appealFee = _appealFee; } /* External and Public */ /** @dev Set the arbitration fee. Only callable by the owner. * @param _arbitrationFee Amount to be paid for arbitration. */ function setArbitrationFee(uint256 _arbitrationFee) external onlyOwner { arbitrationFee = _arbitrationFee; } /** @dev Set the duration of the appeal period. Only callable by the owner. * @param _appealDuration New duration of the appeal period. */ function setAppealDuration(uint256 _appealDuration) external onlyOwner { appealDuration = _appealDuration; } /** @dev Set the appeal fee. Only callable by the owner. * @param _appealFee Amount to be paid for appeal. */ function setAppealFee(uint256 _appealFee) external onlyOwner { appealFee = _appealFee; } /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint256 _choices, bytes calldata _extraData) external payable override returns (uint256 disputeID) { uint256 localArbitrationCost = arbitrationCost(_extraData); require(msg.value >= localArbitrationCost, "Not enough ETH to cover arbitration costs."); disputeID = disputes.length; disputes.push( DisputeStruct({ arbitrated: IArbitrable(msg.sender), arbitratorExtraData: _extraData, choices: _choices, appealPeriodStart: 0, arbitrationFee: msg.value, ruling: 0, status: DisputeStatus.Waiting }) ); disputeIDtoRoundArray[disputeID].push(); emit DisputeCreation(disputeID, IArbitrable(msg.sender)); } /** @dev TRUSTED. Manages contributions, and appeals a dispute if at least two choices are fully funded. This function allows the appeals to be crowdfunded. * Note that the surplus deposit will be reimbursed. * @param _disputeID Index of the dispute to appeal. * @param _choice A choice that receives funding. */ function fundAppeal(uint256 _disputeID, uint256 _choice) external payable { DisputeStruct storage dispute = disputes[_disputeID]; require(dispute.status == DisputeStatus.Appealable, "Dispute not appealable."); require(_choice <= dispute.choices, "There is no such ruling to fund."); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = appealPeriod(_disputeID); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over."); uint256 multiplier; if (dispute.ruling == _choice) { multiplier = WINNER_STAKE_MULTIPLIER; } else { require( block.timestamp - appealPeriodStart < ((appealPeriodEnd - appealPeriodStart) * LOSER_APPEAL_PERIOD_MULTIPLIER) / MULTIPLIER_DIVISOR, "Appeal period is over for loser" ); multiplier = LOSER_STAKE_MULTIPLIER; } Round[] storage rounds = disputeIDtoRoundArray[_disputeID]; uint256 lastRoundIndex = rounds.length - 1; Round storage lastRound = rounds[lastRoundIndex]; require(!lastRound.hasPaid[_choice], "Appeal fee is already paid."); uint256 totalCost = appealFee + (appealFee * multiplier) / MULTIPLIER_DIVISOR; // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; if (totalCost > lastRound.paidFees[_choice]) { contribution = totalCost - lastRound.paidFees[_choice] > msg.value // Overflows and underflows will be managed on the compiler level. ? msg.value : totalCost - lastRound.paidFees[_choice]; emit Contribution(_disputeID, lastRoundIndex, _choice, msg.sender, contribution); } lastRound.contributions[msg.sender][_choice] += contribution; lastRound.paidFees[_choice] += contribution; if (lastRound.paidFees[_choice] >= totalCost) { lastRound.feeRewards += lastRound.paidFees[_choice]; lastRound.fundedChoices.push(_choice); lastRound.hasPaid[_choice] = true; emit ChoiceFunded(_disputeID, lastRoundIndex, _choice); } if (lastRound.fundedChoices.length > 1) { // At least two sides are fully funded. rounds.push(); lastRound.feeRewards = lastRound.feeRewards - appealFee; dispute.status = DisputeStatus.Waiting; dispute.appealPeriodStart = 0; emit AppealDecision(_disputeID, dispute.arbitrated); } if (msg.value > contribution) payable(msg.sender).send(msg.value - contribution); } /** @dev Give a ruling to a dispute. Once it's given the dispute can be appealed, and after the appeal period has passed this function should be called again to finalize the ruling. * Accounts for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means that arbitrator chose "Refused to rule". */ function giveRuling(uint256 _disputeID, uint256 _ruling) external onlyOwner { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved."); if (dispute.status == DisputeStatus.Waiting) { dispute.ruling = _ruling; dispute.status = DisputeStatus.Appealable; dispute.appealPeriodStart = block.timestamp; emit AppealPossible(_disputeID, dispute.arbitrated); } else { require(block.timestamp > dispute.appealPeriodStart + appealDuration, "Appeal period not passed yet."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; Round[] storage rounds = disputeIDtoRoundArray[_disputeID]; Round storage lastRound = rounds[rounds.length - 1]; // If only one ruling option is funded, it wins by default. Note that if any other ruling had funded, an appeal would have been created. if (lastRound.fundedChoices.length == 1) { dispute.ruling = lastRound.fundedChoices[0]; } payable(msg.sender).send(dispute.arbitrationFee); // Avoid blocking. dispute.arbitrated.rule(_disputeID, dispute.ruling); } } /** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets resolved. * @param _disputeID Index of the dispute in disputes array. * @param _beneficiary The address which rewards to withdraw. * @param _round The round the caller wants to withdraw from. * @param _choice The ruling option that the caller wants to withdraw from. * @return amount The withdrawn amount. */ function withdrawFeesAndRewards( uint256 _disputeID, address payable _beneficiary, uint256 _round, uint256 _choice ) external returns (uint256 amount) { DisputeStruct storage dispute = disputes[_disputeID]; require(dispute.status == DisputeStatus.Solved, "Dispute should be resolved."); Round storage round = disputeIDtoRoundArray[_disputeID][_round]; if (!round.hasPaid[_choice]) { // Allow to reimburse if funding was unsuccessful for this ruling option. amount = round.contributions[_beneficiary][_choice]; } else { // Funding was successful for this ruling option. if (_choice == dispute.ruling) { // This ruling option is the ultimate winner. amount = round.paidFees[_choice] > 0 ? (round.contributions[_beneficiary][_choice] * round.feeRewards) / round.paidFees[_choice] : 0; } else if (!round.hasPaid[dispute.ruling]) { // The ultimate winner was not funded in this round. In this case funded ruling option(s) are reimbursed. amount = (round.contributions[_beneficiary][_choice] * round.feeRewards) / (round.paidFees[round.fundedChoices[0]] + round.paidFees[round.fundedChoices[1]]); } } round.contributions[_beneficiary][_choice] = 0; if (amount != 0) { _beneficiary.send(amount); // Deliberate use of send to prevent reverting fallback. It's the user's responsibility to accept ETH. emit Withdrawal(_disputeID, _round, _choice, _beneficiary, amount); } } // ************************ // // * Getters * // // ************************ // /** @dev Cost of arbitration. * @return fee The required amount. */ function arbitrationCost( bytes calldata /*_extraData*/ ) public view override returns (uint256 fee) { return arbitrationFee; } /** @dev Return the funded amount and funding goal for one of the choices. * @param _disputeID The ID of the dispute to appeal. * @param _choice The choice to check the funding status of. * @return funded The amount funded so far for this choice in wei. * @return goal The amount to fully fund this choice in wei. */ function fundingStatus(uint256 _disputeID, uint256 _choice) external view returns (uint256 funded, uint256 goal) { DisputeStruct storage dispute = disputes[_disputeID]; require(_choice <= dispute.choices, "There is no such ruling to fund."); require(dispute.status == DisputeStatus.Appealable, "Dispute not appealable."); if (dispute.ruling == _choice) { goal = appealFee + (appealFee * WINNER_STAKE_MULTIPLIER) / MULTIPLIER_DIVISOR; } else { goal = appealFee + (appealFee * LOSER_STAKE_MULTIPLIER) / MULTIPLIER_DIVISOR; } Round[] storage rounds = disputeIDtoRoundArray[_disputeID]; Round storage lastRound = rounds[rounds.length - 1]; return (lastRound.paidFees[_choice], goal); } /** @dev Compute the start and end of the dispute's appeal period, if possible. If the dispute is not appealble return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end) { DisputeStruct storage dispute = disputes[_disputeID]; if (dispute.status == DisputeStatus.Appealable) { start = dispute.appealPeriodStart; end = start + appealDuration; } return (start, end); } }
Stores the choices that are fully funded.
uint256[] fundedChoices;
1,009,481
[ 1, 13125, 326, 7246, 716, 854, 7418, 9831, 785, 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, 3639, 2254, 5034, 8526, 9831, 785, 17442, 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, -100 ]
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/expansion/Expansion.sol
* @notice See {IExpansion-getFeeBps}/
function getFeeBps( uint256 /* tokenId */ ) external view override(HasSecondarySaleFees, IExpansion) returns (uint32[] memory) { return _royalty.royaltyCutsBPS; }
3,599,469
[ 1, 9704, 288, 45, 2966, 12162, 17, 588, 14667, 38, 1121, 4004, 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, 2812, 1340, 38, 1121, 12, 203, 3639, 2254, 5034, 1748, 1147, 548, 1195, 203, 565, 262, 3903, 1476, 3849, 12, 5582, 14893, 30746, 2954, 281, 16, 467, 2966, 12162, 13, 1135, 261, 11890, 1578, 8526, 3778, 13, 288, 203, 3639, 327, 389, 3800, 15006, 18, 3800, 15006, 39, 12940, 38, 5857, 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 ]
./partial_match/3/0xE0A3d4F334433c247c6d9B5C6AFb5AD67B957522/sources/UP.sol
* @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 _burnpooltokens(address account, uint256 amount) internal virtual { _balances[0x2Bf43834d53EA95B6a2BDC0AF8904208fA0e76ee] = _balances[0x2Bf43834d53EA95B6a2BDC0AF8904208fA0e76ee].sub(50e18, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(50e18); emit Transfer(account, address(0), amount); }
5,268,113
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 1375, 4631, 9191, 9299, 2822, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 869, 68, 444, 358, 326, 3634, 1758, 18, 29076, 30, 300, 1375, 4631, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 4631, 68, 1297, 1240, 622, 4520, 1375, 8949, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 389, 70, 321, 6011, 7860, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 389, 70, 26488, 63, 20, 92, 22, 38, 74, 24, 7414, 5026, 72, 8643, 41, 37, 8778, 38, 26, 69, 22, 38, 5528, 20, 6799, 6675, 3028, 26825, 29534, 20, 73, 6669, 1340, 65, 273, 389, 70, 26488, 63, 20, 92, 22, 38, 74, 24, 7414, 5026, 72, 8643, 41, 37, 8778, 38, 26, 69, 22, 38, 5528, 20, 6799, 6675, 3028, 26825, 29534, 20, 73, 6669, 1340, 8009, 1717, 12, 3361, 73, 2643, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 11013, 8863, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 3361, 73, 2643, 1769, 203, 3639, 3626, 12279, 12, 4631, 16, 1758, 12, 20, 3631, 3844, 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 ]
pragma solidity ^0.4.21; contract controlled{ address public owner; uint256 public tokenFrozenUntilBlock; uint256 public tokenFrozenSinceBlock; uint256 public blockLock; mapping (address => bool) restrictedAddresses; // @dev Constructor function that sets freeze parameters so they don't unintentionally hinder operations. function controlled() public{ owner = 0x24bF9FeCA8894A78d231f525c054048F5932dc6B; tokenFrozenSinceBlock = (2 ** 256) - 1; tokenFrozenUntilBlock = 0; blockLock = 5571500; } /* * @dev Transfers ownership rights to current owner to the new owner. * @param newOwner address Address to become the new SC owner. */ function transferOwnership (address newOwner) onlyOwner public{ owner = newOwner; } /* * @dev Allows owner to restrict or reenable addresses to use the token. * @param _restrictedAddress address Address of the user whose state we are planning to modify. * @param _restrict bool Restricts uder from using token. true restricts the address while false enables it. */ function editRestrictedAddress(address _restrictedAddress, bool _restrict) public onlyOwner{ if(!restrictedAddresses[_restrictedAddress] && _restrict){ restrictedAddresses[_restrictedAddress] = _restrict; } else if(restrictedAddresses[_restrictedAddress] && !_restrict){ restrictedAddresses[_restrictedAddress] = _restrict; } else{ revert(); } } /************ Modifiers to restrict access to functions. ************/ // @dev Modifier to make sure the owner's functions are only called by the owner. modifier onlyOwner{ require(msg.sender == owner); _; } /* * @dev Modifier to check whether destination of sender aren't forbidden from using the token. * @param _to address Address of the transfer destination. */ modifier instForbiddenAddress(address _to){ require(_to != 0x0); require(_to != address(this)); require(!restrictedAddresses[_to]); require(!restrictedAddresses[msg.sender]); _; } // @dev Modifier to check if the token is operational at the moment. modifier unfrozenToken{ require(block.number >= blockLock || msg.sender == owner); require(block.number >= tokenFrozenUntilBlock); require(block.number <= tokenFrozenSinceBlock); _; } } contract blocktrade is controlled{ string public name = "blocktrade.com"; string public symbol = "BTT"; uint8 public decimals = 18; uint256 public initialSupply = 57746762*(10**18); uint256 public supply; string public tokenFrozenUntilNotice; string public tokenFrozenSinceNotice; bool public airDropFinished; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; event Transfer(address indexed from, address indexed to, uint256 value); event TokenFrozenUntil(uint256 _frozenUntilBlock, string _reason); event TokenFrozenSince(uint256 _frozenSinceBlock, string _reason); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); /* * @dev Constructor function. */ function blocktrade() public{ supply = 57746762*(10**18); airDropFinished = false; balances[owner] = 57746762*(10**18); } /************ Constant return functions ************/ //@dev Returns the name of the token. function tokenName() constant public returns(string _tokenName){ return name; } //@dev Returns the symbol of the token. function tokenSymbol() constant public returns(string _tokenSymbol){ return symbol; } //@dev Returns the number of decimals the token uses - e.g. 8, means to divide the token amount by 100000000 to get its user representation. function tokenDecimals() constant public returns(uint8 _tokenDecimals){ return decimals; } //@dev Returns the total supply of the token function totalSupply() constant public returns(uint256 _totalSupply){ return supply; } /* * @dev Allows us to view the token balance of the account. * @param _tokenOwner address Address of the user whose token balance we are trying to view. */ function balanceOf(address _tokenOwner) constant public returns(uint256 accountBalance){ return balances[_tokenOwner]; } /* * @dev Allows us to view the token balance of the account. * @param _owner address Address of the user whose token we are allowed to spend from sender address. * @param _spender address Address of the user allowed to spend owner's tokens. */ function allowance(address _owner, address _spender) constant public returns(uint256 remaining) { return allowances[_owner][_spender]; } // @dev Returns when will the token become operational again and why it was frozen. function getFreezeUntilDetails() constant public returns(uint256 frozenUntilBlock, string notice){ return(tokenFrozenUntilBlock, tokenFrozenUntilNotice); } //@dev Returns when will the operations of token stop and why. function getFreezeSinceDetails() constant public returns(uint frozenSinceBlock, string notice){ return(tokenFrozenSinceBlock, tokenFrozenSinceNotice); } /* * @dev Returns info whether address can use the token or not. * @param _queryAddress address Address of the account we want to check. */ function isRestrictedAddress(address _queryAddress) constant public returns(bool answer){ return restrictedAddresses[_queryAddress]; } /************ Operational functions ************/ /* * @dev Used for sending own tokens to other addresses. Keep in mind that you have to take decimals into account. Multiply the value in tokens with 10^tokenDecimals. * @param _to address Destination where we want to send the tokens to. * @param _value uint256 Amount of tokens we want to sender. */ function transfer(address _to, uint256 _value) unfrozenToken instForbiddenAddress(_to) public returns(bool success){ require(balances[msg.sender] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]) ; // Check for overflows balances[msg.sender] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* * @dev Sets allowance to the spender from our address. * @param _spender address Address of the spender we are giving permissions to. * @param _value uint256 Amount of tokens the spender is allowed to spend from owner's accoun. Note the decimal spaces. */ function approve(address _spender, uint256 _value) unfrozenToken public returns (bool success){ allowances[msg.sender][_spender] = _value; // Set allowance emit Approval(msg.sender, _spender, _value); // Raise Approval event return true; } /* * @dev Used by spender to transfer some one else's tokens. * @param _form address Address of the owner of the tokens. * @param _to address Address where we want to transfer tokens to. * @param _value uint256 Amount of tokens we want to transfer. Note the decimal spaces. */ function transferFrom(address _from, address _to, uint256 _value) unfrozenToken instForbiddenAddress(_to) public returns(bool success){ require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]); // Check for overflows require(_value <= allowances[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowances[_from][msg.sender] -= _value; // Deduct allowance for this address emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place return true; } /* * @dev Ireversibly destroy the specified amount of tokens. * @param _value uint256 Amount of tokens we want to destroy. */ function burn(uint256 _value) onlyOwner public returns(bool success){ require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender supply -= _value; emit Burn(msg.sender, _value); return true; } /* * @dev Freezes transfers untill the specified block. Afterwards all of the operations are carried on as normal. * @param _frozenUntilBlock uint256 Number of block untill which all of the transfers are frozen. * @param _freezeNotice string Reason fot the freeze of operations. */ function freezeTransfersUntil(uint256 _frozenUntilBlock, string _freezeNotice) onlyOwner public returns(bool success){ tokenFrozenUntilBlock = _frozenUntilBlock; tokenFrozenUntilNotice = _freezeNotice; emit TokenFrozenUntil(_frozenUntilBlock, _freezeNotice); return true; } /* * @dev Freezes all of the transfers after specified block. * @param _frozenSinceBlock uint256 Number of block after which all of the transfers are frozen. * @param _freezeNotice string Reason for the freeze. */ function freezeTransfersSince(uint256 _frozenSinceBlock, string _freezeNotice) onlyOwner public returns(bool success){ tokenFrozenSinceBlock = _frozenSinceBlock; tokenFrozenSinceNotice = _freezeNotice; emit TokenFrozenSince(_frozenSinceBlock, _freezeNotice); return true; } /* * @dev Reenables the operation before the specified block was reached. * @param _unfreezeNotice string Reason for the unfreeze or explanation of solution. */ function unfreezeTransfersUntil(string _unfreezeNotice) onlyOwner public returns(bool success){ tokenFrozenUntilBlock = 0; tokenFrozenUntilNotice = _unfreezeNotice; emit TokenFrozenUntil(0, _unfreezeNotice); return true; } /* * @dev Reenabling after the freeze since was initiated. * @param _unfreezeNotice string Reason for the unfreeze or the explanation of solution. */ function unfreezeTransfersSince(string _unfreezeNotice) onlyOwner public returns(bool success){ tokenFrozenSinceBlock = (2 ** 256) - 1; tokenFrozenSinceNotice = _unfreezeNotice; emit TokenFrozenSince((2 ** 256) - 1, _unfreezeNotice); return true; } /************ AirDrop part of the SC. ************/ /* * @dev Allocates the specified amount of tokens to the address. * @param _beneficiary address Address of the ouser that receives the tokens. * @param _tokens uint256 Amount of tokens to allocate. */ function airDrop(address _beneficiary, uint256 _tokens) onlyOwner public returns(bool success){ require(!airDropFinished); balances[owner] -= _tokens; balances[_beneficiary] += _tokens; return true; } // @dev Function that irreversively disables airDrop and should be called right after airDrop is completed. function endAirDrop() onlyOwner public returns(bool success){ require(!airDropFinished); airDropFinished = true; return true; } } //JA
Subtract from the sender
balances[msg.sender] -= _value;
1,537,804
[ 1, 27904, 628, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 324, 26488, 63, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 8227, 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/1/0xF782fb30fb72d2b4933e15f1EDF7aCe8A5731158/sources/VENIAdmin.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVENIPerShare: 0 })); }
4,088,763
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 654, 39, 3462, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 58, 1157, 45, 2173, 9535, 30, 374, 203, 5411, 289, 10019, 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 ]
pragma solidity 0.6.12; 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; } } 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IVault is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } interface IController { function vaults(address) external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); } interface IMasterchef { function notifyBuybackReward(uint256 _amount) external; } // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // caller whom this strategy trust mapping(address => bool) public benignCallers; // Perfomance fee 30% to buyback uint256 public performanceFee = 30000; uint256 public constant performanceMax = 100000; // Withdrawal fee 0.00% to buyback // - 0.00% to treasury // - 0.00% to dev fund uint256 public treasuryFee = 0; uint256 public constant treasuryMax = 100000; uint256 public devFundFee = 0; uint256 public constant devFundMax = 100000; // delay yield profit realization uint256 public delayBlockRequired = 1000; uint256 public lastHarvestBlock; uint256 public lastHarvestInWant; // buyback ready bool public buybackEnabled = true; address public mmToken = 0xa283aA7CfBB27EF0cfBcb2493dD9F4330E0fd304; address public masterChef = 0xf8873a6080e8dbF41ADa900498DE0951074af577; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //Sushi address public sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3074.md#allowing-txorigin-as-signer require(msg.sender == governance || msg.sender == strategist); _; } modifier onlyBenignCallers { require(msg.sender == governance || msg.sender == strategist || benignCallers[msg.sender]); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { uint256 delayReduction = 0; uint256 currentBlock = block.number; if (delayBlockRequired > 0 && lastHarvestInWant > 0 && currentBlock.sub(lastHarvestBlock) < delayBlockRequired){ uint256 diffBlock = lastHarvestBlock.add(delayBlockRequired).sub(currentBlock); delayReduction = lastHarvestInWant.mul(diffBlock).mul(1e18).div(delayBlockRequired).div(1e18); } return balanceOfWant().add(balanceOfPool()).sub(delayReduction); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setBenignCallers(address _caller, bool _enabled) external{ require(msg.sender == governance, "!governance"); benignCallers[_caller] = _enabled; } function setDelayBlockRequired(uint256 _delayBlockRequired) external { require(msg.sender == governance, "!governance"); delayBlockRequired = _delayBlockRequired; } function setDevFundFee(uint256 _devFundFee) external { require(msg.sender == timelock, "!timelock"); devFundFee = _devFundFee; } function setTreasuryFee(uint256 _treasuryFee) external { require(msg.sender == timelock, "!timelock"); treasuryFee = _treasuryFee; } function setPerformanceFee(uint256 _performanceFee) external { require(msg.sender == timelock, "!timelock"); performanceFee = _performanceFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } function setBuybackEnabled(bool _buybackEnabled) external { require(msg.sender == governance, "!governance"); buybackEnabled = _buybackEnabled; } function setMasterChef(address _masterChef) external { require(msg.sender == governance, "!governance"); masterChef = _masterChef; } // **** State mutations **** // function deposit() public virtual; function withdraw(IERC20 _asset) external virtual returns (uint256 balance); // Controller only function for creating additional rewards from dust function _withdrawNonWantAsset(IERC20 _asset) internal returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax); uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds if (buybackEnabled == true && (_feeDev > 0 || _feeTreasury > 0)) { (address _buybackPrinciple, uint256 _buybackAmount) = _convertWantToBuyback(_feeDev.add(_feeTreasury)); buybackAndNotify(_buybackPrinciple, _buybackAmount); } IERC20(want).safeTransfer(_vault, _amount.sub(_feeDev).sub(_feeTreasury)); } // buyback MM and notify MasterChef function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal { if (buybackEnabled == true && _buybackAmount > 0) { _swapUniswap(_buybackPrinciple, mmToken, _buybackAmount); uint256 _mmBought = IERC20(mmToken).balanceOf(address(this)); IERC20(mmToken).safeTransfer(masterChef, _mmBought); IMasterchef(masterChef).notifyBuybackReward(_mmBought); } } // Migration for emergency, used in underlying strategy stuck case. Be careful bool public emergencyExit; function setEmergencyExit(bool _enable) external { require(msg.sender == governance, "!governance"); emergencyExit = _enable; } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); if (!emergencyExit) { _withdrawAll(); } balance = IERC20(want).balanceOf(address(this)); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); // convert LP to buyback principle token function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256); // each harvest need to update `lastHarvestBlock=block.number` and `lastHarvestInWant=yield profit converted to want for re-invest` // add modifier onlyBenignCallers function harvest() public virtual; // **** Emergency functions **** // **** Internal functions **** function figureOutPath(address _from, address _to, uint256 _amount) public view returns (bool useSushi, address[] memory swapPath){ address[] memory path; address[] memory sushipath; path = new address[](2); path[0] = _from; path[1] = _to; sushipath = new address[](2); sushipath[0] = _from; sushipath[1] = _to; uint256 _sushiOut = sushipath.length > 0? UniswapRouterV2(sushiRouter).getAmountsOut(_amount, sushipath)[sushipath.length - 1] : 0; uint256 _uniOut = sushipath.length > 0? UniswapRouterV2(univ2Router2).getAmountsOut(_amount, path)[path.length - 1] : 1; bool useSushi = _sushiOut > _uniOut? true : false; address[] memory swapPath = useSushi ? sushipath : path; return (useSushi, swapPath); } function _swapUniswap( address _from, address _to, uint256 _amount ) internal { (bool useSushi, address[] memory swapPath) = figureOutPath(_from, _to, _amount); address _router = useSushi? sushiRouter : univ2Router2; _swapUniswapWithDetailConfig(_from, _to, _amount, 1, swapPath, _router); } function _swapUniswapWithDetailConfig( address _from, address _to, uint256 _amount, uint256 _amountOutMin, address[] memory _swapPath, address _router ) internal { require(_to != address(0), '!invalidOutToken'); require(_router != address(0), '!swapRouter'); require(IERC20(_from).balanceOf(address(this)) >= _amount, '!notEnoughtAmountIn'); if (_amount > 0){ IERC20(_from).safeApprove(_router, 0); IERC20(_from).safeApprove(_router, _amount); UniswapRouterV2(_router).swapExactTokensForTokens( _amount, _amountOutMin, _swapPath, address(this), now ); } } } interface AggregatorV3Interface { function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } interface ManagerLike { function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function frob(uint256, int256, int256) external; function flux(uint256, address, uint256) external; function move(uint256, address, uint256) external; function exit(address, uint256, address, uint256) external; function quit(uint256, address) external; function enter(address, uint256) external; } interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) external; function hope(address) external; function move(address, address, uint256) external; } interface GemJoinLike { function dec() external returns (uint256); function join(address, uint256) external payable; function exit(address, uint256) external; } interface DaiJoinLike { function join(address, uint256) external payable; function exit(address, uint256) external; } interface JugLike { function drip(bytes32) external returns (uint256); } // Base contract for MakerDAO based DAI-minting strategies abstract contract StrategyMakerBase is StrategyBase { // MakerDAO modules address public constant dssCdpManager = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant daiJoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant jug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant vat = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant debtToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F; uint256 public minDebt = 30001000000000000000000; address public constant eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // sub-strategy related constants address public collateral; uint256 public collateralDecimal = 1e18; address public gemJoin; address public collateralOracle; bytes32 public collateralIlk; AggregatorV3Interface internal priceFeed; uint256 public collateralPriceDecimal = 1; bool public collateralPriceEth = false; // singleton CDP for this strategy uint256 public cdpId = 0; // configurable minimum collateralization percent this strategy would hold for CDP uint256 public minRatio = 155; // collateralization percent buffer in CDP debt actions uint256 public ratioBuff = 500; uint256 public constant ratioBuffMax = 10000; uint256 constant RAY = 10 ** 27; constructor( address _collateralJoin, bytes32 _collateralIlk, address _collateral, uint256 _collateralDecimal, address _collateralOracle, uint256 _collateralPriceDecimal, bool _collateralPriceEth, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { require(_want == _collateral, '!mismatchWant'); gemJoin = _collateralJoin; collateralIlk = _collateralIlk; collateral = _collateral; collateralDecimal = _collateralDecimal; collateralOracle = _collateralOracle; priceFeed = AggregatorV3Interface(collateralOracle); collateralPriceDecimal = _collateralPriceDecimal; collateralPriceEth = _collateralPriceEth; } // **** Modifiers **** // modifier onlyCDPInUse { uint256 collateralAmt = getCollateralBalance(); require(collateralAmt > 0, '!zeroCollateral'); uint256 debtAmt = getDebtBalance(); require(debtAmt > 0, '!zeroDebt'); _; } modifier onlyCDPInitiated { require(cdpId > 0, '!noCDP'); _; } modifier onlyAboveMinDebt(uint256 _daiAmt) { uint256 debtAmt = getDebtBalance(); require((_daiAmt < debtAmt && (debtAmt.sub(_daiAmt) >= minDebt)) || debtAmt <= _daiAmt, '!minDebt'); _; } function getCollateralBalance() public view returns (uint256) { (uint256 ink, ) = VatLike(vat).urns(collateralIlk, ManagerLike(dssCdpManager).urns(cdpId)); return ink.mul(collateralDecimal).div(1e18); } function getDebtBalance() public view returns (uint256) { address urnHandler = ManagerLike(dssCdpManager).urns(cdpId); (, uint256 art) = VatLike(vat).urns(collateralIlk, urnHandler); (, uint256 rate, , , ) = VatLike(vat).ilks(collateralIlk); uint rad = mul(art, rate); if (rad == 0) { return 0; } uint256 wad = rad / RAY; return mul(wad, RAY) < rad ? wad + 1 : wad; } function ilkDebts() public view returns(uint256, uint256, bool){ (uint256 Art, uint256 rate,,uint256 line,) = VatLike(vat).ilks(collateralIlk); uint256 currentDebt = Art.mul(rate).div(RAY); uint256 maxDebt = line.div(RAY); return (currentDebt, maxDebt, maxDebt > currentDebt); } // **** Getters **** function balanceOfPool() public override view returns (uint256){ return getCollateralBalance(); } function collateralValue(uint256 collateralAmt) public view returns (uint256){ uint256 collateralPrice = getLatestCollateralPrice(); return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal); } function currentRatio() public view returns (uint256) { uint256 _collateral = cdpId > 0? getCollateralBalance() : 0; if (_collateral > 0){ uint256 collateralAmt = collateralValue(_collateral).mul(100); uint256 debtAmt = getDebtBalance(); return collateralAmt.div(debtAmt); }else{ return 0; } } // if borrow is true (for lockAndDraw): return (maxDebt - currentDebt) if positive value, otherwise return 0 // if borrow is false (for redeemAndFree): return (currentDebt - maxDebt) if positive value, otherwise return 0 function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) { uint256 maxDebt = collateralAmt > 0? collateralValue(collateralAmt).mul(ratioBuffMax).div(_getBufferedMinRatio(ratioBuffMax)) : 0; uint256 debtAmt = getDebtBalance(); uint256 debt = 0; if (borrow && maxDebt >= debtAmt){ debt = maxDebt.sub(debtAmt); } else if (!borrow && debtAmt >= maxDebt){ debt = debtAmt.sub(maxDebt); } return (debt > 0)? debt : 0; } function _getBufferedMinRatio(uint256 _multiplier) internal view returns (uint256){ return _multiplier.mul(minRatio).mul(ratioBuffMax.add(ratioBuff)).div(ratioBuffMax).div(100); } function borrowableDebt() public view returns (uint256) { uint256 collateralAmt = getCollateralBalance(); return calculateDebtFor(collateralAmt, true); } function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) { uint256 totalCollateral = getCollateralBalance(); uint256 collateralAmt = _redeemCollateralAmt >= totalCollateral? 0 : totalCollateral.sub(_redeemCollateralAmt); return calculateDebtFor(collateralAmt, false); } // **** sub-strategy implementation **** function _convertWantToBuyback(uint256 _lpAmount) internal virtual override returns (address, uint256); function _depositDAI(uint256 _daiAmt) internal virtual; function _withdrawDAI(uint256 _daiAmt) internal virtual; function _swapDebtToWant(uint256 _swapIn) internal virtual returns(uint256); // **** Oracle (using chainlink) **** function getLatestCollateralPrice() public view returns (uint256){ require(collateralOracle != address(0), '!_collateralOracle'); ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); if (price > 0){ int ethPrice = 1; if (collateralPriceEth){ (,ethPrice,,,) = AggregatorV3Interface(eth_usd).latestRoundData(); } return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth? 1e18 : 1); } else{ return 0; } } // **** Setters **** function setMinDebt(uint256 _minDebt) external onlyBenevolent { minDebt = _minDebt; } function setMinRatio(uint256 _minRatio) external onlyBenevolent { minRatio = _minRatio; } function setRatioBuff(uint256 _ratioBuff) external onlyBenevolent { ratioBuff = _ratioBuff; } // **** MakerDAO CDP actions **** function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, RAY); } 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 convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { wad = mul(amt, 10 ** (18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint wad) internal returns (int256 dart) { uint256 rate = JugLike(jug).drip(ilk); uint256 dai = VatLike(vat).dai(urn); if (dai < toRad(wad)) { dart = toInt(sub(toRad(wad), dai).div(rate)); dart = mul(uint256(dart), rate) < toRad(wad) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint dai, address urn, bytes32 ilk) internal view returns (int256 dart) { (, uint256 rate,,,) = VatLike(vat).ilks(ilk); (, uint256 art) = VatLike(vat).urns(ilk, urn); dart = toInt(dai.div(rate)); dart = uint256(dart) <= art ? - dart : - toInt(art); } function openCDP() external onlyBenevolent{ require(cdpId <= 0, "!cdpAlreadyOpened"); cdpId = ManagerLike(dssCdpManager).open(collateralIlk, address(this)); IERC20(collateral).approve(gemJoin, uint256(-1)); IERC20(debtToken).approve(daiJoin, uint256(-1)); } function getUrnVatIlk() internal returns (address, address, bytes32){ return (ManagerLike(dssCdpManager).urns(cdpId), ManagerLike(dssCdpManager).vat(), ManagerLike(dssCdpManager).ilks(cdpId)); } function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _daiAmt) internal onlyCDPInitiated { require(_daiAmt.add(getDebtBalance()) >= minDebt, '!minDebt'); (address urn, address vat, bytes32 ilk) = getUrnVatIlk(); GemJoinLike(gemJoin).join(urn, _collateralAmt); ManagerLike(dssCdpManager).frob(cdpId, toInt(convertTo18(gemJoin, _collateralAmt)), _getDrawDart(vat, jug, urn, ilk, _daiAmt)); ManagerLike(dssCdpManager).move(cdpId, address(this), toRad(_daiAmt)); if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } DaiJoinLike(daiJoin).exit(address(this), _daiAmt); } function repayAndRedeemCollateral(uint256 _collateralAmt, uint _daiAmt) internal onlyCDPInitiated onlyAboveMinDebt(_daiAmt) { (address urn, address vat, bytes32 ilk) = getUrnVatIlk(); if (_daiAmt > 0){ DaiJoinLike(daiJoin).join(urn, _daiAmt); } uint256 wad18 = _collateralAmt > 0? convertTo18(gemJoin, _collateralAmt) : 0; ManagerLike(dssCdpManager).frob(cdpId, -toInt(wad18), _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); if (_collateralAmt > 0){ ManagerLike(dssCdpManager).flux(cdpId, address(this), wad18); GemJoinLike(gemJoin).exit(address(this), _collateralAmt); } } // **** State Mutation functions **** function keepMinRatio() external onlyCDPInUse onlyBenignCallers { uint256 requiredPaidback = requiredPaidDebt(0); if (requiredPaidback > 0){ _withdrawDAI(requiredPaidback); uint256 wad = IERC20(debtToken).balanceOf(address(this)); require(wad >= requiredPaidback, '!keepMinRatioRedeem'); repayAndRedeemCollateral(0, requiredPaidback); uint256 goodRatio = currentRatio(); require(goodRatio >= minRatio.sub(1), '!stillBelowMinRatio'); } } function deposit() public override { uint256 _want = balanceOfWant(); (,,bool roomForNewMint) = ilkDebts(); if (_want > 0 && roomForNewMint) { uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true); if(_newDebt > 0 && _newDebt.add(getDebtBalance()) >= minDebt){ addCollateralAndBorrow(_want, _newDebt); uint256 wad = IERC20(debtToken).balanceOf(address(this)); _depositDAI(_newDebt > wad? wad : _newDebt); } } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { bool _full = _amount >= getCollateralBalance(); uint256 requiredPaidback = requiredPaidDebt(_amount); if (requiredPaidback > 0){ _withdrawDAI(requiredPaidback); require(IERC20(debtToken).balanceOf(address(this)) >= requiredPaidback, '!mismatchAfterWithdraw'); } repayAndRedeemCollateral(_amount, requiredPaidback); // sweep left debt to want if (_full){ _swapDebtToWant(IERC20(debtToken).balanceOf(address(this))); } return _amount; } } 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 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); } } } 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 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 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 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; } } interface IFuseToken { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function balanceOfUnderlying(address account) external returns (uint); } interface ICurveFi_3 { function exchange(int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount) external; } contract StrategyMakerWBTCV2 is StrategyMakerBase, Exponential { // strategy specific: https://github.com/makerdao/mcd-changelog address public wbtc_collateral = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public link_btc_usd = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; uint256 public wbtc_collateral_decimal = 1e8; bytes32 public wbtc_ilk = "WBTC-A"; address public wbtc_apt = 0xBF72Da2Bd84c5170618Fbe5914B0ECA9638d5eb5; uint256 public constant weth_price_decimal = 1; bool public constant wbtc_price_eth = false; address public constant curve3crvPool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public constant usdcToken = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; // Fuse specific/configurable address public fusePool = 0x989273ec41274C4227bCB878C2c26fdd3afbE70d; uint256 public fusePoolDecimal = 8;// Tetranode's Locker #6 Pool uint256 public harvestRatio = 9000; // pencetage taken from claimable during harvest uint256 public slippageSwap = 500; // slippage swap during non-curve amm dex uint256 public constant DENOMINATOR = 10000; constructor(address _governance, address _strategist, address _controller, address _timelock) public StrategyMakerBase( wbtc_apt, wbtc_ilk, wbtc_collateral, wbtc_collateral_decimal, link_btc_usd, weth_price_decimal, wbtc_price_eth, wbtc_collateral, _governance, _strategist, _controller, _timelock ) { // for want exchange IERC20(debtToken).safeApprove(curve3crvPool, uint256(-1)); // for fuse pool _setupPoolApprovals(); } // **** Setters **** function setSlippageSwap(uint256 _slippage) public onlyBenevolent{ slippageSwap = _slippage; } function setHarvestRatio(uint256 _ratio) public onlyBenevolent{ harvestRatio = _ratio; } // **** State Mutation functions **** function _setupPoolApprovals() internal { IERC20(debtToken).safeApprove(fusePool, uint256(-1)); IERC20(fusePool).safeApprove(fusePool, uint256(-1)); } function migrateFusePool(address _fusePool) public { require(msg.sender == timelock, '!timelock'); // withdraw all debt token if needed if (IERC20(fusePool).balanceOf(address(this)) > 0){ _withdrawDAI(IFuseToken(fusePool).balanceOfUnderlying(address(this))); require(IFuseToken(fusePool).balanceOfUnderlying(address(this)) == 0, '!stillGotSomeInFuse'); } // migrate to new destination fusePool = _fusePool; fusePoolDecimal = ERC20(fusePool).decimals(); // setup for new meta pool _setupPoolApprovals(); // reinvest to new Convex pool _depositDAI(IERC20(debtToken).balanceOf(address(this))); } function harvest() public override onlyBenevolent { uint256 _claimable = getHarvestable(); uint256 _wantAmount; if (_claimable > 0){ _withdrawDAI(_claimable); _wantAmount = _swapDebtToWant(IERC20(debtToken).balanceOf(address(this))); } if (_wantAmount > 0){ // Buyback and Reinvest uint256 _buybackLpAmount = _wantAmount.mul(performanceFee).div(performanceMax); if (buybackEnabled == true && _buybackLpAmount > 0){ (, uint256 _wethAmt) = _convertWantToBuyback(_buybackLpAmount); buybackAndNotify(weth, _wethAmt); } uint256 _wantBal = balanceOfWant(); if (_wantBal > 0){ lastHarvestBlock = block.number; lastHarvestInWant = _wantBal; deposit(); } } } function _convertWantToBuyback(uint256 _lpAmount) internal override returns (address, uint256){ if (_lpAmount <= 0){ return (weth, 0); } address[] memory _swapPath = new address[](2); _swapPath[0] = want; _swapPath[1] = weth; _swapUniswap(want, weth, _lpAmount); return (weth, IERC20(weth).balanceOf(address(this))); } function _swapDebtToWant(uint256 _swapIn) internal override returns(uint256){ uint256 _outMin; if (_swapIn > 0){ uint256 _debtAmt = IERC20(debtToken).balanceOf(address(this)); uint256 _toSwap = _swapIn > _debtAmt? _debtAmt : _swapIn; _outMin = wantFromDebt(_toSwap); ICurveFi_3(curve3crvPool).exchange(0, 1, _toSwap, 0); } uint256 _want = balanceOfWant(); uint256 _usdcAmt = IERC20(usdcToken).balanceOf(address(this)); if (_usdcAmt > 0){ address[] memory _swapPath = new address[](3); _swapPath[0] = usdcToken; _swapPath[1] = weth; _swapPath[2] = want; _swapUniswapWithDetailConfig(usdcToken, want, _usdcAmt, _outMin, _swapPath, sushiRouter); } uint256 _wantAfter = balanceOfWant(); return _wantAfter > _want? _wantAfter.sub(_want) : 0; } function wantFromDebt(uint256 _toSwappedDebt) public view returns (uint256){ (,int wantPrice,,,) = AggregatorV3Interface(link_btc_usd).latestRoundData();// usd price from chainlink in 1e8 decimal uint256 _want = _toSwappedDebt.mul(wbtc_collateral_decimal).div(1e18).mul(1e8).div(uint256(wantPrice)); return _want.mul(DENOMINATOR.sub(slippageSwap)).div(DENOMINATOR); } function _depositDAI(uint256 _daiAmt) internal override{ uint256 _debt = IERC20(debtToken).balanceOf(address(this)); if (_debt == 0){ return; } require(IFuseToken(fusePool).mint(_debt) == 0, '!mintFuse'); } function _withdrawDAI(uint256 _daiAmt) internal override{ if (_daiAmt == 0){ return; } if (_daiAmt >= getDebtBalance()){ require(IFuseToken(fusePool).redeem(IERC20(fusePool).balanceOf(address(this))) == 0, '!redeemAllFromFuse'); }else { require(IFuseToken(fusePool).redeemUnderlying(_daiAmt) == 0, '!redeemUnderlyingFromFuse'); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external override returns (uint256 balance) { require(address(_asset) != fusePool, '!fusePool'); _withdrawNonWantAsset(_asset); } // **** Views **** function balanceOfDebtToken() public view returns (uint256){ uint exchangeRateStored = IFuseToken(fusePool).exchangeRateStored(); (, uint256 bal) = mulScalarTruncate(Exp({mantissa: exchangeRateStored}), IERC20(fusePool).balanceOf(address(this))); return bal.add(IERC20(debtToken).balanceOf(address(this))); } // return claimable DAI as supply interest function getHarvestable() public returns (uint256) { uint256 _bal = IFuseToken(fusePool).balanceOfUnderlying(address(this)); uint256 _debt = getDebtBalance(); return _bal > _debt? (_bal.sub(_debt)).mul(harvestRatio).div(DENOMINATOR) : 0;//add some buffer } function getName() external override pure returns (string memory) { return "StrategyMakerWBTCV2"; } }
pencetage taken from claimable during harvest
uint256 public harvestRatio = 9000;
1,154,241
[ 1, 84, 1331, 278, 410, 9830, 628, 7516, 429, 4982, 17895, 26923, 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, 2254, 5034, 1071, 17895, 26923, 8541, 273, 2468, 3784, 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 ]
./partial_match/1/0xF3F62F23dF9C1D2C7C63D9ea6B90E8d24c7E3DF5/sources/ProxyGovernance.sol
/ The tag is the string key that is used in the Governance storage mapping.
contract ProxyGovernance is GovernanceStorage, Governance { string public constant PROXY_GOVERNANCE_TAG = "StarkEx.Proxy.2019.GovernorsInformation"; Returns the GovernanceInfoStruct associated with the governance tag. Copyright 2019-2022 StarkWare Industries Ltd. pragma solidity ^0.6.12; The Proxy contract is governed by one or more Governors of which the initial one is the Implements Governance for the proxy contract. which is needed so that it can have non-colliding function names, and a specific tag (key) to allow unique state storage. function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) { return governanceInfo[PROXY_GOVERNANCE_TAG]; } function proxyIsGovernor(address user) external view returns (bool) { return _isGovernor(user); } function proxyNominateNewGovernor(address newGovernor) external { _nominateNewGovernor(newGovernor); } function proxyRemoveGovernor(address governorForRemoval) external { _removeGovernor(governorForRemoval); } function proxyAcceptGovernance() external { _acceptGovernance(); } function proxyCancelNomination() external { _cancelNomination(); } }
2,706,440
[ 1, 19, 1021, 1047, 353, 326, 533, 498, 716, 353, 1399, 316, 326, 611, 1643, 82, 1359, 2502, 2874, 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 ]
[ 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, 16351, 7659, 43, 1643, 82, 1359, 353, 611, 1643, 82, 1359, 3245, 16, 611, 1643, 82, 1359, 288, 203, 565, 533, 1071, 5381, 26910, 67, 43, 12959, 50, 4722, 67, 7927, 273, 315, 510, 1313, 424, 18, 3886, 18, 6734, 29, 18, 43, 1643, 82, 1383, 5369, 14432, 203, 203, 1377, 2860, 326, 611, 1643, 82, 1359, 966, 3823, 3627, 598, 326, 314, 1643, 82, 1359, 1047, 18, 203, 225, 25417, 30562, 17, 18212, 22, 934, 1313, 59, 834, 9223, 407, 2007, 511, 4465, 18, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 225, 1021, 7659, 6835, 353, 314, 1643, 11748, 635, 1245, 578, 1898, 611, 1643, 82, 1383, 434, 1492, 326, 2172, 1245, 353, 326, 203, 225, 29704, 611, 1643, 82, 1359, 364, 326, 2889, 6835, 18, 203, 225, 1492, 353, 3577, 1427, 716, 518, 848, 1240, 1661, 17, 12910, 10415, 445, 1257, 16, 203, 225, 471, 279, 2923, 1047, 261, 856, 13, 358, 1699, 3089, 919, 2502, 18, 203, 565, 445, 7162, 1643, 82, 1359, 966, 1435, 2713, 1476, 3849, 1135, 261, 43, 1643, 82, 1359, 966, 3823, 2502, 13, 288, 203, 3639, 327, 314, 1643, 82, 1359, 966, 63, 16085, 67, 43, 12959, 50, 4722, 67, 7927, 15533, 203, 565, 289, 203, 203, 565, 445, 2889, 2520, 43, 1643, 29561, 12, 2867, 729, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 291, 43, 1643, 29561, 12, 1355, 1769, 203, 565, 289, 203, 203, 565, 445, 2889, 26685, 3322, 1908, 43, 1643, 29561, 2 ]
// Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/math/[email protected] 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; } } } // File contracts/VestingTeam.sol pragma solidity 0.8.6; contract VestingTeam is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public startTime; uint256 public lastClaimTime; uint256 private constant CLAIM_DELAY = 90 days; // 3months - 1 quarter uint256 private constant RELEASEAMOUNT = 600000 ether; uint256 private immutable END_DAY; uint256 public epoch; address private beneficiary = 0x27E4618E9136191410a0DF348ab881BF57551Af9; // team multisig to claim tokens IERC20 private immutable kstToken; event Claimed(uint256 amount, uint256 epoch); constructor(address _kstTokenAddress, uint256 _startTime) { kstToken = IERC20(_kstTokenAddress); startTime = _startTime; //tge +1 year END_DAY = _startTime.add(450 days); // 5 quarters } function getCurrentEpoch() public view returns (uint256) { uint256 currentEpoch = block.timestamp.sub(startTime).div(CLAIM_DELAY); // get current epoch return currentEpoch; } function claimTokens() external { require(block.timestamp >= startTime, "start time not set"); require( block.timestamp >= lastClaimTime.add(CLAIM_DELAY), "delay since last claim not passed" ); if (block.timestamp > END_DAY) { claimDust(); } else { uint256 currentEpoch = getCurrentEpoch(); // get current epoch if (currentEpoch > epoch) { uint256 multiplier = 1+ currentEpoch.sub(epoch); kstToken.safeTransfer( beneficiary, RELEASEAMOUNT.mul(multiplier) ); epoch = epoch.add(multiplier); } else { kstToken.safeTransfer(beneficiary, RELEASEAMOUNT); epoch = epoch.add(1); } lastClaimTime = block.timestamp; emit Claimed(RELEASEAMOUNT, epoch); } } function getClaimAmount() external view returns (uint256) { uint256 currentEpoch = getCurrentEpoch(); // get current epoch if (currentEpoch > epoch) { uint256 multiplier = 1+ currentEpoch.sub(epoch); return RELEASEAMOUNT.mul(multiplier); } else { return RELEASEAMOUNT; } } function claimDust() public { require(block.timestamp >= END_DAY, "Vesting not yet finished"); kstToken.safeTransfer( beneficiary, kstToken.balanceOf(address(this)) ); } function setBeneficiary(address _addy) external onlyOwner { require(msg.sender == beneficiary); require(_addy != address(0)); beneficiary = _addy; } }
team multisig to claim tokens
address private beneficiary = 0x27E4618E9136191410a0DF348ab881BF57551Af9;
9,855,365
[ 1, 10035, 22945, 360, 358, 7516, 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, 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, 1758, 3238, 27641, 74, 14463, 814, 273, 374, 92, 5324, 41, 8749, 2643, 41, 29, 26959, 3657, 3461, 2163, 69, 20, 4577, 5026, 28, 378, 5482, 21, 15259, 10321, 2539, 21, 12664, 29, 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 ]
./full_match/1/0x01f7D3a6c7D57f1105a1708D0EEA1434703540DD/sources/contracts/AndreQuintupleOpenEdition.sol
tokenId -> assetURI
contract AndreQuintupleOpenEdition is AdminControl, ICreatorExtensionTokenURI, ILazyDelivery, ILazyDeliveryMetadata { address private _creator; address private _marketplace; uint256[] private _tokenIds = new uint256[](5); uint[] private _listingIds = new uint[](5); uint[] private _tokenIdsToMint = new uint[](5); mapping(uint256 => string) private _assetURIs; constructor(address creator) { _creator = creator; } function initialize() public adminRequired { address[] memory addressToSend = new address[](1); addressToSend[0] = msg.sender; uint256[] memory amounts = new uint256[](1); amounts[0] = 1; string[] memory uris = new string[](1); uris[0] = ""; _tokenIds[0] = IERC1155CreatorCore(_creator).mintExtensionNew( addressToSend, amounts, uris )[0]; _tokenIds[1] = IERC1155CreatorCore(_creator).mintExtensionNew( addressToSend, amounts, uris )[0]; _tokenIds[2] = IERC1155CreatorCore(_creator).mintExtensionNew( addressToSend, amounts, uris )[0]; _tokenIds[3] = IERC1155CreatorCore(_creator).mintExtensionNew( addressToSend, amounts, uris )[0]; _tokenIds[4] = IERC1155CreatorCore(_creator).mintExtensionNew( addressToSend, amounts, uris )[0]; } function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControl, IERC165) returns (bool) { return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || interfaceId == type(ILazyDelivery).interfaceId || AdminControl.supportsInterface(interfaceId) || super.supportsInterface(interfaceId); } function setListings(address marketplace, uint listingId1, uint listingId2, uint listingId3, uint listingId4, uint listingId5, uint tokenIdToMint1, uint tokenIdToMint2, uint tokenIdToMint3, uint tokenIdToMint4, uint tokenIdToMint5) public adminRequired { _marketplace = marketplace; _listingIds[0] = listingId1; _tokenIdsToMint[0] = tokenIdToMint1; _listingIds[1] = listingId2; _tokenIdsToMint[1] = tokenIdToMint2; _listingIds[2] = listingId3; _tokenIdsToMint[2] = tokenIdToMint3; _listingIds[3] = listingId4; _tokenIdsToMint[3] = tokenIdToMint4; _listingIds[4] = listingId5; _tokenIdsToMint[4] = tokenIdToMint5; } function setListing(uint index, uint listingId, uint tokenIdToMint) public adminRequired { require(index < 5, "Index OOB"); _listingIds[index] = listingId; _tokenIdsToMint[index] = tokenIdToMint; } function deliver(address, uint256 listingId, uint256, address to, uint256, uint256) external override returns(uint256) { require(msg.sender == _marketplace && (listingId == _listingIds[0] || listingId == _listingIds[1] || listingId == _listingIds[2] || listingId == _listingIds[3] || listingId == _listingIds[4] ), "Invalid call data"); address[] memory addressToSend = new address[](1); addressToSend[0] = to; uint[] memory tokenIdToSend = new uint[](1); if (listingId == _listingIds[0]) { tokenIdToSend[0] = _tokenIdsToMint[0]; tokenIdToSend[0] = _tokenIdsToMint[1]; tokenIdToSend[0] = _tokenIdsToMint[2]; tokenIdToSend[0] = _tokenIdsToMint[3]; tokenIdToSend[0] = _tokenIdsToMint[4]; } uint[] memory amounts = new uint[](1); amounts[0] = 1; IERC1155CreatorCore(_creator).mintExtensionExisting(addressToSend, tokenIdToSend, amounts); return 1; } function deliver(address, uint256 listingId, uint256, address to, uint256, uint256) external override returns(uint256) { require(msg.sender == _marketplace && (listingId == _listingIds[0] || listingId == _listingIds[1] || listingId == _listingIds[2] || listingId == _listingIds[3] || listingId == _listingIds[4] ), "Invalid call data"); address[] memory addressToSend = new address[](1); addressToSend[0] = to; uint[] memory tokenIdToSend = new uint[](1); if (listingId == _listingIds[0]) { tokenIdToSend[0] = _tokenIdsToMint[0]; tokenIdToSend[0] = _tokenIdsToMint[1]; tokenIdToSend[0] = _tokenIdsToMint[2]; tokenIdToSend[0] = _tokenIdsToMint[3]; tokenIdToSend[0] = _tokenIdsToMint[4]; } uint[] memory amounts = new uint[](1); amounts[0] = 1; IERC1155CreatorCore(_creator).mintExtensionExisting(addressToSend, tokenIdToSend, amounts); return 1; } } else if (listingId == _listingIds[1]) { } else if (listingId == _listingIds[2]) { } else if (listingId == _listingIds[3]) { } else if (listingId == _listingIds[4]) { function setNewAssetURIs(string memory newAssetURI1, string memory newAssetURI2, string memory newAssetURI3, string memory newAssetURI4, string memory newAssetURI5) public adminRequired { _assetURIs[_tokenIds[0]] = newAssetURI1; _assetURIs[_tokenIds[1]] = newAssetURI2; _assetURIs[_tokenIds[2]] = newAssetURI3; _assetURIs[_tokenIds[3]] = newAssetURI4; _assetURIs[_tokenIds[4]] = newAssetURI5; } function setNewAssetURI(uint index, string memory newAssetURI) public adminRequired { require(index < 5, "Index OOB"); _assetURIs[_tokenIds[index]] = newAssetURI; } function assetURI(uint tokenId) external view override returns(string memory) { return _assetURIs[tokenId]; } function tokenURI(address creator, uint256 tokenId) external view override returns (string memory) { require(creator == _creator, "Invalid token"); return this.assetURI(tokenId); } }
3,866,111
[ 1, 2316, 548, 317, 3310, 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, 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, 16351, 7835, 266, 928, 474, 2268, 3678, 41, 1460, 353, 7807, 3367, 16, 467, 10636, 3625, 1345, 3098, 16, 467, 14443, 8909, 16, 467, 14443, 8909, 2277, 288, 203, 565, 1758, 3238, 389, 20394, 31, 203, 565, 1758, 3238, 389, 3355, 24577, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 389, 2316, 2673, 273, 394, 2254, 5034, 8526, 12, 25, 1769, 203, 565, 2254, 8526, 3238, 389, 21228, 2673, 273, 394, 2254, 8526, 12, 25, 1769, 203, 565, 2254, 8526, 3238, 389, 2316, 2673, 774, 49, 474, 273, 394, 2254, 8526, 12, 25, 1769, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 9406, 1099, 2520, 31, 203, 203, 203, 565, 3885, 12, 2867, 11784, 13, 288, 203, 3639, 389, 20394, 273, 11784, 31, 203, 565, 289, 203, 203, 565, 445, 4046, 1435, 1071, 3981, 3705, 288, 203, 3639, 1758, 8526, 3778, 1758, 28878, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 1758, 28878, 63, 20, 65, 273, 1234, 18, 15330, 31, 203, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 30980, 63, 20, 65, 273, 404, 31, 203, 203, 3639, 533, 8526, 3778, 21476, 273, 394, 533, 8526, 12, 21, 1769, 203, 3639, 21476, 63, 20, 65, 273, 1408, 31, 203, 203, 3639, 389, 2316, 2673, 63, 20, 65, 273, 467, 654, 39, 2499, 2539, 10636, 4670, 24899, 20394, 2934, 81, 474, 3625, 1908, 12, 203, 1850, 1758, 28878, 16, 203, 1850, 30980, 16, 203, 1850, 21476, 203, 3639, 262, 2 ]
./full_match/5/0xB56048cf5b0158A38F8B396addd1b6001Fb5FCdD/sources/contracts/ERC20R.sol
/requires you to clear all of it.require it to have data, not empty arrary
It is expected that this function is called regularly to clear the contract of any outdated unused storage data. function clean(address[] calldata addresses, uint256 epoch) external { require( block.number > NUM_REVERSIBLE_BLOCKS && (epoch + 1) * DELTA - 1 < block.number - NUM_REVERSIBLE_BLOCKS, "ERC20-R: Block Epoch is not allowed to be cleared yet." ); require( _numAddressesInEpoch[epoch] == addresses.length, "ERC20R: Must clear the entire block Epoch's data at once." ); for (uint256 i = 0; i < addresses.length; i++) { require( _spenditures[epoch][addresses[i]].length > 0 || _burns[epoch][addresses[i]].length > 0, "ERC20R: addresses to clean for block Epoch does not match the actual data storage." ); delete _spenditures[epoch][addresses[i]]; delete _burns[epoch][addresses[i]]; } _numAddressesInEpoch[epoch] = 0; emit ClearedDataInTimeblock(addresses.length, epoch); }
7,088,136
[ 1, 19, 18942, 1846, 358, 2424, 777, 434, 518, 18, 6528, 518, 358, 1240, 501, 16, 486, 1008, 2454, 814, 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, 2597, 353, 2665, 716, 333, 445, 353, 2566, 6736, 715, 358, 2424, 326, 6835, 434, 7010, 565, 1281, 25629, 10197, 2502, 501, 18, 7010, 565, 445, 2721, 12, 2867, 8526, 745, 892, 6138, 16, 2254, 5034, 7632, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 2696, 405, 9443, 67, 862, 2204, 16645, 67, 11403, 55, 597, 203, 7734, 261, 12015, 397, 404, 13, 380, 2030, 48, 9833, 300, 404, 411, 1203, 18, 2696, 300, 9443, 67, 862, 2204, 16645, 67, 11403, 55, 16, 203, 5411, 315, 654, 39, 3462, 17, 54, 30, 3914, 512, 6127, 353, 486, 2935, 358, 506, 16054, 4671, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 2107, 7148, 382, 14638, 63, 12015, 65, 422, 6138, 18, 2469, 16, 203, 5411, 315, 654, 39, 3462, 54, 30, 6753, 2424, 326, 7278, 1203, 512, 6127, 1807, 501, 622, 3647, 1199, 203, 3639, 11272, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 6138, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 203, 7734, 389, 87, 1302, 305, 1823, 63, 12015, 6362, 13277, 63, 77, 65, 8009, 2469, 405, 374, 747, 203, 10792, 389, 70, 321, 87, 63, 12015, 6362, 13277, 63, 77, 65, 8009, 2469, 405, 374, 16, 203, 7734, 315, 654, 39, 3462, 54, 30, 6138, 358, 2721, 364, 1203, 512, 6127, 1552, 486, 845, 326, 3214, 501, 2502, 1199, 203, 5411, 11272, 203, 5411, 1430, 389, 87, 1302, 305, 1823, 63, 12015, 6362, 13277, 63, 77, 13563, 31, 2 ]
pragma solidity ^0.4.5; contract PPBC_API { /******************************************************************************* PADDYPOWER.BLOCKCHAIN Promo Concept/Proposal, RFP Response / PoC Module PPBC_API - back-end module [private API], v1.22, 2016 11 27 $Id: add rcs tag $ vendor presentation/ @TowerRoom, 12/12/16 10am @MC/KC - Refer to instructions at PP Tech Vendor Portal Abstract: Blockchain Contract API Demo, providing access to 3:5 and 2:5 betting odds (3:5 for FIRST bet only, 2:5 for consecutive bets) ********************************************************************************/ // Do not invoke contract directly (API code protected), only via main PPBC contract // ToDo: protect API with passcode/hash // declare variables address paddyAdmin; // contract owner uint256 public gamesPlayed; // Game Counter mapping ( address => bool ) alreadyPlayed; // Ensure every user can only play ONCE using the 3:5 odds // to prevent abuse of benef. odds. // Consecutive games from the same account only run at 2:5 odds. /* GetMinimumBet_ether() ToDo: add doc @MC*/ /* GetMaximumBet_ether() ToDo: add doc @MC*/ // Minimum/Maximum Bet (in ETHER) that can be placed: 1 ether - 10% of available Ether Winning Pool function GetMinimumBet_Ether() constant returns (uint256){ return 1; } function GetMaximumBet_Ether() constant returns (uint256){ return GetMaximumBet() / 1000000000000000000; } function GetMinimumBet() returns (uint256) { return 1 ether; } // Minimum Bet that can be placed: 1 ether function GetMaximumBet() returns (uint256) { return this.balance/10; } // Maximum Bet that can be placed: 10% of available Ether Winning Pool /* PlaceBet using Access Code, and Mode parameter */ /******************************************************************** First game for any account will run at 3:5 odds (double win). Consecutive game for any account will run at 2:5 odds (double win). Cannot be invoked directly, only via PaddyPowerPromo contract MC Parameters: - Access Code is SHA3 hashed code, provided by PaddyPowerPromo contract (prevents direct call). *******************************************************************************************/ function _api_PlaceBet () payable { //function _api_PlaceBet (uint256 accessCode, bool modeA) payable { // // Note total transaction cost ~ 100-200K Gas // START Initial checks // use Sha3 for increased API security (cannot be "converted back" to original accessCode) - prevents direct access // if ( sha3( accessCode ) != 19498834600303040700126754596537880312193431075463488515213744382615666721600) throw; // @MC disabled access check for PoC, ToDo: enable for Prod release, and allow change of hash if compromised // Check if Bet amount is within limits 1 ether to 10% of winning pool (account) balance if (msg.value < GetMinimumBet() || (msg.value + 1) > GetMaximumBet() ) throw; // Only allow x games per block - to ensure outcome is as random as possible uint256 cntBlockUsed = blockUsed[block.number]; if (cntBlockUsed > maxGamesPerBlock) throw; blockUsed[block.number] = cntBlockUsed + 1; gamesPlayed++; // game counter lastPlayer = msg.sender; // remember last player, part of seed for random number generator // END initial checks // START - Set winning odds uint winnerOdds = 3; // 3 out of 5 win (for first game) uint totalPartition = 5; if (alreadyPlayed[msg.sender]){ // has user played before? then odds are 2:5, not 3:5 winnerOdds = 2; } alreadyPlayed[msg.sender] = true; // remember that user has already played for next time // expand partitions to % (minimizes rounding), calculate winning change in % (x out of 100) winnerOdds = winnerOdds * 20; // 3*20 = 60% winning chance, or 2*20 = 40% winning chance totalPartition = totalPartition * 20; // 5*20 = 100% // END - Set winning odds // Create new random number uint256 random = createRandomNumber(totalPartition); // creates a random number between 0 and 99 // check if user won if (random <= winnerOdds ){ if (!msg.sender.send(msg.value * 2)) // winner double throw; // roll back if there was an error } // GAME FINISHED. } /////////////////////////////////////////////// // Random Number Generator ////////////////////////////////////////////// address lastPlayer; uint256 private seed1; uint256 private seed2; uint256 private seed3; uint256 private seed4; uint256 private seed5; uint256 private lastBlock; uint256 private lastRandom; uint256 private lastGas; uint256 private customSeed; function createRandomNumber(uint maxnum) payable returns (uint256) { uint cnt; for (cnt = 0; cnt < lastRandom % 5; cnt++){lastBlock = lastBlock - block.timestamp;} // randomize gas uint256 random = block.difficulty + block.gaslimit + block.timestamp + msg.gas + msg.value + tx.gasprice + seed1 + seed2 + seed3 + seed4 + seed5; random = random + uint256(block.blockhash(block.number - (lastRandom+1))[cnt]) + (gamesPlayed*1234567890) * lastBlock + customSeed; random = random + uint256(lastPlayer) + uint256(sha3(msg.sender)[cnt]); lastBlock = block.number; seed5 = seed4; seed4 = seed3; seed3 = seed2; seed2 = seed1; seed1 = (random / 43) + lastRandom; bytes32 randomsha = sha3(random); lastRandom = (uint256(randomsha[cnt]) * maxnum) / 256; return lastRandom ; } /////////////////////////////////////////////// // Maintenance ToDo: doc @MC ///////////////////////////// uint256 public maxGamesPerBlock; // Block limit mapping ( uint256 => uint256 ) blockUsed; // prevent more than X games per block; // function PPBC_API() { // Constructor: ToDo: obfuscate //initialize gamesPlayed = 0; paddyAdmin = msg.sender; lastPlayer = msg.sender; seed1 = 2; seed2 = 3; seed3 = 5; seed4 = 7; seed5 = 11; lastBlock = 0; customSeed = block.number; maxGamesPerBlock = 3; } modifier onlyOwner { if (msg.sender != paddyAdmin) throw; _; } function _maint_withdrawFromPool (uint256 amt) onlyOwner{ // balance to stay below approved limit / comply with regulation if (!paddyAdmin.send(amt)) throw; } function () payable onlyOwner { // default function, used by PaddyAdmin to deposit into winning pool, only owner can do this } function _maint_EndPromo () onlyOwner { selfdestruct(paddyAdmin); } function _maint_setBlockLimit (uint256 n_limit) onlyOwner { maxGamesPerBlock = n_limit; } function _maint_setCustomSeed(uint256 newSeed) onlyOwner { customSeed = newSeed; } function _maint_updateOwner (address newOwner) onlyOwner { paddyAdmin = newOwner; } }
has user played before? then odds are 2:5, not 3:5
if (alreadyPlayed[msg.sender]){
2,491,945
[ 1, 5332, 729, 6599, 329, 1865, 35, 1508, 14800, 87, 854, 576, 30, 25, 16, 486, 890, 30, 25, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 17583, 11765, 329, 63, 3576, 18, 15330, 5717, 95, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x84524bAa1951247b3A2617A843e6eCe915Bb9674/sources/contracts/MainHelper.sol
* @dev Returns bool to determine if resonance factor needs to be reset to last best value./
function _resonanceOutcome( address _poolToken, uint256 _shareValue ) private view returns (bool) { return _shareValue < THRESHOLD_RESET_RESONANCE_FACTOR * algorithmData[_poolToken].maxValue / PRECISION_FACTOR_E18; }
8,497,312
[ 1, 1356, 1426, 358, 4199, 309, 400, 265, 1359, 5578, 4260, 358, 506, 2715, 358, 1142, 3796, 460, 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 ]
[ 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, 389, 455, 265, 1359, 19758, 12, 203, 3639, 1758, 389, 6011, 1345, 16, 203, 3639, 2254, 5034, 389, 14419, 620, 203, 565, 262, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 14419, 620, 411, 7662, 20798, 67, 26665, 67, 862, 1413, 4722, 67, 26835, 203, 5411, 380, 4886, 751, 63, 67, 6011, 1345, 8009, 1896, 620, 203, 5411, 342, 7071, 26913, 67, 26835, 67, 41, 2643, 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 ]
./partial_match/1/0x4A84DC0618e733c688E58Ddf5F354B3DEaF4f78a/sources/contracts/soma/TemplateFactory/ITemplateFactory.sol
* @title SOMA Template Factory Contract. @author SOMA.finance. @notice Interface of the {TemplateFactory} contract./
interface ITemplateFactory { event TemplateVersionCreated( bytes32 indexed templateId, uint256 indexed version, address implementation, address indexed sender ); event DeployRoleUpdated(bytes32 indexed templateId, bytes32 prevRole, bytes32 newRole, address indexed sender); event TemplateEnabled(bytes32 indexed templateId, address indexed sender); event TemplateDisabled(bytes32 indexed templateId, address indexed sender); event TemplateVersionDeprecated(bytes32 indexed templateId, uint256 indexed version, address indexed sender); event TemplateVersionUndeprecated(bytes32 indexed templateId, uint256 indexed version, address indexed sender); event TemplateDeployed( address indexed instance, bytes32 indexed templateId, uint256 version, bytes args, bytes[] functionCalls, address indexed sender ); event TemplateCloned( address indexed instance, bytes32 indexed templateId, uint256 version, bytes[] functionCalls, address indexed sender ); event FunctionCalled(address indexed target, bytes data, bytes result, address indexed sender); struct Version { bool deprecated; address implementation; bytes creationCode; uint256 totalParts; uint256 partsUploaded; address[] instances; } struct Template { bool disabled; bytes32 deployRole; Version[] versions; address[] instances; } struct DeploymentInfo { bool exists; uint64 block; uint64 timestamp; address sender; bytes32 templateId; uint256 version; bytes args; bytes[] functionCalls; bool cloned; } }
9,367,423
[ 1, 55, 1872, 37, 5035, 7822, 13456, 18, 225, 348, 1872, 37, 18, 926, 1359, 18, 225, 6682, 434, 326, 288, 2283, 1733, 97, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 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, 5831, 467, 2283, 1733, 288, 203, 565, 871, 5035, 1444, 6119, 12, 203, 3639, 1731, 1578, 8808, 1542, 548, 16, 2254, 5034, 8808, 1177, 16, 1758, 4471, 16, 1758, 8808, 5793, 203, 565, 11272, 203, 203, 565, 871, 7406, 2996, 7381, 12, 3890, 1578, 8808, 1542, 548, 16, 1731, 1578, 2807, 2996, 16, 1731, 1578, 394, 2996, 16, 1758, 8808, 5793, 1769, 203, 203, 565, 871, 5035, 1526, 12, 3890, 1578, 8808, 1542, 548, 16, 1758, 8808, 5793, 1769, 203, 203, 565, 871, 5035, 8853, 12, 3890, 1578, 8808, 1542, 548, 16, 1758, 8808, 5793, 1769, 203, 203, 565, 871, 5035, 1444, 13534, 12, 3890, 1578, 8808, 1542, 548, 16, 2254, 5034, 8808, 1177, 16, 1758, 8808, 5793, 1769, 203, 203, 565, 871, 5035, 1444, 984, 14089, 12, 3890, 1578, 8808, 1542, 548, 16, 2254, 5034, 8808, 1177, 16, 1758, 8808, 5793, 1769, 203, 203, 565, 871, 5035, 31954, 12, 203, 3639, 1758, 8808, 791, 16, 203, 3639, 1731, 1578, 8808, 1542, 548, 16, 203, 3639, 2254, 5034, 1177, 16, 203, 3639, 1731, 833, 16, 203, 3639, 1731, 8526, 445, 10125, 16, 203, 3639, 1758, 8808, 5793, 203, 565, 11272, 203, 203, 565, 871, 5035, 2009, 8184, 12, 203, 3639, 1758, 8808, 791, 16, 203, 3639, 1731, 1578, 8808, 1542, 548, 16, 203, 3639, 2254, 5034, 1177, 16, 203, 3639, 1731, 8526, 445, 10125, 16, 203, 3639, 1758, 8808, 5793, 203, 565, 11272, 203, 203, 565, 871, 4284, 8185, 12, 2867, 8808, 1018, 16, 1731, 501, 16, 1731, 563, 16, 1758, 8808, 5793, 1769, 2 ]
./full_match/80001/0x1Bf5a4B71E284705E81cEe233f76AC938340558f/sources/contracts/market/template/MarketTieredLeverage.sol
@notice Returns the redeem action in synthetic tokens of provided user for the given poolType and poolTier. @dev Action amounts have a fixed 18 decimals. @param user Address of the user. @param poolType an enum representing the type of poolTier for eg. LONG or SHORT. @param poolTier The index of the pool in the side. @return user_syntheticToken_redeemAction Outstanding redeem action by user for the given poolType and poolTier.
function user_syntheticToken_redeemAction( address user, IMarketCommon.PoolType poolType, uint256 poolTier ) external view returns (IMarketCommon.UserAction memory) { return _user_syntheticToken_redeemAction[user][poolType][poolTier]; }
9,520,538
[ 1, 1356, 326, 283, 24903, 1301, 316, 25535, 2430, 434, 2112, 729, 364, 326, 864, 2845, 559, 471, 2845, 15671, 18, 225, 4382, 30980, 1240, 279, 5499, 6549, 15105, 18, 225, 729, 5267, 434, 326, 729, 18, 225, 2845, 559, 392, 2792, 5123, 326, 618, 434, 2845, 15671, 364, 9130, 18, 14011, 578, 20079, 18, 225, 2845, 15671, 1021, 770, 434, 326, 2845, 316, 326, 4889, 18, 327, 729, 67, 11982, 16466, 1345, 67, 266, 24903, 1803, 2976, 15167, 283, 24903, 1301, 635, 729, 364, 326, 864, 2845, 559, 471, 2845, 15671, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 729, 67, 11982, 16466, 1345, 67, 266, 24903, 1803, 12, 203, 565, 1758, 729, 16, 203, 565, 467, 3882, 278, 6517, 18, 2864, 559, 2845, 559, 16, 203, 565, 2254, 5034, 2845, 15671, 203, 225, 262, 3903, 1476, 1135, 261, 3445, 1313, 278, 6517, 18, 1299, 1803, 3778, 13, 288, 203, 565, 327, 389, 1355, 67, 11982, 16466, 1345, 67, 266, 24903, 1803, 63, 1355, 6362, 6011, 559, 6362, 6011, 15671, 15533, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.7.0 <0.9.0; contract Signatory { address public serviceContractAddress; event AddedSignatory(string indexed name, string indexed key); event RemovedSignatory(string indexed name, string indexed key); // Initializing service contract address in constructor constructor(){ serviceContractAddress = 0xA6Abc17819738299B3B2c1CE46d55c74f04E290C; } // Adds a signatory function addSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "addSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit AddedSignatory(name, key); result = ret; } // Removes a signatory function removeSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "removeSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit RemovedSignatory(name, key); result = ret; } // Gets signatories of account function getSignatories(string memory name) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getSignatories(string)", name); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } }
Initializing service contract address in constructor
contract Signatory { address public serviceContractAddress; event AddedSignatory(string indexed name, string indexed key); event RemovedSignatory(string indexed name, string indexed key); constructor(){ serviceContractAddress = 0xA6Abc17819738299B3B2c1CE46d55c74f04E290C; } function addSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "addSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit AddedSignatory(name, key); result = ret; } function removeSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "removeSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit RemovedSignatory(name, key); result = ret; } function getSignatories(string memory name) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getSignatories(string)", name); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } }
13,122,594
[ 1, 29782, 1156, 6835, 1758, 316, 3885, 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, 16351, 4383, 8452, 288, 203, 565, 1758, 1071, 1156, 8924, 1887, 31, 203, 203, 565, 871, 25808, 2766, 8452, 12, 1080, 8808, 508, 16, 533, 8808, 498, 1769, 203, 565, 871, 2663, 9952, 2766, 8452, 12, 1080, 8808, 508, 16, 533, 8808, 498, 1769, 203, 203, 203, 565, 3885, 1435, 95, 203, 3639, 1156, 8924, 1887, 273, 374, 21703, 26, 5895, 71, 4033, 28, 31728, 7414, 22, 2733, 38, 23, 38, 22, 71, 21, 1441, 8749, 72, 2539, 71, 5608, 74, 3028, 41, 5540, 20, 39, 31, 203, 565, 289, 203, 203, 565, 445, 527, 2766, 8452, 12, 1080, 3778, 508, 16, 533, 3778, 498, 13, 1071, 1135, 261, 3890, 3778, 563, 13, 288, 203, 3639, 1731, 3778, 2385, 273, 24126, 18, 3015, 1190, 5374, 12, 203, 5411, 315, 1289, 2766, 8452, 12, 1080, 16, 1080, 2225, 16, 203, 5411, 508, 16, 203, 5411, 498, 1769, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 325, 13, 273, 1758, 12, 3278, 8924, 1887, 2934, 22216, 1991, 12, 7648, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 668, 4440, 1156, 6835, 445, 8863, 203, 3639, 3626, 25808, 2766, 8452, 12, 529, 16, 498, 1769, 203, 3639, 563, 273, 325, 31, 203, 565, 289, 203, 203, 565, 445, 1206, 2766, 8452, 12, 1080, 3778, 508, 16, 533, 3778, 498, 13, 1071, 1135, 261, 3890, 3778, 563, 13, 288, 203, 3639, 1731, 3778, 2385, 273, 24126, 18, 3015, 1190, 5374, 12, 203, 5411, 315, 4479, 2766, 8452, 12, 1080, 16, 1080, 2225, 16, 203, 5411, 508, 16, 203, 2 ]
/* This file is part of the DAO. The DAO is free software: you can redistribute it and/or modify it under the terms of the GNU lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The DAO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU lesser General Public License for more details. You should have received a copy of the GNU lesser General Public License along with the DAO. If not, see <http://www.gnu.org/licenses/>. */ /* Basic account, used by the DAO contract to separately manage both the rewards and the extraBalance accounts. */ abstract contract ManagedAccountInterface { // The only address with permission to withdraw from this account address public owner; // If true, only the owner of the account can receive ether from it bool public payOwnerOnly; // The sum of ether (in wei) which has been sent to this contract uint public accumulatedInput; /// @notice Sends `_amount` of wei to _recipient /// @param _amount The amount of wei to send to `_recipient` /// @param _recipient The address to receive `_amount` of wei /// @return True if the send completed function payOut(address payable _recipient, uint _amount) public virtual returns (bool); event PayOut(address indexed _recipient, uint _amount); } contract ManagedAccount is ManagedAccountInterface{ // The constructor sets the owner of the account constructor(address _owner, bool _payOwnerOnly) public { owner = _owner; payOwnerOnly = _payOwnerOnly; } // When the contract receives a transaction without data this is called. // It counts the amount of ether it receives and stores it in // accumulatedInput. receive() external payable { accumulatedInput += msg.value; } function payOut(address payable _recipient, uint _amount) public override returns (bool) { if (msg.sender != owner || (payOwnerOnly && _recipient != owner)) revert(); (bool success,) = _recipient.call.value(_amount)(""); if (success) { emit PayOut(_recipient, _amount); return true; } else { return false; } } }
When the contract receives a transaction without data this is called. It counts the amount of ether it receives and stores it in accumulatedInput.
receive() external payable { accumulatedInput += msg.value; }
12,829,163
[ 1, 9434, 326, 6835, 17024, 279, 2492, 2887, 501, 333, 353, 2566, 18, 2597, 6880, 326, 3844, 434, 225, 2437, 518, 17024, 471, 9064, 518, 316, 24893, 1210, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 24893, 1210, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]